Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ownership): web render bot and team owners (#7277)
Will Hutchinsonf4fd3a9aa128
diff --git a/apps/web/src/components/app/side-panel/EntityDetailsGrid.tsx b/apps/web/src/components/app/side-panel/EntityDetailsGrid.tsxindex 939e23a65e..b6f068ec5a 100644--- a/apps/web/src/components/app/side-panel/EntityDetailsGrid.tsx+++ b/apps/web/src/components/app/side-panel/EntityDetailsGrid.tsx@@ -1,6 +1,5 @@-import { UserIcon } from '@core/component/UserIcon';-import { getDisplayName, tryMacroId } from '@core/user';import { type DateValue, formatDate } from '@core/util/date';+import { OwnerLabel } from '@entity/owner/owner-display';import ClockIcon from '@phosphor/clock.svg';import { type ParentProps, Show } from 'solid-js';import { SidePanel } from './SidePanel';@@ -19,10 +18,7 @@ export function EntityDetailsGrid({(owner) => (<SidePanel.Row label="Owner"><SidePanel.Pill>- <UserIcon id={owner()} size="sm" showTooltip suppressClick />- <span class="truncate">- {getDisplayName(tryMacroId(owner()))}- </span>+ <OwnerLabel ownerId={owner()} suppressClick /></SidePanel.Pill></SidePanel.Row>)}diff --git a/apps/web/src/components/app/side-panel/FileSidePanelSections.tsx b/apps/web/src/components/app/side-panel/FileSidePanelSections.tsxindex f32ac700c1..247fba0e0f 100644--- a/apps/web/src/components/app/side-panel/FileSidePanelSections.tsx+++ b/apps/web/src/components/app/side-panel/FileSidePanelSections.tsx@@ -5,12 +5,11 @@ import {import { useBlockId } from '@core/block';import { EntityIcon } from '@core/component/EntityIcon';import { openDocument } from '@core/component/LexicalMarkdown/component/core/BlockLink';-import { UserIcon } from '@core/component/UserIcon';import { useCanEdit } from '@core/signal/permissions';-import { getDisplayName, tryMacroId } from '@core/user';import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';import { type DateValue, formatDate } from '@core/util/date';import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';+import { OwnerLabel } from '@entity/owner/owner-display';import { useDocumentMetadataQuery } from '@queries/storage/document-metadata';import { createCallback } from '@solid-primitives/rootless';import { createMemo, Show } from 'solid-js';@@ -224,12 +223,9 @@ export function FolderLink(props: { projectId: string; projectName: string }) {}export function OwnerValue(props: { ownerId: string }) {- const displayName = () => getDisplayName(tryMacroId(props.ownerId));-return (<SidePanel.Pill>- <UserIcon id={props.ownerId} size="sm" showTooltip suppressClick />- <span class="truncate">{displayName()}</span>+ <OwnerLabel ownerId={props.ownerId} suppressClick /></SidePanel.Pill>);}diff --git a/apps/web/src/features/email-compose/primitives/email-composer.test.ts b/apps/web/src/features/email-compose/primitives/email-composer.test.tsindex d118ee8a58..5928d7843b 100644--- a/apps/web/src/features/email-compose/primitives/email-composer.test.ts+++ b/apps/web/src/features/email-compose/primitives/email-composer.test.ts@@ -7,6 +7,10 @@ import { mountEmailComposer } from '../tests/composer';beforeEach(() => vi.useFakeTimers());afterEach(() => vi.useRealTimers());+function hoursFromNow(hours: number): Date {+ return new Date(Date.now() + hours * 60 * 60 * 1000);+}+// Real controller and editor, with only feature capabilities replaced.describe('standalone compose controller', () => {it.each([@@ -205,7 +209,7 @@ describe('standalone compose controller', () => {const root = mountEmailComposer(context);try {root.edit('Schedule this reply', 'Schedule review');- const requested = new Date('2026-10-01T12:00:00Z');+ const requested = hoursFromNow(24);vi.mocked(context.delivery.schedule).mockRejectedValueOnce(new Error('offline'));@@ -240,15 +244,15 @@ describe('standalone compose controller', () => {const root = mountEmailComposer(context);try {root.edit('Schedule this reply', 'Schedule review');- root.state.context.schedule.onSelect(new Date('2026-10-01T12:00:00Z'));+ root.state.context.schedule.onSelect(hoursFromNow(24));root.state.context.onSend();await vi.advanceTimersByTimeAsync(0);expect(context.delivery.schedule).toHaveBeenCalledOnce();expect(root.state.context.disabled()).toBe(true);root.state.context.onSend();- expect(- root.state.context.schedule.onSelect(new Date('2026-10-02T12:00:00Z'))- ).toBe(false);+ expect(root.state.context.schedule.onSelect(hoursFromNow(48))).toBe(+ false+ );expect(context.delivery.sendMessage).not.toHaveBeenCalled();expect(context.delivery.schedule).toHaveBeenCalledOnce();pending.resolve();diff --git a/apps/web/src/features/email-compose/primitives/send-schedule.test.ts b/apps/web/src/features/email-compose/primitives/send-schedule.test.tsindex 9c553c7dcf..939109d073 100644--- a/apps/web/src/features/email-compose/primitives/send-schedule.test.ts+++ b/apps/web/src/features/email-compose/primitives/send-schedule.test.ts@@ -21,6 +21,10 @@ vi.mock('@core/cross-tab/cross-tab-bus', () => ({createCrossTabBus: () => ({ publish() {}, subscribe: () => () => {} }),}));+function hoursFromNow(hours: number): Date {+ return new Date(Date.now() + hours * 60 * 60 * 1000);+}+function composer(kind: 'standalone' | 'reply',composeContext: EmailComposeContext,@@ -929,9 +933,7 @@ describe('send and schedule ordering', () => {state.form.setSelectedInbox('secondary');state.handleAddAttachments([new File(['attachment'], 'review.txt')]);await vi.advanceTimersByTimeAsync(500);- expect(state.handleSendTimeChange(new Date('2026-10-01T12:00:00Z'))).toBe(- true- );+ expect(state.handleSendTimeChange(hoursFromNow(24))).toBe(true);const scheduling = state.sendEmail();await vi.advanceTimersByTimeAsync(0);expect(composeContext.delivery.schedule).not.toHaveBeenCalled();@@ -1002,7 +1004,7 @@ describe('send and schedule ordering', () => {expect(state.sendActionDisabled()).toBe(true);const saves = vi.mocked(composeContext.drafts.saveDraft).mock.calls.length;- await state.handleSendTimeChange(new Date('2026-10-01T12:00:00Z'));+ await state.handleSendTimeChange(hoursFromNow(24));state.persistDraftOnSenderSwitch('secondary');await vi.advanceTimersByTimeAsync(500);expect(composeContext.delivery.schedule).not.toHaveBeenCalled();@@ -1234,7 +1236,7 @@ describe('send and schedule ordering', () => {'draft-a','draft-b',]);- state.handleSendTimeChange(new Date('2026-10-01T12:00:00Z'));+ state.handleSendTimeChange(hoursFromNow(24));await state.sendEmail();expect(composeContext.delivery.archive).toHaveBeenLastCalledWith({ threadId: 'thread-c', value: true },@@ -1259,7 +1261,7 @@ describe('send and schedule ordering', () => {state.send();await vi.advanceTimersByTimeAsync(0);expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();- expect(state.selectTime(new Date('2026-10-01T12:00:00Z'))).toBe(false);+ expect(state.selectTime(hoursFromNow(24))).toBe(false);finishSaving({draftId: 'draft',threadId: 'thread',diff --git a/apps/web/src/features/entity/components/Badges.tsx b/apps/web/src/features/entity/components/Badges.tsxindex d59291be34..9ceaeb0a47 100644--- a/apps/web/src/features/entity/components/Badges.tsx+++ b/apps/web/src/features/entity/components/Badges.tsx@@ -1,5 +1,3 @@-import { UserIcon } from '@core/component/UserIcon';-import { getDisplayName, tryMacroId } from '@core/user';import { formatTimeZoneAbbreviation } from '@core/util/date';import ClockIcon from '@phosphor/clock.svg';import HashIcon from '@phosphor/hash.svg';@@ -11,6 +9,7 @@ import { isThisYear } from 'date-fns/isThisYear';import { isToday } from 'date-fns/isToday';import { isTomorrow } from 'date-fns/isTomorrow';import type { ParentProps } from 'solid-js';+import { OwnerLabel } from '../owner/owner-display';import type { CallStatus } from '../types/entity';function Badge(props: ParentProps<{ class?: string; title?: string }>) {@@ -27,31 +26,28 @@ function Badge(props: ParentProps<{ class?: string; title?: string }>) {);}-// TODO (seamus) : tool tip for now, better shared context laterexport function SharedBadge(props: { ownerId: string }) {return (- <Badge class="text-ink-extra-muted border-edge-muted pr-2">- <UserIcon id={props.ownerId} size="sm" />+ <Badge class="text-ink-extra-muted border-edge-muted pr-2 max-w-48 min-w-0">+ <span class="flex min-w-0 normal-case font-sans">+ <OwnerLabel ownerId={props.ownerId} userAvatarOnly />+ </span>shared</Badge>);}export function SharedBadgeSmall(props: { ownerId: string }) {- const id = () => tryMacroId(props.ownerId);- const name = () => getDisplayName(id()) || undefined;-return (<HoverCardcontent={<div class="flex items-center gap-1.5 text-xs">- <UserIcon- id={props.ownerId}- size="sm"+ <OwnerLabel+ ownerId={props.ownerId}suppressClickshowTooltip={false}/>- <span>{name()} shared this with you</span>+ <span>shared this with you</span></div>}>@@ -63,20 +59,16 @@ export function SharedBadgeSmall(props: { ownerId: string }) {}export function CreatedByBadgeSmall(props: { ownerId: string }) {- const id = () => tryMacroId(props.ownerId);- const name = () => getDisplayName(id()) || undefined;-return (<HoverCardcontent={<div class="flex items-center gap-1.5 text-xs">- <UserIcon- id={props.ownerId}- size="sm"+ <span>Created by</span>+ <OwnerLabel+ ownerId={props.ownerId}suppressClickshowTooltip={false}/>- <span>Created by {name()}</span></div>}>diff --git a/apps/web/src/features/entity/components/OwnerBadges.test.tsx b/apps/web/src/features/entity/components/OwnerBadges.test.tsxnew file mode 100644index 0000000000..1e2664dea9--- /dev/null+++ b/apps/web/src/features/entity/components/OwnerBadges.test.tsx@@ -0,0 +1,106 @@+import { cleanup, render } from '@solidjs/testing-library';+import type { JSX } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';++const PETER = 'macro|[email protected]';+const DEPLOY_BOT = '5f0c8a4e-2d1b-4c3a-9e7f-6a5b4c3d2e1f';+const ENGINEERING = '01234567-89ab-cdef-0123-456789abcdef';++vi.mock('@core/component/UserIcon', () => ({+ UserIcon: () => <span>avatar</span>,+}));+vi.mock('@core/context/user', () => ({+ useUserId: () => () => 'macro|[email protected]',+}));+vi.mock('@core/user', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@core/user')>()),+ getDisplayName: (id: string | undefined) =>+ id === 'macro|[email protected]' ? 'Peter Park' : '',+}));+vi.mock('@queries/bots/profiles', () => ({+ useBotProfile: () => ({+ isPending: false,+ isError: false,+ data: { name: 'Deploy Bot', avatarUrl: undefined, deleted: true },+ }),+}));+vi.mock('@queries/team/teams', () => ({+ useUserTeamsQuery: () => ({+ isPending: false,+ isError: false,+ data: [{ id: '01234567-89ab-cdef-0123-456789abcdef', name: 'Engineering' }],+ }),+}));+vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));+vi.mock('@core/component/HoverCard', () => ({+ HoverCard: (props: { trigger: JSX.Element; content: JSX.Element }) => (+ <>+ {props.trigger}+ {props.content}+ </>+ ),+}));++import { CreatedByBadgeSmall, SharedBadge, SharedBadgeSmall } from './Badges';++afterEach(cleanup);++function textsOf(badge: () => JSX.Element): string[] {+ const { container } = render(badge);+ const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);+ const texts: string[] = [];+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ const text = node.textContent?.trim();+ if (text) texts.push(text);+ }+ return texts;+}++describe('SharedBadge', () => {+ it('draws a user as an avatar, a bot with its name, and a team as a badge', () => {+ expect(textsOf(() => <SharedBadge ownerId={PETER} />)).toEqual([+ 'avatar',+ 'shared',+ ]);+ expect(+ textsOf(() => <SharedBadge ownerId={`bot|${DEPLOY_BOT}`} />)+ ).toEqual(['avatar', 'Deploy Bot (deleted)', 'shared']);+ expect(textsOf(() => <SharedBadge ownerId={ENGINEERING} />)).toEqual([+ 'Engineering',+ 'shared',+ ]);+ });+});++describe('SharedBadgeSmall', () => {+ it('names the user, bot, or team that shared the row', () => {+ expect(textsOf(() => <SharedBadgeSmall ownerId={PETER} />)).toEqual([+ 'avatar',+ 'Peter Park',+ 'shared this with you',+ ]);+ expect(+ textsOf(() => <SharedBadgeSmall ownerId={`bot|${DEPLOY_BOT}`} />)+ ).toEqual(['avatar', 'Deploy Bot (deleted)', 'shared this with you']);+ expect(textsOf(() => <SharedBadgeSmall ownerId={ENGINEERING} />)).toEqual([+ 'Engineering',+ 'shared this with you',+ ]);+ });+});++describe('CreatedByBadgeSmall', () => {+ it('names the user, bot, or team that created the row', () => {+ expect(textsOf(() => <CreatedByBadgeSmall ownerId={PETER} />)).toEqual([+ 'Created by',+ 'avatar',+ 'Peter Park',+ ]);+ expect(+ textsOf(() => <CreatedByBadgeSmall ownerId={`bot|${DEPLOY_BOT}`} />)+ ).toEqual(['Created by', 'avatar', 'Deploy Bot (deleted)']);+ expect(+ textsOf(() => <CreatedByBadgeSmall ownerId={ENGINEERING} />)+ ).toEqual(['Created by', 'Engineering']);+ });+});diff --git a/apps/web/src/features/entity/entity.ts b/apps/web/src/features/entity/entity.tsindex c1b89fcf22..29656bbeec 100644--- a/apps/web/src/features/entity/entity.ts+++ b/apps/web/src/features/entity/entity.ts@@ -5,10 +5,8 @@ import { Root } from './core/Root';import { Slot } from './core/Slot';import { EntityEmailParticipants } from './extractors/entity-email-participants';import { EntityIcon } from './extractors/entity-icon';-import { EntityOwner } from './extractors/entity-owner';import { EntityTimestamp } from './extractors/entity-timestamp';import { EntityTitle } from './extractors/entity-title';-// Notification componentsimport {MobileNotificationStackRows,NotificationContent,@@ -36,7 +34,6 @@ export const Entity = {Title: EntityTitle,Timestamp: EntityTimestamp,EmailParticipants: EntityEmailParticipants,- Owner: EntityOwner,Search: {ContentHits: ContentHits,},diff --git a/apps/web/src/features/entity/extractors/entity-owner.tsx b/apps/web/src/features/entity/extractors/entity-owner.tsxdeleted file mode 100644index 84445e3a1c..0000000000--- a/apps/web/src/features/entity/extractors/entity-owner.tsx+++ /dev/null@@ -1,29 +0,0 @@-import { useUserId } from '@core/context/user';-import { getDisplayName, tryMacroId } from '@core/user';-import type { EntityData } from '../types/entity';--export function EntityOwner(props: { entity: EntityData }) {- const userId = useUserId();- const ownerId = () => props.entity.ownerId;-- const ownerDisplayName = () => {- const owner = ownerId();- if (!owner) return undefined;- return getDisplayName(tryMacroId(owner));- };-- const displayText = () => {- const owner = ownerId();- const currentUser = userId();-- if (!owner) return undefined;-- if (currentUser && owner === currentUser) {- return 'me';- }-- return ownerDisplayName();- };-- return <>{displayText()}</>;-}diff --git a/apps/web/src/features/entity/index.ts b/apps/web/src/features/entity/index.tsindex 331abb6c0e..e7d548d5ff 100644--- a/apps/web/src/features/entity/index.ts+++ b/apps/web/src/features/entity/index.ts@@ -30,6 +30,7 @@ export {getSnippetHit,isHitSnippetEntity,} from './extractors-search/snippet-entity';+export { OwnerLabel } from './owner/owner-display';export { EntityProvider } from './Provider';export {createBulkCopyDssEntityMutation,diff --git a/apps/web/src/features/entity/owner/owner-display.test.tsx b/apps/web/src/features/entity/owner/owner-display.test.tsxnew file mode 100644index 0000000000..f3430a5d66--- /dev/null+++ b/apps/web/src/features/entity/owner/owner-display.test.tsx@@ -0,0 +1,214 @@+import { cleanup, fireEvent, render } from '@solidjs/testing-library';+import { createSignal, type JSX } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++type QueryLike = { isPending: boolean; isError: boolean; data: unknown };++const mocks = vi.hoisted(() => ({+ displayNames: new Map<string, string>(),+ botProfiles: new Map<string, QueryLike>(),+ requestedBotIds: [] as string[],+ teams: { isPending: false, isError: false, data: [] as unknown },+ mutate: vi.fn(),+}));++vi.mock('@core/context/user', () => ({+ useUserId: () => () => 'macro|[email protected]',+}));+vi.mock('@core/user', async () => ({+ ...(await import('@core/user/macroId')),+ getDisplayName: (id: string | undefined) =>+ (id && mocks.displayNames.get(id)) ?? '',+ getDisplayNameParts: () => ({ firstName: '', lastName: '' }),+ getInitials: () => '',+ useIsConnectedSecondaryInbox: () => () => false,+}));+vi.mock('@queries/bots/profiles', () => ({+ useBotProfile: (botId: () => string) => {+ mocks.requestedBotIds.push(botId());+ const current = () => mocks.botProfiles.get(botId());+ return {+ get isPending() {+ return current()?.isPending ?? true;+ },+ get isError() {+ return current()?.isError ?? false;+ },+ get data() {+ return current()?.data;+ },+ };+ },+}));+vi.mock('@queries/team/teams', () => ({+ useUserTeamsQuery: () => mocks.teams,+}));+vi.mock('@queries/channel/get-or-create-dm', () => ({+ useGetOrCreateDirectMessageMutation: () => ({ mutate: mocks.mutate }),+}));+vi.mock('@components/app/split-layout/layout', () => ({+ useSplitLayout: () => ({ openWithSplit: vi.fn() }),+}));+vi.mock('@core/signal/profilePicture', () => ({+ useProfilePictureUrl: () => [() => undefined],+}));+vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));+vi.mock('@core/component/UserCardTrigger', () => ({+ UserCardTrigger: (props: { trigger: JSX.Element }) => props.trigger,+}));++import { OwnerLabel } from './owner-display';++const VIEWER = 'macro|[email protected]';+const PETER = 'macro|[email protected]';+const DEPLOY_BOT = '5f0c8a4e-2d1b-4c3a-9e7f-6a5b4c3d2e1f';+const ENGINEERING = '01234567-89ab-cdef-0123-456789abcdef';++function settled(data: unknown): QueryLike {+ return { isPending: false, isError: false, data };+}++beforeEach(() => {+ mocks.displayNames = new Map([+ [VIEWER, 'Sarah Chen'],+ [PETER, 'Peter Park'],+ ]);+ mocks.botProfiles = new Map();+ mocks.requestedBotIds = [];+ mocks.teams = settled([{ id: ENGINEERING, name: 'Engineering' }]);+ mocks.mutate.mockReset();+});++afterEach(cleanup);++function textOf(ownerId: string | undefined, viewerLabel?: string): string {+ const { container, unmount } = render(() => (+ <OwnerLabel ownerId={ownerId} viewerLabel={viewerLabel} />+ ));+ const text = container.textContent ?? '';+ unmount();+ return text;+}++describe('OwnerLabel', () => {+ it('reads the viewer word for the viewer and their name without one', () => {+ expect(textOf(VIEWER, 'Me')).toBe('Me');+ expect(textOf(VIEWER)).toBe('Sarah Chen');+ });++ it('names another user even when a viewer word is given', () => {+ expect(textOf(PETER, 'Me')).toBe('Peter Park');+ });++ it('names a first-party bot without requesting its profile', () => {+ expect(textOf('bot|00000000-0000-0000-0000-00000000a1a1')).toBe('Macro');+ expect(textOf('00000000-0000-0000-0000-00000000c5c5')).toBe('Cursor');+ expect(mocks.requestedBotIds).toEqual([]);++ mocks.botProfiles.set(+ DEPLOY_BOT,+ settled({ name: 'Deploy Bot', avatarUrl: undefined, deleted: false })+ );+ expect(textOf(`bot|${DEPLOY_BOT}`)).toBe('Deploy Bot');+ expect(mocks.requestedBotIds).toEqual([DEPLOY_BOT]);+ });++ it('suffixes a deleted bot', () => {+ mocks.botProfiles.set(+ DEPLOY_BOT,+ settled({ name: 'Deploy Bot', avatarUrl: undefined, deleted: true })+ );+ expect(textOf(`bot|${DEPLOY_BOT}`)).toBe('Deploy Bot (deleted)');+ });++ it('reads Bot for a bot the backend does not know', () => {+ mocks.botProfiles.set(DEPLOY_BOT, settled(null));+ expect(textOf(`bot|${DEPLOY_BOT}`)).toBe('Bot');+ });++ it('shows the next bot from the same profile subscription', () => {+ const triageBot = '7a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d';+ mocks.botProfiles.set(+ DEPLOY_BOT,+ settled({ name: 'Deploy Bot', avatarUrl: undefined, deleted: false })+ );+ mocks.botProfiles.set(+ triageBot,+ settled({ name: 'Triage Bot', avatarUrl: undefined, deleted: false })+ );+ const [ownerId, setOwnerId] = createSignal(`bot|${DEPLOY_BOT}`);+ const { container } = render(() => <OwnerLabel ownerId={ownerId()} />);++ expect(container.textContent).toBe('Deploy Bot');+ setOwnerId(`bot|${triageBot}`);+ expect(container.textContent).toBe('Triage Bot');+ expect(mocks.requestedBotIds).toEqual([DEPLOY_BOT]);+ });++ it('fills in a bot name in place once its profile arrives', () => {+ const [query, setQuery] = createSignal<QueryLike>({+ isPending: true,+ isError: false,+ data: undefined,+ });+ mocks.botProfiles.set(DEPLOY_BOT, {+ get isPending() {+ return query().isPending;+ },+ get isError() {+ return query().isError;+ },+ get data() {+ return query().data;+ },+ });+ const { container } = render(() => (+ <OwnerLabel ownerId={`bot|${DEPLOY_BOT}`} />+ ));+ const avatar = container.querySelector('[data-slot="avatar"]');+ expect(container.textContent).toBe('');++ setQuery(+ settled({ name: 'Deploy Bot', avatarUrl: undefined, deleted: false })+ );++ expect(container.textContent).toBe('Deploy Bot');+ expect(container.querySelector('[data-slot="avatar"]')).toBe(avatar);+ });++ it('names a known team and reads Team for any other', () => {+ expect(textOf(ENGINEERING)).toBe('Engineering');+ expect(textOf('fedcba98-7654-3210-fedc-ba9876543210')).toBe('Team');+ });++ it('renders nothing without an owner', () => {+ expect(textOf('')).toBe('');+ expect(textOf(undefined)).toBe('');+ expect(textOf('system:nightly')).toBe('?Unknown');+ });++ it('opens a DM only from a user avatar that allows it', () => {+ mocks.botProfiles.set(+ DEPLOY_BOT,+ settled({ name: 'Deploy Bot', avatarUrl: undefined, deleted: false })+ );+ const { container, getByText } = render(() => (+ <>+ <OwnerLabel ownerId={PETER} />+ <OwnerLabel ownerId={VIEWER} suppressClick />+ <OwnerLabel ownerId={`bot|${DEPLOY_BOT}`} />+ <OwnerLabel ownerId={ENGINEERING} />+ </>+ ));++ for (const avatar of container.querySelectorAll('[data-slot="avatar"]')) {+ fireEvent.mouseDown(avatar);+ }+ fireEvent.mouseDown(getByText('Engineering'));++ expect(container.querySelectorAll('[data-slot="avatar"]').length).toBe(3);+ expect(mocks.mutate.mock.calls.map(([vars]) => vars)).toEqual([+ { recipient_id: PETER },+ ]);+ });+});diff --git a/apps/web/src/features/entity/owner/owner-display.tsx b/apps/web/src/features/entity/owner/owner-display.tsxnew file mode 100644index 0000000000..1779d8938b--- /dev/null+++ b/apps/web/src/features/entity/owner/owner-display.tsx@@ -0,0 +1,168 @@+import { UserIcon } from '@core/component/UserIcon';+import { useUserId } from '@core/context/user';+import { getDisplayName } from '@core/user';+import type { MacroId } from '@core/user/macroId';+import UsersThreeIcon from '@phosphor/users-three.svg';+import { firstPartyBotName } from '@queries/bots/first-party-bot-name';+import { useBotProfile } from '@queries/bots/profiles';+import { queryReadyGate } from '@queries/gate';+import { useUserTeamsQuery } from '@queries/team/teams';+import { Avatar } from '@ui';+import { type JSX, Match, type ParentProps, Show, Switch } from 'solid-js';+import { botOwnerName, type Owner, parseOwner } from './owner';++function IconAndName(+ props: ParentProps<{ name: string | undefined; title?: string }>+): JSX.Element {+ return (+ <span class="inline-flex min-w-0 items-center gap-1.5" title={props.title}>+ {props.children}+ <Show when={props.name !== undefined}>+ <span class="truncate">{props.name}</span>+ </Show>+ </span>+ );+}++function TeamBadge(props: { name: string }): JSX.Element {+ return (+ <IconAndName name={props.name} title={props.name}>+ <UsersThreeIcon class="size-4 shrink-0" />+ </IconAndName>+ );+}++function asKind<K extends Owner['kind']>(+ owner: Owner | undefined,+ kind: K+): Extract<Owner, { kind: K }> | undefined {+ return owner?.kind === kind+ ? (owner as Extract<Owner, { kind: K }>)+ : undefined;+}++function UserOwner(props: {+ id: MacroId;+ viewerLabel?: string;+ suppressClick?: boolean;+ showTooltip?: boolean;+ userAvatarOnly?: boolean;+}): JSX.Element {+ const userId = useUserId();+ const name = () => {+ const label = props.viewerLabel;+ return label && props.id === userId() ? label : getDisplayName(props.id);+ };+ return (+ <IconAndName name={props.userAvatarOnly ? undefined : name()}>+ <UserIcon+ id={props.id}+ size="sm"+ suppressClick={props.suppressClick}+ showTooltip={props.showTooltip}+ />+ </IconAndName>+ );+}++function BotFace(props: {+ principal: string;+ name: string;+ avatarUrl?: string;+}): JSX.Element {+ return (+ <IconAndName name={props.name}>+ <UserIcon id={props.principal} photoUrl={props.avatarUrl} size="sm" />+ </IconAndName>+ );+}++function ProfileBot(props: { botId: string }): JSX.Element {+ const profile = useBotProfile(() => props.botId);+ const settled = () => (queryReadyGate(profile) ? profile.data : undefined);+ const name = () => {+ const found = settled();+ if (found) return botOwnerName(found);+ return found === null || profile.isError ? 'Bot' : '';+ };+ return (+ <BotFace+ principal={`bot|${props.botId}`}+ name={name()}+ avatarUrl={settled()?.avatarUrl}+ />+ );+}++function BotOwner(props: { botId: string }): JSX.Element {+ const firstParty = () => firstPartyBotName(props.botId);+ return (+ <Show when={firstParty()} fallback={<ProfileBot botId={props.botId} />}>+ {(name) => <BotFace principal={`bot|${props.botId}`} name={name()} />}+ </Show>+ );+}++function TeamOwner(props: { teamId: string }): JSX.Element {+ const teams = useUserTeamsQuery();+ const name = () => {+ if (queryReadyGate(teams)) {+ return (+ teams.data.find((team) => team.id === props.teamId)?.name ?? 'Team'+ );+ }+ return teams.isError ? 'Team' : '';+ };+ return <TeamBadge name={name()} />;+}++function UnknownOwner(): JSX.Element {+ return (+ <IconAndName name="Unknown">+ <Avatar size="sm">+ <Avatar.Fallback>?</Avatar.Fallback>+ </Avatar>+ </IconAndName>+ );+}++/**+ * An owner's avatar and name, for every owner kind. A user keeps `UserIcon`'s+ * DM click and tooltip unless the caller turns them off. A bot never opens a+ * DM, and a team renders a team badge rather than a person. Renders nothing+ * without an owner.+ */+export function OwnerLabel(props: {+ ownerId: string | undefined;+ /** Replaces the viewer's own name, such as "Me". */+ viewerLabel?: string;+ suppressClick?: boolean;+ showTooltip?: boolean;+ userAvatarOnly?: boolean;+}): JSX.Element {+ const owner = () => parseOwner(props.ownerId);+ return (+ <Switch>+ <Match when={asKind(owner(), 'user')}>+ {(user) => (+ <UserOwner+ id={user().id}+ viewerLabel={props.viewerLabel}+ suppressClick={props.suppressClick}+ showTooltip={props.showTooltip}+ userAvatarOnly={props.userAvatarOnly}+ />+ )}+ </Match>+ <Match when={asKind(owner(), 'bot')}>+ {(bot) => <BotOwner botId={bot().botId} />}+ </Match>+ <Match when={asKind(owner(), 'team')}>+ {(team) => <TeamOwner teamId={team().teamId} />}+ </Match>+ <Match when={asKind(owner(), 'unknown')}>+ <UnknownOwner />+ </Match>+ </Switch>+ );+}diff --git a/apps/web/src/features/entity/owner/owner.test.ts b/apps/web/src/features/entity/owner/owner.test.tsnew file mode 100644index 0000000000..ed6e041e91--- /dev/null+++ b/apps/web/src/features/entity/owner/owner.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';+import { botOwnerName, parseOwner } from './owner';++const BOT_ID = '5f0c8a4e-2d1b-4c3a-9e7f-6a5b4c3d2e1f';+const TEAM_ID = '01234567-89ab-cdef-0123-456789abcdef';+const MACRO_BOT_ID = '00000000-0000-0000-0000-00000000a1a1';++describe('parseOwner', () => {+ it.each([+ {+ principal: 'macro|[email protected]',+ owner: { kind: 'user', id: 'macro|[email protected]' },+ },+ { principal: `bot|${BOT_ID}`, owner: { kind: 'bot', botId: BOT_ID } },+ {+ principal: `bot|${MACRO_BOT_ID}`,+ owner: { kind: 'bot', botId: MACRO_BOT_ID },+ },+ {+ principal: 'bot|not-a-uuid',+ owner: { kind: 'unknown', raw: 'bot|not-a-uuid' },+ },+ { principal: MACRO_BOT_ID, owner: { kind: 'bot', botId: MACRO_BOT_ID } },+ { principal: TEAM_ID, owner: { kind: 'team', teamId: TEAM_ID } },+ {+ principal: 'system:nightly',+ owner: { kind: 'unknown', raw: 'system:nightly' },+ },+ ])('parses $principal', ({ principal, owner }) => {+ expect(parseOwner(principal)).toEqual(owner);+ });++ it('has no owner for an empty or missing principal, unlike a blank one', () => {+ expect(parseOwner('')).toBeUndefined();+ expect(parseOwner(undefined)).toBeUndefined();+ expect(parseOwner(' ')).toEqual({ kind: 'unknown', raw: ' ' });+ });+});++describe('botOwnerName', () => {+ it('suffixes a deleted bot', () => {+ expect(botOwnerName({ name: 'Deploy Bot', deleted: true })).toBe(+ 'Deploy Bot (deleted)'+ );+ });++ it('keeps a live bot name as is', () => {+ expect(botOwnerName({ name: 'Deploy Bot', deleted: false })).toBe(+ 'Deploy Bot'+ );+ });+});diff --git a/apps/web/src/features/entity/owner/owner.ts b/apps/web/src/features/entity/owner/owner.tsnew file mode 100644index 0000000000..cd1516c20e--- /dev/null+++ b/apps/web/src/features/entity/owner/owner.ts@@ -0,0 +1,34 @@+import { type MacroId, tryMacroId } from '@core/user/macroId';+import { isHexHyphenatedId } from '@queries/bots/bot-id';+import { firstPartyBotName } from '@queries/bots/first-party-bot-name';++export type Owner =+ | { kind: 'user'; id: MacroId }+ | { kind: 'bot'; botId: string }+ | { kind: 'team'; teamId: string }+ | { kind: 'unknown'; raw: string };++const BOT_PREFIX = 'bot|';++export function parseOwner(principal: string | undefined): Owner | undefined {+ if (!principal) return undefined;+ const user = tryMacroId(principal);+ if (user) return { kind: 'user', id: user };+ if (principal.startsWith(BOT_PREFIX)) {+ const botId = principal.slice(BOT_PREFIX.length);+ return isHexHyphenatedId(botId)+ ? { kind: 'bot', botId }+ : { kind: 'unknown', raw: principal };+ }+ const bareFirstPartyBot = firstPartyBotName(principal);+ if (bareFirstPartyBot) return { kind: 'bot', botId: principal };+ if (isHexHyphenatedId(principal)) return { kind: 'team', teamId: principal };+ return { kind: 'unknown', raw: principal };+}++export function botOwnerName(profile: {+ name: string;+ deleted: boolean;+}): string {+ return profile.deleted ? `${profile.name} (deleted)` : profile.name;+}diff --git a/apps/web/src/features/entity/utils/shared.test.ts b/apps/web/src/features/entity/utils/shared.test.tsnew file mode 100644index 0000000000..51d5e0fa3d--- /dev/null+++ b/apps/web/src/features/entity/utils/shared.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it } from 'vitest';+import type { EntityData } from '../types/entity';+import { isSharedWithViewer } from './shared';++const VIEWER = 'macro|[email protected]';+const PETER = 'macro|[email protected]';+const ENGINEERING = '01234567-89ab-cdef-0123-456789abcdef';++function row(+ type: EntityData['type'],+ fields: { ownerId?: string; storedForId?: string } = {}+): EntityData {+ return {+ id: `${type}-1`,+ name: type,+ type,+ ownerId: PETER,+ ...fields,+ } as EntityData;+}++describe('isSharedWithViewer', () => {+ it.each([+ ['agent_session', true],+ ['automation', true],+ ['calendar_event', true],+ ['chat', true],+ ['document', true],+ ['email', true],+ ['initiative', true],+ ['project', true],+ ['call', false],+ ['channel', false],+ ['channel_message', false],+ ['channel_thread', false],+ ['crm_company', false],+ ['crm_contact', false],+ ['reminder', false],+ ] as const)(+ '%s owned by another user reads as shared: %s',+ (type, shared) => {+ expect(isSharedWithViewer(row(type), VIEWER)).toBe(shared);+ }+ );++ it('reads a foreign row by who it is stored for', () => {+ expect(+ isSharedWithViewer(row('foreign', { storedForId: VIEWER }), VIEWER)+ ).toBe(false);+ expect(+ isSharedWithViewer(row('foreign', { storedForId: ENGINEERING }), VIEWER)+ ).toBe(true);+ });++ it.each([+ { owner: 'another user', ownerId: PETER, shared: true },+ { owner: 'the viewer', ownerId: VIEWER, shared: false },+ {+ owner: 'a bot',+ ownerId: 'bot|5f0c8a4e-2d1b-4c3a-9e7f-6a5b4c3d2e1f',+ shared: true,+ },+ { owner: 'a team', ownerId: ENGINEERING, shared: true },+ { owner: 'nobody', ownerId: '', shared: false },+ ])(+ 'a document owned by $owner reads as shared: $shared',+ ({ ownerId, shared }) => {+ expect(isSharedWithViewer(row('document', { ownerId }), VIEWER)).toBe(+ shared+ );+ }+ );+});diff --git a/apps/web/src/features/entity/utils/shared.ts b/apps/web/src/features/entity/utils/shared.tsindex a6df8f9cb0..edcf2b53ce 100644--- a/apps/web/src/features/entity/utils/shared.ts+++ b/apps/web/src/features/entity/utils/shared.ts@@ -1,18 +1,42 @@import { useUserContext } from '@core/context/user';+import { match, P } from 'ts-pattern';import type { EntityData } from '../types/entity';+const OWNER_PRINCIPAL_ROW = [+ 'agent_session',+ 'automation',+ 'calendar_event',+ 'chat',+ 'document',+ 'email',+ 'initiative',+ 'project',+] as const;++const UNSHARED_ROW = [+ 'call',+ 'channel',+ 'channel_message',+ 'channel_thread',+ 'crm_company',+ 'crm_contact',+ 'reminder',+] as const;++export function isSharedWithViewer(+ entity: EntityData,+ viewerId: string | undefined+): boolean {+ return match(entity)+ .with({ type: P.union(...OWNER_PRINCIPAL_ROW) }, (row) => {+ return Boolean(row.ownerId) && row.ownerId !== viewerId;+ })+ .with({ type: 'foreign' }, (row) => row.storedForId !== viewerId)+ .with({ type: P.union(...UNSHARED_ROW) }, () => false)+ .exhaustive();+}+export function useIsShared(entity: EntityData) {const { userId } = useUserContext();- return () => {- if (entity.type === 'channel') return false;- if (entity.type === 'call') return false;- if (entity.type === 'foreign') return entity.storedForId !== userId();- if (entity.type === 'crm_company') return false;- // A reminder is private to whoever set it, and the API only ever returns- // the caller's own, so it carries no ownerId at all — without this the- // undefined would never match and every reminder would read as shared.- if (entity.type === 'reminder') return false;- if (entity.ownerId === userId()) return false;- return true;- };+ return () => isSharedWithViewer(entity, userId());}diff --git a/apps/web/src/features/next-soup/soup-view/views/tasks/task-grid-layout.tsx b/apps/web/src/features/next-soup/soup-view/views/tasks/task-grid-layout.tsxindex 08c45b3c18..62b399bb48 100644--- a/apps/web/src/features/next-soup/soup-view/views/tasks/task-grid-layout.tsx+++ b/apps/web/src/features/next-soup/soup-view/views/tasks/task-grid-layout.tsx@@ -1,12 +1,11 @@import { useMaybeSoupView } from '@app/features/next-soup/soup-view/soup-view-context';-import { UserIcon } from '@core/component/UserIcon';-import { getDisplayNameParts, tryMacroId } from '@core/user';import {Entity,type EntityData,type EntityWithProperties,isProjectContainedEntity,MultiSelectCheckbox,+ OwnerLabel,ProjectBreadCrumb,UnreadIndicator,} from '@entity';@@ -23,7 +22,6 @@ import {} from '@property/context/PropertiesContext';import { EntityRowTags } from '@property/tags';import type { Property, PropertyApiValues } from '@property/types';-import { useUserId } from '@queries/auth';import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';import { EntityType } from '@service-properties/generated/schemas/entityType';import type { SoupProperty } from '@service-storage/generated/schemas/soupProperty';@@ -67,16 +65,7 @@ function buildStubProperty(col: TaskGridColumn): Property {export function TaskGridLayout(props: LayoutProps) {const soupView = useMaybeSoupView();- const currentId = useUserId();const entity = () => props.entity as EntityWithProperties<EntityData>;- const isShared = () => props.entity.ownerId !== currentId();-- // Get owner's first name for the Created By column- const ownerDisplayName = () =>- isShared()- ? getDisplayNameParts(tryMacroId(props.entity.ownerId)).firstName ||- 'Unknown'- : 'Me';const propertyMap = createMemo(() => {const map = new Map<string, Property>();@@ -182,13 +171,10 @@ export function TaskGridLayout(props: LayoutProps) {</span>)}</Show>- {/* Show shared badges on narrow/medium containers, hide on wide (>1220px) */}- <Show when={isShared()}>- {/* Narrow: "shared this with you" tooltip */}+ <Show when={props.isShared}><span class="@min-[841px]/u-list:hidden"><SharedBadgeSmall ownerId={props.entity.ownerId} /></span>- {/* Medium (841px-1220px): "Created by" tooltip */}<span class="hidden @min-[841px]/u-list:inline @min-[1221px]/u-list:hidden"><CreatedByBadgeSmall ownerId={props.entity.ownerId} /></span>@@ -217,14 +203,12 @@ export function TaskGridLayout(props: LayoutProps) {)}</For>- {/* Created By column - only shown on wide containers (>1220px) */}<Entity.Slotplacement="createdBy"class="hidden @min-[1221px]/u-list:flex min-w-0 overflow-hidden ph-no-capture"><Badge variant="ghost" size="sm" class="max-w-full gap-1.5">- <UserIcon id={props.entity.ownerId} size="sm" showTooltip={true} />- <span class="truncate">{ownerDisplayName()}</span>+ <OwnerLabel ownerId={props.entity.ownerId} viewerLabel="Me" /></Badge></Entity.Slot>diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsxindex c445443712..ce36cc4a1e 100644--- a/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsx+++ b/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsx@@ -1,9 +1,8 @@-import { UserIcon } from '@core/component/UserIcon';-import { getDisplayNameParts, tryMacroId } from '@core/user';import {Entity,isProjectContainedEntity,MultiSelectCheckbox,+ OwnerLabel,ProjectBreadCrumb,type TaskEntityWithProperties,UnreadIndicator,@@ -22,7 +21,6 @@ import {} from '@property/context/PropertiesContext';import { EntityRowTags } from '@property/tags';import type { Property, PropertyApiValues } from '@property/types';-import { useUserId } from '@queries/auth';import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';import { EntityType } from '@service-properties/generated/schemas/entityType';import type { SoupProperty } from '@service-storage/generated/schemas/soupProperty';@@ -65,16 +63,7 @@ type TaskGridLayoutProps = Omit<LayoutProps, 'entity'> & {};export function TaskGridLayout(props: TaskGridLayoutProps) {- const currentId = useUserId();const entity = () => props.entity;- const isShared = () => props.entity.ownerId !== currentId();-- // Get owner's first name for the Created By column- const ownerDisplayName = () =>- isShared()- ? getDisplayNameParts(tryMacroId(props.entity.ownerId)).firstName ||- 'Unknown'- : 'Me';const propertyMap = createMemo(() => {const map = new Map<string, Property>();@@ -176,13 +165,10 @@ export function TaskGridLayout(props: TaskGridLayoutProps) {</span>)}</Show>- {/* Show shared badges on narrow/medium containers, hide on wide (>1220px) */}- <Show when={isShared()}>- {/* Narrow: "shared this with you" tooltip */}+ <Show when={props.isShared}><span class="@min-[841px]/u-list:hidden"><SharedBadgeSmall ownerId={props.entity.ownerId} /></span>- {/* Medium (841px-1220px): "Created by" tooltip */}<span class="hidden @min-[841px]/u-list:inline @min-[1221px]/u-list:hidden"><CreatedByBadgeSmall ownerId={props.entity.ownerId} /></span>@@ -220,13 +206,11 @@ export function TaskGridLayout(props: TaskGridLayoutProps) {</Entity.Slot></Show>- {/* Created By column - only shown on wide containers (>1220px) */}<Entity.Slotplacement="createdBy"- class="hidden @min-[1221px]/u-list:flex items-center gap-1.5 min-w-0 overflow-hidden text-xs ph-no-capture"+ class="hidden @min-[1221px]/u-list:flex items-center min-w-0 overflow-hidden text-xs text-ink-muted ph-no-capture">- <UserIcon id={props.entity.ownerId} size="sm" showTooltip={true} />- <span class="truncate text-ink-muted">{ownerDisplayName()}</span>+ <OwnerLabel ownerId={props.entity.ownerId} viewerLabel="Me" /></Entity.Slot><Entity.Slotdiff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsxindex 0c560d8d6c..b2caa8b0fa 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx@@ -6,6 +6,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { Permissions } from '../SharePermissions';import { ShareModal, ShareOptions, ShareTrigger } from './ShareButton';+const ME = 'macro|[email protected]';+const SOMEONE_ELSE = 'macro|[email protected]';+const mocks = vi.hoisted(() => ({sendToChannel: vi.fn(),sendToUsers: vi.fn(),@@ -128,7 +131,7 @@ vi.mock('@core/component/VerticalScrollIndicators', () => ({ScrollIndicators: () => null,}));vi.mock('@core/context/user', () => ({- useUserId: () => () => 'owner',+ useUserId: () => () => ME,useReferralCode: () => () => undefined,}));vi.mock('@channel/use-channel-participants', () => ({@@ -167,7 +170,7 @@ vi.mock('@core/signal/permissions', () => ({useGetPermissions: () => () => 'owner',useIsDocumentOwner: () => () => true,}));-vi.mock('@core/user', () => ({ idToEmail: (id: string) => id }));+vi.mock('@core/user', () => ({ getDisplayName: (id: string) => id }));vi.mock('@core/util/currentBlockDocumentName', () => ({useBlockDocumentName: () => () => '',}));@@ -205,7 +208,7 @@ vi.mock('@queries/call/call', () => ({return {callId: 'call-1',channelId: mocks.callRecordChannelId,- createdBy: 'owner',+ createdBy: ME,shareWithTeam: mocks.callRecordShared,};},@@ -329,13 +332,13 @@ beforeEach(() => {mocks.getAgentPermissions.mockResolvedValue(ok({id: 'session-permissions',- owner: 'owner',+ owner: ME,channelSharePermissions: [],}));mocks.updateAgentPermissions.mockResolvedValue(ok({}));mocks.getInitiativePermissions.mockResolvedValue(- ok({ id: 'project-permissions', owner: 'owner' })+ ok({ id: 'project-permissions', owner: ME }));mocks.updateInitiativePermissions.mockResolvedValue(ok({}));mocks.updateChatPermissions.mockResolvedValue({ isErr: () => false });@@ -359,7 +362,7 @@ function mountShare(isOwner: boolean) {<ShareModalid="persisted-session"name="Fix the menu"- owner={isOwner ? 'owner' : 'someone-else'}+ owner={isOwner ? ME : SOMEONE_ELSE}itemType="agent_session"blockAlias="agent"userPermissions={Permissions.OWNER}@@ -383,7 +386,7 @@ describe('agent session sharing', () => {mocks.getAgentPermissions.mockResolvedValue(ok({id: 'session-permissions',- owner: 'owner',+ owner: ME,linkShare: 'PUBLIC',linkShareAccessLevel: 'view',channelSharePermissions: [@@ -561,7 +564,7 @@ describe('agent session sharing', () => {<ShareModalid="persisted-session"name="Fix the menu"- owner="someone-else"+ owner={SOMEONE_ELSE}itemType="agent_session"blockAlias="agent"userPermissions={Permissions.CAN_VIEW}@@ -710,7 +713,7 @@ function mountChatShare() {isErr: () => false,value: {id: 'perm-1',- owner: 'owner',+ owner: ME,linkShare: null,linkShareAccessLevel: null,teamShareAccessLevel: 'view',@@ -721,7 +724,7 @@ function mountChatShare() {<ShareModalid="chat-1"name="Planning chat"- owner="owner"+ owner={ME}itemType="chat"blockAlias="chat"userPermissions={Permissions.OWNER}@@ -736,7 +739,7 @@ function mountCallShare() {isErr: () => false,value: {id: 'perm-call',- owner: 'owner',+ owner: ME,linkShare: null,linkShareAccessLevel: null,teamShareAccessLevel: 'view',@@ -747,7 +750,7 @@ function mountCallShare() {<ShareModalid="call-1"name="Weekly sync"- owner="owner"+ owner={ME}itemType="call"blockAlias="call"userPermissions={Permissions.OWNER}@@ -926,7 +929,7 @@ function mountProjectShare() {isErr: () => false,value: {id: 'perm-project',- owner: 'owner',+ owner: ME,linkShare: null,linkShareAccessLevel: null,teamShareAccessLevel: 'view',@@ -937,7 +940,7 @@ function mountProjectShare() {<ShareModalid="project-1"name="Launch folder"- owner="owner"+ owner={ME}itemType="project"blockAlias="project"userPermissions={Permissions.OWNER}@@ -1039,7 +1042,7 @@ describe('native project sharing', () => {} = {}) {mocks.inBlock = false;- const owner = options.owner ?? 'owner';+ const owner = options.owner ?? ME;render(() => (<ShareModalid="initiative-1"@@ -1048,7 +1051,7 @@ describe('native project sharing', () => {itemType="initiative"blockAlias="initiative"userPermissions={- owner === 'owner' ? Permissions.OWNER : Permissions.CAN_VIEW+ owner === ME ? Permissions.OWNER : Permissions.CAN_VIEW}people={options.people}hasDirectShares={options.hasDirectShares}@@ -1110,7 +1113,7 @@ describe('native project sharing', () => {});it('lets only the owner forward a project', () => {- mountProject({ owner: 'someone-else' });+ mountProject({ owner: SOMEONE_ELSE });expect(screen.getByText('Only the owner can share access to this project. You can copy a link for people who already have access.'@@ -1124,7 +1127,7 @@ describe('native project sharing', () => {mocks.getInitiativePermissions.mockResolvedValue(ok({id: 'project-permissions',- owner: 'owner',+ owner: ME,teamShareAccessLevel: 'view',channelSharePermissions: [{ channel_id: 'channel-1', access_level: 'edit' },diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsxindex 662349e6e4..b7763b2c0a 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx@@ -27,10 +27,10 @@ import { isMobile } from '@core/mobile/isMobile';import { blockHotkeyScopeSignal } from '@core/signal/blockElement';import { blockEditPermissionEnabledSignal } from '@core/signal/load';import { useIsDocumentOwner } from '@core/signal/permissions';-import { idToEmail } from '@core/user';import type { ResultError } from '@core/util/result';import { buildSimpleEntityUrl } from '@core/util/url';import { useCopyLink } from '@core/util/useCopyLink';+import { OwnerLabel } from '@entity/owner/owner-display';import IconShared from '@icon/share.svg';import { Dialog } from '@kobalte/core/dialog';import ChevronDownIcon from '@phosphor/caret-down.svg';@@ -492,7 +492,6 @@ interface MobileShareDrawerProps {userPermissions: Permissions;recipients: SharePermissionV2ChannelSharePermissions | undefined;channelNameMap: Map<string, { name: string; type: string }>;- formattedOwner: string;linkShare: LinkShare | null | undefined;linkShareAccessLevel: AccessLevel | null | undefined;teamShare?: TeamShareControls;@@ -632,11 +631,8 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {<div class="grid gap-3 text-ink text-sm select-none py-3 px-4"><Show when={props.owner}><div class="flex justify-between">- <div class="flex items-center gap-2 overflow-hidden">- <UserIcon isDeleted={false} id={props.owner!} size="sm" />- <div class="font-medium truncate">- {props.formattedOwner}- </div>+ <div class="flex items-center gap-2 overflow-hidden font-medium">+ <OwnerLabel ownerId={props.owner} viewerLabel="Me" /></div><div class="flex items-center"><div class="font-medium text-ink-muted text-xs">Owner</div>@@ -1269,14 +1265,6 @@ export function ShareModal(props: ShareModalProps) {});- const formattedOwner = createMemo(() => {- const ownerValue = props.owner;- if (!ownerValue) {- return '';- }- return ownerValue === userId() ? 'Me' : idToEmail(ownerValue).split('@')[0];- });-return (<Showwhen={!isMobile()}@@ -1296,7 +1284,6 @@ export function ShareModal(props: ShareModalProps) {userPermissions={userPermissions()}recipients={recipients()}channelNameMap={channelNameMap()}- formattedOwner={formattedOwner()}linkShare={linkShare()}linkShareAccessLevel={linkShareAccessLevel()}teamShare={teamShareControls()}@@ -1396,15 +1383,11 @@ export function ShareModal(props: ShareModalProps) {<div class="grid gap-3 text-ink text-sm select-none p-4"><Show when={props.owner}><div class="flex justify-between">- <div class="flex items-center gap-2 overflow-hidden">- <UserIcon- isDeleted={false}- id={props.owner!}- size="sm"+ <div class="flex items-center gap-2 overflow-hidden font-medium">+ <OwnerLabel+ ownerId={props.owner}+ viewerLabel="Me"/>- <div class="font-medium truncate">- {formattedOwner()}- </div></div><div class="flex items-center"><div class="font-medium text-ink-muted text-xs">diff --git a/apps/web/src/lib/queries/bots/bot-id.ts b/apps/web/src/lib/queries/bots/bot-id.tsnew file mode 100644index 0000000000..71bd16a6b7--- /dev/null+++ b/apps/web/src/lib/queries/bots/bot-id.ts@@ -0,0 +1,7 @@+const HEX_HYPHENATED_ID =+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/** A hyphenated hex id. First-party bot ids omit the UUID version digit. */+export function isHexHyphenatedId(value: string): boolean {+ return HEX_HYPHENATED_ID.test(value);+}diff --git a/apps/web/src/lib/queries/bots/bots.ts b/apps/web/src/lib/queries/bots/bots.tsindex f83e6168a3..c10bedc209 100644--- a/apps/web/src/lib/queries/bots/bots.ts+++ b/apps/web/src/lib/queries/bots/bots.ts@@ -4,7 +4,7 @@ import { storageServiceClient } from '@service-storage/client';import type { Bot } from '@service-storage/generated/schemas/bot';import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';import { channelKeys } from '../channel/keys';-import { botKeys } from './keys';+import { botKeys, botProfileKeys } from './keys';type CreateBotParams = {avatarUrl?: string;@@ -90,7 +90,12 @@ export function useUpdateBotMutation() {),onSuccess: async (bot) => {queryClient.setQueryData(botKeys.detail(bot.id).queryKey, bot);- await invalidateBots();+ await Promise.all([+ invalidateBots(),+ queryClient.invalidateQueries({+ queryKey: botProfileKeys.detail(bot.id).queryKey,+ }),+ ]);},onError: (error) => console.error('failed to update bot', error),}));@@ -116,6 +121,9 @@ export function useDeleteBotMutation() {await Promise.all([invalidateBots(),+ queryClient.invalidateQueries({+ queryKey: botProfileKeys.detail(vars.botId).queryKey,+ }),...vars.channelIds.flatMap((channelId) => [queryClient.invalidateQueries({queryKey: channelKeys.channelBots(channelId).queryKey,diff --git a/apps/web/src/lib/queries/bots/keys.ts b/apps/web/src/lib/queries/bots/keys.tsindex a82c44df9e..a016c2f3de 100644--- a/apps/web/src/lib/queries/bots/keys.ts+++ b/apps/web/src/lib/queries/bots/keys.ts@@ -6,3 +6,7 @@ export const botKeys = createQueryKeys('bots', {channels: (botId: string) => ({ queryKey: [botId] }),tokens: (botId: string) => ({ queryKey: [botId] }),});++export const botProfileKeys = createQueryKeys('bot-owner-profiles', {+ detail: (botId: string) => ({ queryKey: [botId] }),+});diff --git a/apps/web/src/lib/queries/bots/profiles.test.ts b/apps/web/src/lib/queries/bots/profiles.test.tsnew file mode 100644index 0000000000..f60ff68d87--- /dev/null+++ b/apps/web/src/lib/queries/bots/profiles.test.ts@@ -0,0 +1,138 @@+import { err, ok } from 'neverthrow';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const getBotOwnerProfiles = vi.fn();++vi.mock('@service-storage/client', () => ({+ storageServiceClient: {+ getBotOwnerProfiles: (...args: unknown[]) => getBotOwnerProfiles(...args),+ },+}));++import { botProfileLoader } from './profiles';++const DEPLOY_BOT = '5f0c8a4e-2d1b-4c3a-9e7f-6a5b4c3d2e1f';+const TRIAGE_BOT = '7a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d';++function botIdAt(index: number): string {+ return `00000000-0000-4000-8000-${String(index).padStart(12, '0')}`;+}++describe('botProfileLoader', () => {+ beforeEach(() => {+ getBotOwnerProfiles.mockReset();+ });++ it('sends concurrent ids in one request and maps each profile', async () => {+ getBotOwnerProfiles.mockResolvedValue(+ ok([+ {+ id: DEPLOY_BOT,+ name: 'Deploy Bot',+ avatar_url: 'https://example.com/deploy.png',+ deleted_at: null,+ },+ {+ id: TRIAGE_BOT,+ name: 'Triage Bot',+ avatar_url: null,+ deleted_at: '2026-09-01T00:00:00Z',+ },+ ])+ );++ const profiles = await Promise.all([+ botProfileLoader.load(DEPLOY_BOT),+ botProfileLoader.load(TRIAGE_BOT),+ ]);++ expect(getBotOwnerProfiles.mock.calls).toEqual([+ [{ ids: [DEPLOY_BOT, TRIAGE_BOT] }],+ ]);+ expect(profiles).toEqual([+ {+ name: 'Deploy Bot',+ avatarUrl: 'https://example.com/deploy.png',+ deleted: false,+ },+ { name: 'Triage Bot', avatarUrl: undefined, deleted: true },+ ]);+ });++ it('splits 101 ids into a request of 100 and a request of 1', async () => {+ getBotOwnerProfiles.mockImplementation(async ({ ids }: { ids: string[] }) =>+ ok(ids.map((id) => ({ id, name: 'Deploy Bot' })))+ );+ const ids = Array.from({ length: 101 }, (_, index) => botIdAt(index));++ const profiles = await Promise.all(+ ids.map((id) => botProfileLoader.load(id))+ );++ expect(getBotOwnerProfiles.mock.calls).toEqual([+ [{ ids: ids.slice(0, 100) }],+ [{ ids: [botIdAt(100)] }],+ ]);+ expect(profiles[100]).toEqual({+ name: 'Deploy Bot',+ avatarUrl: undefined,+ deleted: false,+ });+ });++ it('resolves an id the endpoint omits to null', async () => {+ getBotOwnerProfiles.mockResolvedValue(+ ok([{ id: DEPLOY_BOT, name: 'Deploy Bot' }])+ );++ const [known, omitted] = await Promise.all([+ botProfileLoader.load(DEPLOY_BOT),+ botProfileLoader.load(TRIAGE_BOT),+ ]);++ expect(known).toEqual({+ name: 'Deploy Bot',+ avatarUrl: undefined,+ deleted: false,+ });+ expect(omitted).toBeNull();+ });++ it('rejects a malformed id and still loads a valid one', async () => {+ getBotOwnerProfiles.mockResolvedValue(+ ok([{ id: DEPLOY_BOT, name: 'Deploy Bot' }])+ );++ const [good, bad] = await Promise.allSettled([+ botProfileLoader.load(DEPLOY_BOT),+ botProfileLoader.load('not-a-uuid'),+ ]);++ expect(good.status === 'fulfilled' && good.value).toEqual({+ name: 'Deploy Bot',+ avatarUrl: undefined,+ deleted: false,+ });+ expect(bad.status === 'rejected' && bad.reason.message).toBe(+ 'Invalid bot id'+ );+ expect(getBotOwnerProfiles.mock.calls).toEqual([[{ ids: [DEPLOY_BOT] }]]);+ });++ it('rejects every waiter when the request fails', async () => {+ getBotOwnerProfiles.mockResolvedValue(+ err([{ code: 'HTTP_ERROR', message: 'bot profiles unavailable' }])+ );++ const results = await Promise.allSettled([+ botProfileLoader.load(DEPLOY_BOT),+ botProfileLoader.load(TRIAGE_BOT),+ ]);++ expect(+ results.map((result) =>+ result.status === 'rejected' ? result.reason.message : result.status+ )+ ).toEqual(['bot profiles unavailable', 'bot profiles unavailable']);+ });+});diff --git a/apps/web/src/lib/queries/bots/profiles.ts b/apps/web/src/lib/queries/bots/profiles.tsnew file mode 100644index 0000000000..141ce97cd4--- /dev/null+++ b/apps/web/src/lib/queries/bots/profiles.ts@@ -0,0 +1,94 @@+import { throwOnErr } from '@core/util/result';+import { storageServiceClient } from '@service-storage/client';+import type { BotOwnerProfile } from '@service-storage/generated/schemas/botOwnerProfile';+import { AsyncBatcher } from '@tanstack/pacer';+import { useQuery } from '@tanstack/solid-query';+import { isHexHyphenatedId } from './bot-id';+import { botProfileKeys } from './keys';++export type BotProfile = {+ name: string;+ avatarUrl: string | undefined;+ deleted: boolean;+};++type PendingRequest = {+ resolve: (profile: BotProfile | null) => void;+ reject: (error: Error) => void;+};++const MAX_BOT_OWNER_PROFILE_IDS = 100;++function toBotProfile(row: BotOwnerProfile): BotProfile {+ return {+ name: row.name,+ avatarUrl: row.avatar_url ?? undefined,+ deleted: row.deleted_at != null,+ };+}++class BotProfileLoader {+ private pendingRequests = new Map<string, PendingRequest[]>();++ private batcher = new AsyncBatcher<string>(+ async (botIds) =>+ await throwOnErr(() =>+ storageServiceClient.getBotOwnerProfiles({ ids: botIds })+ ),+ {+ wait: 30,+ maxSize: MAX_BOT_OWNER_PROFILE_IDS,+ onSuccess: (rows: BotOwnerProfile[], botIds) => {+ const profiles = new Map(+ rows.map((row) => [row.id, toBotProfile(row)])+ );+ for (const botId of botIds) {+ const profile = profiles.get(botId) ?? null;+ for (const request of this.take(botId)) request.resolve(profile);+ }+ },+ onError: (error, botIds) => {+ const err =+ error instanceof Error+ ? error+ : new Error('Failed to fetch bot profiles');+ for (const botId of botIds) {+ for (const request of this.take(botId)) request.reject(err);+ }+ },+ throwOnError: false,+ }+ );++ load(botId: string): Promise<BotProfile | null> {+ if (!isHexHyphenatedId(botId)) {+ return Promise.reject(new Error('Invalid bot id'));+ }+ return new Promise((resolve, reject) => {+ const existing = this.pendingRequests.get(botId);+ if (existing) {+ existing.push({ resolve, reject });+ } else {+ this.pendingRequests.set(botId, [{ resolve, reject }]);+ this.batcher.addItem(botId);+ }+ });+ }++ private take(botId: string): PendingRequest[] {+ const requests = this.pendingRequests.get(botId) ?? [];+ this.pendingRequests.delete(botId);+ return requests;+ }+}++export const botProfileLoader = new BotProfileLoader();++/** Profile for a bare bot UUID. `null` when the backend does not know it. */+export function useBotProfile(botId: () => string) {+ return useQuery(() => ({+ queryKey: botProfileKeys.detail(botId()).queryKey,+ queryFn: () => botProfileLoader.load(botId()),+ enabled: botId().length > 0,+ }));+}