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.

perf(share): make the Share dialog open immediately (#8841)

Jacob Beckermanc3b042df167a
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.test.tsx
new file mode 100644
index 0000000000..13916227b8
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.test.tsx
@@ -0,0 +1,38 @@
+import { render } from '@solidjs/testing-library';
+import type { LexicalEditor } from 'lexical';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createMenuOperations } from '../../../shared/inlineMenu';
+import { SnippetsMenu } from './SnippetsMenu';
+
+const mocks = vi.hoisted(() => ({ readSnippets: vi.fn(() => []) }));
+
+vi.mock('../MentionsMenu/hooks/useEntityMention', () => ({
+ useEntityMention: () => ({ entities: mocks.readSnippets }),
+}));
+vi.mock('@app/lib/analytics/analytics-context', () => ({
+ useAnalytics: () => ({ track: vi.fn() }),
+}));
+vi.mock('@queries/storage/snippets', () => ({ fetchSnippetRaw: vi.fn() }));
+vi.mock('../../../directive/floatWithSelection', () => ({
+ floatWithSelection: () => {},
+}));
+
+const editor = {
+ dispatchCommand: vi.fn(),
+ getRootElement: () => null,
+} as unknown as LexicalEditor;
+
+afterEach(() => mocks.readSnippets.mockClear());
+
+describe('SnippetsMenu', () => {
+ // Snippets come from the app-wide Quick Access index, which a first read
+ // builds over every item; every composer mounts this menu closed.
+ it('reads snippets only once the menu opens', async () => {
+ const menu = createMenuOperations();
+ render(() => <SnippetsMenu editor={editor} menu={menu} />);
+ expect(mocks.readSnippets).not.toHaveBeenCalled();
+
+ menu.openMenu();
+ await vi.waitFor(() => expect(mocks.readSnippets).toHaveBeenCalled());
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx
index a8a9bd2b92..3f58584482 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx
@@ -98,7 +98,10 @@ function SnippetsMenuInner(props: SnippetsMenuProps) {
setSelectedIndex(0);
});
+ // Reading snippets builds the whole Quick Access index, so a closed menu
+ // must not: every composer mounts one.
createEffect(() => {
+ if (!menuOpen()) return;
const count = filteredSnippets().length;
if (count > 0 && selectedIndex() >= count) {
setSelectedIndex(count - 1);
diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
index 30b4773b44..6ac2ea4588 100644
--- a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
@@ -1,5 +1,11 @@
import { ForwardToChannel } from '@core/component/ForwardToChannel';
-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import {
+ render as baseRender,
+ cleanup,
+ fireEvent,
+ screen,
+} from '@solidjs/testing-library';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
import { err, ok } from 'neverthrow';
import { createSignal, For, type JSX, onCleanup } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -61,6 +67,17 @@ vi.mock(
})
);
+let queryClient = new QueryClient();
+// The dialog reads share permissions through a query outside a block.
+const render = (ui: () => JSX.Element) =>
+ baseRender(ui, {
+ wrapper: (props) => (
+ <QueryClientProvider client={queryClient}>
+ {props.children}
+ </QueryClientProvider>
+ ),
+ });
+
const ME = 'macro|[email protected]';
const SOMEONE_ELSE = 'macro|[email protected]';
@@ -409,6 +426,9 @@ vi.mock('@ui', async () => {
};
});
beforeEach(() => {
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
vi.clearAllMocks();
mocks.meetingNotesFlag = () => ({ enabled: true, loading: false });
mocks.inBlock = true;
@@ -557,11 +577,72 @@ function mountShare(isOwner: boolean) {
));
return { onOpenChange, onCopyLink };
}
-const selectChannel = () =>
- fireEvent.click(screen.getByRole('button', { name: 'Select channel' }));
+// The share form mounts after the dialog first paints.
+const selectChannel = async () =>
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Select channel' })
+ );
const share = () =>
fireEvent.click(screen.getByRole('button', { name: 'Share' }));
+it('opens before its share form, then mounts the form', async () => {
+ mountShare(true);
+ expect(screen.getByText('Fix the menu')).toBeTruthy();
+ expect(
+ screen.getByRole('status', { name: 'Loading share form' })
+ ).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Select channel' })).toBeNull();
+
+ expect(
+ await screen.findByRole('button', { name: 'Select channel' })
+ ).toBeTruthy();
+ expect(
+ screen.queryByRole('status', { name: 'Loading share form' })
+ ).toBeNull();
+});
+
+it('shows a placeholder, not "Just me", while link sharing loads', async () => {
+ mocks.inBlock = false;
+ let resolve!: (value: unknown) => void;
+ mocks.getDocumentPermissions.mockReturnValue(
+ new Promise((r) => {
+ resolve = r;
+ })
+ );
+ render(() => (
+ <ShareModal
+ id="slow-document"
+ name="Plan"
+ owner={ME}
+ itemType="document"
+ blockAlias="md"
+ userPermissions={Permissions.OWNER}
+ open
+ onOpenChange={vi.fn()}
+ />
+ ));
+ expect(
+ screen.getByRole('status', { name: 'Loading link sharing' })
+ ).toBeTruthy();
+ expect(
+ screen.queryByRole('group', { name: 'Link sharing scope' })
+ ).toBeNull();
+
+ resolve(
+ ok({
+ linkShare: 'PUBLIC',
+ linkShareAccessLevel: 'view',
+ channelSharePermissions: [],
+ })
+ );
+ expect(
+ await screen.findByRole('group', { name: 'Link sharing scope' })
+ ).toBeTruthy();
+ expect(
+ screen.queryByRole('status', { name: 'Loading link sharing' })
+ ).toBeNull();
+});
+
describe('agent session sharing', () => {
it.each([false, true])(
'offers Edit for forwarding, people, and links when the legacy block disables editing (mobile: %s)',
@@ -587,7 +668,7 @@ describe('agent session sharing', () => {
);
fireEvent.click(editOptions()[0]);
- selectChannel();
+ await selectChannel();
share();
await vi.waitFor(() =>
expect(mocks.updateAgentPermissions).toHaveBeenCalledWith(
@@ -640,7 +721,9 @@ describe('agent session sharing', () => {
mountShare(true);
if (mobile) fireEvent.click(screen.getByRole('tab', { name: 'Link' }));
- fireEvent.click(screen.getByRole('button', { name: 'Set link PUBLIC' }));
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Set link PUBLIC' })
+ );
await vi.waitFor(() =>
expect(mocks.updateAgentPermissions).toHaveBeenCalledWith(
'persisted-session',
@@ -678,11 +761,11 @@ describe('agent session sharing', () => {
it.each([false, true])(
'shows the standard share form for owners (mobile: %s)',
- (mobile) => {
+ async (mobile) => {
mocks.mobile = mobile;
mountShare(true);
expect(
- screen.getByRole('button', { name: 'Select channel' })
+ await screen.findByRole('button', { name: 'Select channel' })
).toBeTruthy();
expect(screen.getByRole('button', { name: 'Share' })).toBeTruthy();
if (mobile) {
@@ -693,7 +776,7 @@ describe('agent session sharing', () => {
screen.getByText('People with access to this agent session')
).toBeTruthy();
expect(
- screen.getByRole('group', { name: 'Link sharing scope' })
+ await screen.findByRole('group', { name: 'Link sharing scope' })
).toBeTruthy();
}
expect(
@@ -704,6 +787,22 @@ describe('agent session sharing', () => {
}
);
+ it('loads sharing when Share gains focus, before it is opened', async () => {
+ mocks.inBlock = false;
+ mocks.getDocumentPermissions.mockResolvedValue(
+ ok({ channelSharePermissions: [] })
+ );
+ render(() => (
+ <ShareTrigger onClick={vi.fn()} id="focus-prefetch" blockType="md" />
+ ));
+ fireEvent.focusIn(screen.getByRole('button', { name: 'Share' }));
+ await vi.waitFor(() =>
+ expect(mocks.getDocumentPermissions).toHaveBeenCalledWith({
+ document_id: 'focus-prefetch',
+ })
+ );
+ });
+
it('uses explicit identity outside a block', () => {
mocks.inBlock = false;
render(() => (
@@ -783,7 +882,7 @@ describe('agent session sharing', () => {
expect(mocks.getChatPermissions).not.toHaveBeenCalled();
expect(mocks.getProjectPermissions).not.toHaveBeenCalled();
expect(mocks.getAgentPermissions).toHaveBeenCalledWith('persisted-session');
- selectChannel();
+ await selectChannel();
share();
expect(mocks.sendToChannel).toHaveBeenCalledWith({
attachments: [
@@ -868,26 +967,26 @@ describe('agent session sharing', () => {
}
);
- it('cancels an owner draft without sharing', () => {
+ it('cancels an owner draft without sharing', async () => {
const { onOpenChange } = mountShare(true);
- selectChannel();
+ await selectChannel();
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(onOpenChange).toHaveBeenCalledWith(false);
expect(mocks.sendToChannel).not.toHaveBeenCalled();
});
- it('provides a working Share action on mobile', () => {
+ it('provides a working Share action on mobile', async () => {
mocks.mobile = true;
mountShare(true);
- const button = screen.getByRole('button', { name: 'Share' });
+ const button = await screen.findByRole('button', { name: 'Share' });
expect(button.hasAttribute('disabled')).toBe(true);
- selectChannel();
+ await selectChannel();
expect(button.hasAttribute('disabled')).toBe(false);
share();
expect(mocks.sendToChannel).toHaveBeenCalledOnce();
});
- it('keeps context identity for existing forwarding callers without overrides', () => {
+ it('keeps context identity for existing forwarding callers without overrides', async () => {
render(() => <ForwardToChannel name="Document" hideAccessLevelSelector />);
- selectChannel();
+ await selectChannel();
share();
expect(mocks.sendToChannel).toHaveBeenCalledWith(
expect.objectContaining({
@@ -897,7 +996,7 @@ describe('agent session sharing', () => {
})
);
});
- it('uses the current explicit identity if it changes while mounted', () => {
+ it('uses the current explicit identity if it changes while mounted', async () => {
const [id, setId] = createSignal('old-session');
render(() => (
<ForwardToChannel
@@ -908,7 +1007,7 @@ describe('agent session sharing', () => {
/>
));
setId('new-session');
- selectChannel();
+ await selectChannel();
share();
expect(mocks.sendToChannel).toHaveBeenCalledWith(
expect.objectContaining({
@@ -990,7 +1089,7 @@ function mountCallShare() {
}
describe('call team sharing', () => {
- it('hides team access for a standalone call even when stale permissions claim it is shared', () => {
+ it('hides team access for a standalone call even when stale permissions claim it is shared', async () => {
mocks.hasTeam = true;
mocks.callRecordChannelId = null;
mountCallShare();
@@ -999,7 +1098,7 @@ describe('call team sharing', () => {
expect(
screen.queryByRole('group', { name: 'Team access level' })
).toBeNull();
- expect(screen.getByRole('button', { name: 'Share' })).toBeTruthy();
+ expect(await screen.findByRole('button', { name: 'Share' })).toBeTruthy();
expect(mocks.updateCallTeamShare).not.toHaveBeenCalled();
});
@@ -1080,15 +1179,15 @@ describe('call team sharing', () => {
expect(mocks.updateCallTeamShare).not.toHaveBeenCalled();
});
- it('loads team access from the call record outside a block', () => {
+ it('loads team access from the call record outside a block', async () => {
mocks.inBlock = false;
mocks.hasTeam = true;
mountCallShare();
expect(
- screen
- .getByRole('group', { name: 'Team access level' })
- .getAttribute('data-value')
+ (
+ await screen.findByRole('group', { name: 'Team access level' })
+ ).getAttribute('data-value')
).toBe('view');
expect(mocks.fetchCallSharePermission).not.toHaveBeenCalled();
});
@@ -1329,7 +1428,7 @@ describe('native project sharing', () => {
return { channelId: input.channelId, navigateToChannel: vi.fn() };
});
mountProject();
- selectChannel();
+ await selectChannel();
share();
await vi.waitFor(() => expect(order).toEqual(['grant', 'message']));
expect(mocks.sendToChannel.mock.calls[0][0].attachments).toEqual([
@@ -1359,7 +1458,7 @@ describe('native project sharing', () => {
return { channelId: input.channelId, navigateToChannel: vi.fn() };
});
mountProject();
- selectChannel();
+ await selectChannel();
share();
const { toast } = await import('@core/component/Toast/Toast');
await vi.waitFor(() =>
@@ -1426,7 +1525,7 @@ describe('native project sharing', () => {
it.each([false, true])(
'lists direct collaborators among the people with access (mobile: %s)',
- (mobile) => {
+ async (mobile) => {
mocks.mobile = mobile;
mountProject({
people: () => <div>Collaborator row</div>,
@@ -1439,7 +1538,7 @@ describe('native project sharing', () => {
).toBeTruthy();
expect(screen.getByText('Collaborator row')).toBeTruthy();
if (mobile) fireEvent.click(screen.getByRole('tab', { name: 'Link' }));
- expect(screen.getByText('Shared')).toBeTruthy();
+ expect(await screen.findByText('Shared')).toBeTruthy();
}
);
@@ -1502,7 +1601,7 @@ describe('pipeline sharing', () => {
});
mountPipeline();
expect(screen.queryByText(/Only editors can share/)).toBeNull();
- selectChannel();
+ await selectChannel();
share();
await vi.waitFor(() => expect(order).toEqual(['grant', 'message']));
expect(mocks.sendToChannel.mock.calls[0][0].attachments).toEqual([
@@ -1526,7 +1625,7 @@ describe('pipeline sharing', () => {
{ channel_id: 'channel-1', access_level: 'edit' },
]);
expect(
- screen.getByRole('button', { name: 'Select channel' })
+ await screen.findByRole('button', { name: 'Select channel' })
).toBeTruthy();
expect(
screen.queryByRole('group', { name: 'Team access level' })
@@ -1566,7 +1665,8 @@ describe('pipeline sharing', () => {
return ok({});
});
mountPipeline();
- if (mobile) fireEvent.click(screen.getByRole('tab', { name: 'Team' }));
+ if (mobile)
+ fireEvent.click(await screen.findByRole('tab', { name: 'Team' }));
const control = await screen.findByRole('group', {
name: 'Team access level',
});
diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
index 67c846213f..8cab82cd21 100644
--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
@@ -1,3 +1,4 @@
+import { ListSkeleton } from '@app/components/view-shell/ListSkeleton';
import {
AccessRequestError,
DirectAccessView,
@@ -14,7 +15,6 @@ import {
import type { MeetingAccessState } from '@app/features/calendar-notes/core/types';
import { DocumentMeetingNotes } from '@app/features/calendar-notes/document-meeting-notes';
import {
- fetchPipelineSharePermissions,
updatePipelineSharePermissions,
updatePipelineTeamShare,
} from '@app/features/crm/sharing-adapter';
@@ -75,32 +75,29 @@ import IconEdit from '@phosphor/pencil.svg';
import UserCircle from '@phosphor/user-circle.svg';
import UsersIcon from '@phosphor/users.svg';
import IconX from '@phosphor/x.svg';
-import {
- fetchAgentSessionSharePermissions,
- updateAgentSessionSharePermissions,
-} from '@queries/agent-session/share-permissions';
+import { updateAgentSessionSharePermissions } from '@queries/agent-session/share-permissions';
import {
setCallRecordTeamShareCache,
sharePermissionFromCallRecord,
updateCallTeamShare,
useCallRecordQuery,
} from '@queries/call/call';
+import { updateInitiativeSharePermissions } from '@queries/initiative/share-permissions';
import {
- fetchInitiativeSharePermissions,
- updateInitiativeSharePermissions,
-} from '@queries/initiative/share-permissions';
-import {
- getDatabaseSharePermissions,
- updateDatabaseSharePermissions,
-} from '@queries/storage/databases';
+ fetchSharePermissions,
+ invalidateSharePermissions,
+ prefetchShareChannelNames,
+ prefetchSharePermissions,
+ shareChannelNamesQueryOptions,
+ sharedChannelIds,
+ sharePermissionsQueryOptions,
+} from '@queries/share/share-permissions';
+import { updateDatabaseSharePermissions } from '@queries/storage/databases';
import {
updateEntitySharePolicy,
usesGraphqlSharePolicy,
} from '@queries/storage/entity-mutations';
-import {
- getFormSharePermissions,
- updateFormSharePermissions,
-} from '@queries/storage/forms';
+import { updateFormSharePermissions } from '@queries/storage/forms';
import { useCurrentTeamQuery } from '@queries/team/teams';
import { cognitionApiServiceClient } from '@service-cognition/client';
import {
@@ -112,6 +109,7 @@ import type { LinkShare } from '@service-storage/generated/schemas/linkShare';
import type { SharePermissionV2ChannelSharePermissions } from '@service-storage/generated/schemas/sharePermissionV2ChannelSharePermissions';
import { createCallback } from '@solid-primitives/rootless';
import { useNavigate } from '@solidjs/router';
+import { useQuery, useQueryClient } from '@tanstack/solid-query';
import {
Button,
CopyButton,
@@ -127,12 +125,13 @@ import {
type Component,
type ComponentProps,
createMemo,
- createResource,
createSignal,
For,
+ type JSX,
Match,
onCleanup,
onMount,
+ type ParentProps,
Show,
Switch,
} from 'solid-js';
@@ -191,30 +190,6 @@ export function shareLevelsFor(
return itemType === 'form' ? ['view', 'edit'] : undefined;
}
-async function fetchSharePermissions(id: string, itemType: ShareItemType) {
- if (itemType === 'crm_pipeline') return fetchPipelineSharePermissions(id);
- if (itemType === 'agent_session') {
- return fetchAgentSessionSharePermissions(id);
- }
- if (itemType === 'initiative') {
- return fetchInitiativeSharePermissions(id);
- }
- if (itemType === 'database') return getDatabaseSharePermissions(id);
- if (itemType === 'form') return getFormSharePermissions(id);
- if (itemType === 'chat') {
- return cognitionApiServiceClient.getChatPermissions({ id });
- }
- if (itemType === 'document') {
- return storageServiceClient.getDocumentPermissions({ document_id: id });
- }
- if (itemType === 'project') {
- if (id === 'trash') {
- return;
- }
- return storageServiceClient.projects.getPermissions({ id });
- }
-}
-
const SHARE_LINK_SUBTEXT =
'Sending this link in a Macro message will automatically update permissions to include recipients.';
@@ -313,6 +288,7 @@ const accessLevelText = (accessLevel?: AccessLevel | null) => {
const [refetchArray, setRefetchArray] = createSignal<(() => void)[]>([]);
export const refetchDocumentShareButtonResource = () => {
+ invalidateSharePermissions();
const refetchArray_ = refetchArray();
if (refetchArray_.length === 0) {
console.warn('no document share permission refetch functions initialized');
@@ -423,6 +399,8 @@ interface LinkSharingControlsProps {
setLinkShareAccessLevel: (accessLevel: AccessLevel | null) => void;
copyLink: () => void;
teamShare?: TeamShareControls;
+ /** The current link setting is still loading; don't show it as off. */
+ loading?: boolean;
}
/** Owner-only explicit team sharing, present only for entity types that support it. */
@@ -529,60 +507,135 @@ function LinkSharingControls(props: LinkSharingControlsProps) {
};
return (
- <div class="flex flex-col gap-3 p-4 text-sm text-ink">
- <div class="flex flex-wrap items-center justify-between gap-3">
- <div class="flex items-center gap-2">
- <span class="font-medium">{scopeCopy().title}</span>
- <Tooltip label={shareStatus().tooltip}>
- <div
- class={cn(
- 'flex items-center justify-center rounded-xl border px-2 py-0.5',
- shareStatus().label === 'Just me'
- ? 'border-edge-muted bg-edge-muted text-ink-extra-muted'
- : 'border-accent/30 bg-accent/10 text-accent'
- )}
- >
- <span class="text-xs font-medium whitespace-nowrap">
- {shareStatus().label}
- </span>
- </div>
- </Tooltip>
- </div>
- <Tabs
- touch="segmented"
- aria-label="Link sharing scope"
- size="sm"
- value={scope()}
- options={LINK_SHARE_SCOPE_OPTIONS}
- onChange={props.setLinkShareScope}
- />
- </div>
- <p class="text-sm text-ink-muted">{scopeCopy().description}</p>
- <Show when={scope() !== 'NONE'}>
+ <Show when={!props.loading} fallback={<LinkSharingSkeleton />}>
+ <div class="flex flex-col gap-3 p-4 text-sm text-ink">
<div class="flex flex-wrap items-center justify-between gap-3">
- <div class="flex items-center gap-2 text-ink-muted">
- <span>Access level</span>
- <ShareOptions
- editPermissionEnabled={props.editPermissionEnabled}
- permissions={props.linkShareAccessLevel ?? 'view'}
- hideNoAccess={true}
- setPermissions={props.setLinkShareAccessLevel}
- />
+ <div class="flex items-center gap-2">
+ <span class="font-medium">{scopeCopy().title}</span>
+ <Tooltip label={shareStatus().tooltip}>
+ <div
+ class={cn(
+ 'flex items-center justify-center rounded-xl border px-2 py-0.5',
+ shareStatus().label === 'Just me'
+ ? 'border-edge-muted bg-edge-muted text-ink-extra-muted'
+ : 'border-accent/30 bg-accent/10 text-accent'
+ )}
+ >
+ <span class="text-xs font-medium whitespace-nowrap">
+ {shareStatus().label}
+ </span>
+ </div>
+ </Tooltip>
</div>
- <Button variant="outline" onClick={props.copyLink}>
- <CopyIcon class="size-4" />
- <span>Copy Link</span>
- </Button>
+ <Tabs
+ touch="segmented"
+ aria-label="Link sharing scope"
+ size="sm"
+ value={scope()}
+ options={LINK_SHARE_SCOPE_OPTIONS}
+ onChange={props.setLinkShareScope}
+ />
</div>
- </Show>
- <Show when={props.teamShare}>
- {(teamShare) => (
- <div class="border-t border-edge-muted pt-3">
- <TeamAccessSection teamShare={teamShare()} />
+ <p class="text-sm text-ink-muted">{scopeCopy().description}</p>
+ <Show when={scope() !== 'NONE'}>
+ <div class="flex flex-wrap items-center justify-between gap-3">
+ <div class="flex items-center gap-2 text-ink-muted">
+ <span>Access level</span>
+ <ShareOptions
+ editPermissionEnabled={props.editPermissionEnabled}
+ permissions={props.linkShareAccessLevel ?? 'view'}
+ hideNoAccess={true}
+ setPermissions={props.setLinkShareAccessLevel}
+ />
+ </div>
+ <Button variant="outline" onClick={props.copyLink}>
+ <CopyIcon class="size-4" />
+ <span>Copy Link</span>
+ </Button>
</div>
- )}
- </Show>
- </div>
+ </Show>
+ <Show when={props.teamShare}>
+ {(teamShare) => (
+ <div class="border-t border-edge-muted pt-3">
+ <TeamAccessSection teamShare={teamShare()} />
+ </div>
+ )}
+ </Show>
+ </div>
+ </Show>
+ );
+}
+
+function LinkSharingSkeleton() {
+ return (
+ <ListSkeleton.Root label="Loading link sharing" class="p-4">
+ <div class="flex flex-col gap-3">
+ <div class="flex items-center justify-between gap-3">
+ <ListSkeleton.Bar class="h-3 w-32" />
+ <ListSkeleton.Bar class="h-7 w-48" />
+ </div>
+ <ListSkeleton.Bar class="h-3 w-64" />
+ </div>
+ </ListSkeleton.Root>
+ );
+}
+
+/**
+ * Mounts its children once the dialog around it has painted. The share form's
+ * editor and recipient list cost a frame or more to build, and building them
+ * inside the click kept the whole dialog from appearing until they were done.
+ */
+function AfterFirstPaint(props: ParentProps<{ fallback: JSX.Element }>) {
+ const [ready, setReady] = createSignal(false);
+ onMount(() => {
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ // The frame callback runs before that frame paints; the task after it
+ // runs once it has.
+ const frame = requestAnimationFrame(() => {
+ timeout = setTimeout(() => setReady(true));
+ });
+ onCleanup(() => {
+ cancelAnimationFrame(frame);
+ clearTimeout(timeout);
+ });
+ });
+ return (
+ <Show when={ready()} fallback={props.fallback}>
+ {props.children}
+ </Show>
+ );
+}
+
+function ShareFormSkeleton() {
+ return (
+ <ListSkeleton.Root label="Loading share form" class="p-4">
+ <div class="flex flex-col gap-3">
+ <ListSkeleton.Bar class="h-8 w-full" />
+ <ListSkeleton.Bar class="h-3 w-40" />
+ <ListSkeleton.Bar class="h-16 w-full rounded-xl" />
+ </div>
+ </ListSkeleton.Root>
+ );
+}
+
+/** Placeholder rows for the channels an item is shared with. */
+function RecipientsSkeleton() {
+ return (
+ <ListSkeleton.Root label="Loading people with access">
+ <div class="grid gap-3">
+ <For each={[0, 1]}>
+ {() => (
+ <div class="flex items-center justify-between gap-2">
+ <div class="flex items-center gap-2">
+ <ListSkeleton.Bar class="size-4 shrink-0" />
+ <ListSkeleton.Bar class="h-3 w-32" />
+ </div>
+ <ListSkeleton.Bar class="h-3 w-16" />
+ </div>
+ )}
+ </For>
+ </div>
+ </ListSkeleton.Root>
);
}
@@ -613,6 +666,7 @@ interface MobileShareDrawerProps {
linkShare: LinkShare | null | undefined;
linkShareAccessLevel: AccessLevel | null | undefined;
teamShare?: TeamShareControls;
+ permissionsLoading: boolean;
refetch: () => void;
navigateToChannel: (channelId: string) => void;
removeChannelAccess: (channelId: string) => void;
@@ -725,27 +779,31 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {
</p>
</Show>
<Show when={props.canForward}>
- <ForwardToChannel
- {...forwardTarget(
- props.blockAlias,
- props.id,
- props.setChannelPermissions
- )}
- editPermissionEnabled={props.editPermissionEnabled}
- ref={(handle) => setForwardRef(handle)}
- submitPermissionInfo={{
- setChannelPermissions: (id, accessLevel) =>
- props.setChannelPermissions(id, accessLevel, true),
- userPermissions: props.userPermissions,
- channelSharePermissions: props.recipients,
- }}
- onSubmit={() => props.setIsOpen(false)}
- refetch={props.refetch}
- name={props.name}
- hideAccessLevelSelector={props.itemType === 'email'}
- initialAccessLevel={props.itemType === 'email' ? 'view' : null}
- allowedAccessLevels={shareLevelsFor(props.itemType)}
- />
+ <AfterFirstPaint fallback={<ShareFormSkeleton />}>
+ <ForwardToChannel
+ {...forwardTarget(
+ props.blockAlias,
+ props.id,
+ props.setChannelPermissions
+ )}
+ editPermissionEnabled={props.editPermissionEnabled}
+ ref={(handle) => setForwardRef(handle)}
+ submitPermissionInfo={{
+ setChannelPermissions: (id, accessLevel) =>
+ props.setChannelPermissions(id, accessLevel, true),
+ userPermissions: props.userPermissions,
+ channelSharePermissions: props.recipients,
+ }}
+ onSubmit={() => props.setIsOpen(false)}
+ refetch={props.refetch}
+ name={props.name}
+ hideAccessLevelSelector={props.itemType === 'email'}
+ initialAccessLevel={
+ props.itemType === 'email' ? 'view' : null
+ }
+ allowedAccessLevels={shareLevelsFor(props.itemType)}
+ />
+ </AfterFirstPaint>
</Show>
<Show when={!props.canForward}>
<div class="px-4 py-3">
@@ -860,6 +918,7 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {
when={props.linkSharing}
fallback={
<LinkSharingControls
+ loading={props.permissionsLoading}
meetingAccess={props.meetingAccess}
editPermissionEnabled={props.editPermissionEnabled}
linkShare={props.linkShare}
@@ -941,25 +1000,42 @@ export function ShareModal(props: ShareModalProps) {
props.itemType !== 'agent_session' &&
props.itemType !== 'initiative' &&
props.itemType !== 'crm_pipeline';
- const [fallbackPermissionsResource, { refetch: refetchFallback }] =
- createResource(
- () => {
- if (isBlockContext || !props.id) return;
- return { id: props.id, itemType: props.itemType };
- },
- async (source) => {
- if (!source) return;
- const { id, itemType } = source;
- return fetchSharePermissions(id, itemType);
- },
- { initialValue: undefined }
- );
- const permissionsResource = isBlockContext
- ? permissionsBlockResource[0]
- : fallbackPermissionsResource;
- const refetch = isBlockContext
- ? permissionsBlockResource[1].refetch
- : refetchFallback;
+ // Outside a block the dialog reads a cached query, which the Share trigger
+ // warms on hover, so it opens with the roster already in hand.
+ const queryClient = useQueryClient();
+ const fallbackPermissionsQuery = useQuery(() => ({
+ ...sharePermissionsQueryOptions(props.id, props.itemType),
+ enabled: !isBlockContext && !!props.id,
+ }));
+ const sharePermission = () => {
+ if (isBlockContext) {
+ const result = permissionsBlockResource[0].latest;
+ return result && !result.isErr() ? result.value : undefined;
+ }
+ return fallbackPermissionsQuery.isPending
+ ? undefined
+ : (fallbackPermissionsQuery.data ?? undefined);
+ };
+ const permissionsLoading = () =>
+ isBlockContext
+ ? permissionsBlockResource[0].loading &&
+ !permissionsBlockResource[0].latest
+ : fallbackPermissionsQuery.isLoading;
+ const refetch = async () => {
+ if (isBlockContext) {
+ await permissionsBlockResource[1].refetch();
+ return;
+ }
+ // A change made while the first read is in flight must not settle on
+ // that read's stale result.
+ if (fallbackPermissionsQuery.isFetching) {
+ await queryClient.cancelQueries({
+ queryKey: sharePermissionsQueryOptions(props.id, props.itemType)
+ .queryKey,
+ });
+ }
+ await fallbackPermissionsQuery.refetch();
+ };
const userId = useUserId();
const [meetingAccessSnapshot, setMeetingAccessSnapshot] = createSignal<{
documentId: string;
@@ -1030,34 +1106,25 @@ export function ShareModal(props: ShareModalProps) {
);
});
- const [channelNamesResource] = createResource(
- () => {
- const result = permissionsResource.latest;
- if (!result || result.isErr()) {
- return;
- }
- const sharePermission = result.value;
- if (!sharePermission?.channelSharePermissions?.length) {
- return;
- }
- const channel_ids = sharePermission.channelSharePermissions.map(
- ({ channel_id }) => channel_id
- );
- return { channel_ids };
- },
- storageServiceClient.getBatchChannelPreviews,
- { initialValue: undefined }
+ const sharedChannels = createMemo(
+ () => sharedChannelIds(sharePermission()),
+ undefined,
+ {
+ equals: (a, b) =>
+ a.length === b.length && a.every((id, i) => id === b[i]),
+ }
+ );
+ const channelNamesQuery = useQuery(() =>
+ shareChannelNamesQueryOptions(sharedChannels())
);
// Create a map of channel IDs to channel names
const channelNameMap = createMemo(() => {
- const result = channelNamesResource.latest;
- if (!result || result.isErr()) {
- return new Map();
- }
-
- const data = result.value;
+ const data = channelNamesQuery.isPending
+ ? undefined
+ : channelNamesQuery.data;
const map = new Map();
+ if (!data) return map;
data.previews.forEach((preview) => {
if (preview.type === 'access') {
@@ -1071,13 +1138,9 @@ export function ShareModal(props: ShareModalProps) {
return map;
});
- const recipients = createMemo(() => {
- const result = permissionsResource.latest;
- if (!result || result.isErr()) return;
-
- const sharePermission = result.value;
- return sharePermission.channelSharePermissions;
- });
+ const recipients = createMemo(
+ () => sharePermission()?.channelSharePermissions
+ );
// A viewer who does not own the item cannot read its other grants, so the
// roster is just the owner and must not be titled as the full audience.
@@ -1377,23 +1440,11 @@ export function ShareModal(props: ShareModalProps) {
}
);
- const linkShare = createMemo(() => {
- const currentPermissions = permissionsResource.latest;
- if (!currentPermissions || currentPermissions.isErr()) {
- return;
- }
-
- return currentPermissions.value.linkShare;
- });
+ const linkShare = createMemo(() => sharePermission()?.linkShare);
- const linkShareAccessLevel = createMemo(() => {
- const currentPermissions = permissionsResource.latest;
- if (!currentPermissions || currentPermissions.isErr()) {
- return;
- }
-
- return currentPermissions.value.linkShareAccessLevel;
- });
+ const linkShareAccessLevel = createMemo(
+ () => sharePermission()?.linkShareAccessLevel
+ );
const teamShareAccessLevel = createMemo(() => {
if (props.itemType === 'call') {
@@ -1402,10 +1453,7 @@ export function ShareModal(props: ShareModalProps) {
if (!record) return;
return sharePermissionFromCallRecord(record).teamShareAccessLevel;
}
- const currentPermissions = permissionsResource.latest;
- if (!currentPermissions || currentPermissions.isErr()) return;
-
- return currentPermissions.value.teamShareAccessLevel;
+ return sharePermission()?.teamShareAccessLevel;
});
const updateTeamSharePermissions = createCallback(
@@ -1498,8 +1546,11 @@ export function ShareModal(props: ShareModalProps) {
(props.itemType !== 'call' ||
(callRecordQuery.isSuccess && callRecordQuery.data.channelId != null));
+ // Calls read team access from their record; everything else waits for its
+ // permissions so the control never shows "None" before the real level.
const teamShareControls = (): TeamShareControls | undefined =>
canShareWithTeam() &&
+ (props.itemType === 'call' || !permissionsLoading()) &&
userPermissions() === Permissions.OWNER &&
currentTeamQuery.isSuccess &&
currentTeamQuery.data
@@ -1643,6 +1694,7 @@ export function ShareModal(props: ShareModalProps) {
linkShare={linkShare()}
linkShareAccessLevel={linkShareAccessLevel()}
teamShare={teamShareControls()}
+ permissionsLoading={permissionsLoading()}
refetch={refetch}
navigateToChannel={navigateToChannel}
removeChannelAccess={removeChannelAccess}
@@ -1685,29 +1737,31 @@ export function ShareModal(props: ShareModalProps) {
</p>
</Show>
<Show when={canForward()}>
- <ForwardToChannel
- {...forwardTarget(
- props.blockAlias,
- props.id,
- setChannelPermissions
- )}
- editPermissionEnabled={editPermissionEnabled()}
- submitPermissionInfo={{
- setChannelPermissions: (id, accessLevel) =>
- setChannelPermissions(id, accessLevel, true),
- userPermissions: recipientPermissions(),
- channelSharePermissions: recipients(),
- }}
- onSubmit={() => props.onOpenChange(false)}
- onCancel={() => props.onOpenChange(false)}
- refetch={refetch}
- name={props.name}
- hideAccessLevelSelector={props.itemType === 'email'}
- initialAccessLevel={
- props.itemType === 'email' ? 'view' : null
- }
- allowedAccessLevels={shareLevelsFor(props.itemType)}
- />
+ <AfterFirstPaint fallback={<ShareFormSkeleton />}>
+ <ForwardToChannel
+ {...forwardTarget(
+ props.blockAlias,
+ props.id,
+ setChannelPermissions
+ )}
+ editPermissionEnabled={editPermissionEnabled()}
+ submitPermissionInfo={{
+ setChannelPermissions: (id, accessLevel) =>
+ setChannelPermissions(id, accessLevel, true),
+ userPermissions: recipientPermissions(),
+ channelSharePermissions: recipients(),
+ }}
+ onSubmit={() => props.onOpenChange(false)}
+ onCancel={() => props.onOpenChange(false)}
+ refetch={refetch}
+ name={props.name}
+ hideAccessLevelSelector={props.itemType === 'email'}
+ initialAccessLevel={
+ props.itemType === 'email' ? 'view' : null
+ }
+ allowedAccessLevels={shareLevelsFor(props.itemType)}
+ />
+ </AfterFirstPaint>
</Show>
<Show when={!canForward()}>
<div class="flex justify-end px-4 py-3">
@@ -1742,7 +1796,8 @@ export function ShareModal(props: ShareModalProps) {
<Show
when={
(recipients()?.length ?? 0) > 0 ||
- !!(props.owner ?? requests.state()?.owner)
+ !!(props.owner ?? requests.state()?.owner) ||
+ permissionsLoading()
}
>
<Panel
@@ -1799,6 +1854,9 @@ export function ShareModal(props: ShareModalProps) {
exclude={props.directPeopleIds}
/>
<Dynamic component={props.people} />
+ <Show when={permissionsLoading()}>
+ <RecipientsSkeleton />
+ </Show>
<For each={recipients() || []}>
{(recipient) => (
<div class="flex justify-between">
@@ -1937,6 +1995,7 @@ export function ShareModal(props: ShareModalProps) {
when={props.linkSharing}
fallback={
<LinkSharingControls
+ loading={permissionsLoading()}
meetingAccess={meetingAccessForSharing()}
editPermissionEnabled={editPermissionEnabled()}
linkShare={linkShare()}
@@ -2019,15 +2078,34 @@ export function ShareTrigger(props: {
throw new Error('<ShareTrigger> requires an explicit block id');
};
+ const itemType = (): ShareItemType =>
+ blockType() === 'initiative'
+ ? 'initiative'
+ : blockNameToItemType(blockType());
+
+ // Hovering or focusing Share loads what the dialog shows first, so a click
+ // opens it with its roster instead of waiting on the network.
+ const warmShareDialog = () => {
+ if (!isAuthenticated()) return;
+ if (inBlock) {
+ const result = permissionsBlockResource[0].latest;
+ fireAndForget(
+ prefetchShareChannelNames(
+ sharedChannelIds(result && !result.isErr() ? result.value : undefined)
+ ),
+ 'share-modal'
+ );
+ return;
+ }
+ fireAndForget(
+ prefetchSharePermissions(blockId(), itemType()),
+ 'share-modal'
+ );
+ };
+
const panel = useSplitPanel();
const requests = useShareRequestTrigger({
- entity: () =>
- shareEntity(
- blockType() === 'initiative'
- ? 'initiative'
- : blockNameToItemType(blockType()),
- blockId()
- ),
+ entity: () => shareEntity(itemType(), blockId()),
active: () => !panel?.isInlinePreview && (panel?.isPanelActive() ?? false),
open: () => props.onClick(),
});
@@ -2093,7 +2171,12 @@ export function ShareTrigger(props: {
return (
<HeaderActionGroup label="Sharing">
- <div ref={requests.ref} class="flex items-center touch:gap-1">
+ <div
+ ref={requests.ref}
+ class="flex items-center touch:gap-1"
+ onPointerEnter={warmShareDialog}
+ onFocusIn={warmShareDialog}
+ >
<Tooltip
label={
shareStatus()?.tooltip ??
diff --git a/apps/web/src/lib/queries/share/keys.ts b/apps/web/src/lib/queries/share/keys.ts
new file mode 100644
index 0000000000..f5441914e3
--- /dev/null
+++ b/apps/web/src/lib/queries/share/keys.ts
@@ -0,0 +1,10 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+
+export const sharePermissionKeys = createQueryKeys('sharePermissions', {
+ entity: (itemType: string, id: string) => ({
+ queryKey: [itemType, id],
+ }),
+ channelNames: (channelIds: readonly string[]) => ({
+ queryKey: [channelIds],
+ }),
+});
diff --git a/apps/web/src/lib/queries/share/share-permissions.ts b/apps/web/src/lib/queries/share/share-permissions.ts
new file mode 100644
index 0000000000..8ff82d8832
--- /dev/null
+++ b/apps/web/src/lib/queries/share/share-permissions.ts
@@ -0,0 +1,121 @@
+import { fetchPipelineSharePermissions } from '@app/features/crm/sharing-adapter';
+import type { ShareItemType } from '@core/component/TopBar/linkShare';
+import { ThrownResultError, throwOnErr } from '@core/util/result';
+import { cognitionApiServiceClient } from '@service-cognition/client';
+import { storageServiceClient } from '@service-storage/client';
+import { queryOptions } from '@tanstack/solid-query';
+import { fetchAgentSessionSharePermissions } from '../agent-session/share-permissions';
+import { queryClient } from '../client';
+import { fetchInitiativeSharePermissions } from '../initiative/share-permissions';
+import { getDatabaseSharePermissions } from '../storage/databases';
+import { getFormSharePermissions } from '../storage/forms';
+import { sharePermissionKeys } from './keys';
+
+// Long enough that hovering Share and then clicking it fetches once; short
+// enough that a reopened dialog revalidates grants made elsewhere.
+const SHARE_PERMISSIONS_STALE_TIME = 15_000;
+
+/** Reads an item's share permissions from the service that owns it. */
+export async function fetchSharePermissions(
+ id: string,
+ itemType: ShareItemType
+) {
+ if (itemType === 'crm_pipeline') return fetchPipelineSharePermissions(id);
+ if (itemType === 'agent_session') {
+ return fetchAgentSessionSharePermissions(id);
+ }
+ if (itemType === 'initiative') {
+ return fetchInitiativeSharePermissions(id);
+ }
+ if (itemType === 'database') return getDatabaseSharePermissions(id);
+ if (itemType === 'form') return getFormSharePermissions(id);
+ if (itemType === 'chat') {
+ return cognitionApiServiceClient.getChatPermissions({ id });
+ }
+ if (itemType === 'document') {
+ return storageServiceClient.getDocumentPermissions({ document_id: id });
+ }
+ if (itemType === 'project') {
+ if (id === 'trash') {
+ return;
+ }
+ return storageServiceClient.projects.getPermissions({ id });
+ }
+}
+
+async function loadSharePermissions(id: string, itemType: ShareItemType) {
+ const result = await fetchSharePermissions(id, itemType);
+ if (!result) return null;
+ // Each owning service returns its own permission shape, so the union can't
+ // go through `throwOnErr`; this is the same conversion.
+ if (result.isErr()) throw new ThrownResultError(result.error);
+ return result.value;
+}
+
+export function sharePermissionsQueryOptions(
+ id: string,
+ itemType: ShareItemType
+) {
+ return queryOptions({
+ queryKey: sharePermissionKeys.entity(itemType, id).queryKey,
+ queryFn: () => loadSharePermissions(id, itemType),
+ enabled: !!id,
+ staleTime: SHARE_PERMISSIONS_STALE_TIME,
+ });
+}
+
+/** Names of the channels an item is shared with, for the Share dialog roster. */
+export function shareChannelNamesQueryOptions(channelIds: readonly string[]) {
+ return queryOptions({
+ queryKey: sharePermissionKeys.channelNames(channelIds).queryKey,
+ queryFn: () =>
+ throwOnErr(() =>
+ storageServiceClient.getBatchChannelPreviews({
+ channel_ids: [...channelIds],
+ })
+ ),
+ enabled: channelIds.length > 0,
+ staleTime: SHARE_PERMISSIONS_STALE_TIME,
+ });
+}
+
+/** The channel ids a permissions read grants, in a stable order for cache keys. */
+export function sharedChannelIds(
+ permissions:
+ | { channelSharePermissions?: { channel_id: string }[] | null }
+ | null
+ | undefined
+): string[] {
+ return (permissions?.channelSharePermissions ?? [])
+ .map(({ channel_id }) => channel_id)
+ .sort();
+}
+
+/**
+ * Warms what the Share dialog reads first, so opening it right after hovering
+ * or focusing its trigger shows the roster without a network wait.
+ */
+export async function prefetchSharePermissions(
+ id: string,
+ itemType: ShareItemType
+) {
+ if (!id) return;
+ const options = sharePermissionsQueryOptions(id, itemType);
+ await queryClient.prefetchQuery(options);
+ await prefetchShareChannelNames(
+ sharedChannelIds(queryClient.getQueryData(options.queryKey))
+ );
+}
+
+/** Warms the roster's channel names when the permissions are already loaded. */
+export async function prefetchShareChannelNames(channelIds: readonly string[]) {
+ if (channelIds.length === 0) return;
+ await queryClient.prefetchQuery(shareChannelNamesQueryOptions(channelIds));
+}
+
+/** Marks every cached share read stale after a share change made elsewhere. */
+export function invalidateSharePermissions() {
+ queryClient.invalidateQueries({
+ queryKey: sharePermissionKeys._def,
+ });
+}