From 0703b510477f5246b685dc4b0ebe6d355c65a197 Mon Sep 17 00:00:00 2001 From: hkonsti <45428767+hkonsti@users.noreply.github.com> Date: Sat, 21 Nov 2026 04:57:53 +0000 Subject: [PATCH 1/3] move an agent's settings out of the dialog into a pane at the Chat page's right, beside the open task, opened from its name over its tasks The pane is a fourth column with an address of its own under the chat's or the open task's, so the task stays open beside it and Back closes it. From 1280px all four columns stand side by side; below that the list of tasks gives way, and on a narrow window the pane shows alone. The dialog keeps the name and the head; deleting moves to a card at the pane's foot. --- packages/docs/content/agents/chat.mdx | 5 + packages/web/src/components/app-shell.tsx | 69 ++++++- .../src/components/persona-dialog.test.tsx | 24 +++ .../web/src/components/persona-dialog.tsx | 29 +-- packages/web/src/components/persona-pane.tsx | 65 +++++++ packages/web/src/hooks/use-persona-pane.tsx | 90 +++++++++ packages/web/src/pages/chat-page.test.tsx | 171 +++++++++++++++--- packages/web/src/pages/chat-page.tsx | 121 +++++++++---- packages/web/src/router.tsx | 5 + 9 files changed, 481 insertions(+), 98 deletions(-) create mode 100644 packages/web/src/components/persona-pane.tsx create mode 100644 packages/web/src/hooks/use-persona-pane.tsx diff --git a/packages/docs/content/agents/chat.mdx b/packages/docs/content/agents/chat.mdx index e37f9d39..fef510d9 100644 --- a/packages/docs/content/agents/chat.mdx +++ b/packages/docs/content/agents/chat.mdx @@ -14,6 +14,11 @@ inside them: what the agents may do with each connection is set in its column, o and every call any of them makes is in the activity log, by the task it was made for, which says which agent it was. +Click an agent's name over its list of tasks, or choose **Settings** from its right-click menu in +the list, to open its settings at the right, beside the task you have open: whose it is, and +deleting it at the foot. **Edit** there changes its name and head. Click the name again, press +Back or the cross to close them. + Your chat with an agent is yours alone, as a direct message is, General's too: nobody else in the organization sees it. In it, the agent acts as you, so it reaches what you use: the connections shared with everyone, the ones shared with you by name, the ones you connected yourself and your diff --git a/packages/web/src/components/app-shell.tsx b/packages/web/src/components/app-shell.tsx index ded16d52..f920fbc7 100644 --- a/packages/web/src/components/app-shell.tsx +++ b/packages/web/src/components/app-shell.tsx @@ -51,6 +51,9 @@ type Props = { // A column beside the content, on a page that scrolls inside, as Chat's open task, with its own // cell of the title bar (`Side`). side?: Side; + // A column at the right of the side, as Chat's agent settings beside the open task, with its own + // cell of the title bar (`Pane`). + pane?: Pane; }; /** @@ -65,16 +68,31 @@ export type Side = { narrow: 'side' | 'content'; }; +/** + * A column at the page's right, beside the side, as Chat's agent settings beside its open task: its + * cell of the title bar, and what is under it. It is as wide as `--pane-width`, the side giving it + * room first; where the content, the side and the pane can't all stand side by side, the content + * gives way, as the list of tasks does to the open task, and on a narrow window, the pane shows + * alone. + */ +export type Pane = { + header: ReactNode; + content: ReactNode; +}; + // The content's width while a side stands beside it, the side taking the rest of the page's // (`cqw`, the page being the container): as wide as the person dragged the line between them, on // this device (`--content-width`), or, until they do, as wide as the navigation starts out (ui's // sidebar.tsx), as a second sidebar resized apart from it; but never so wide that the side has -// less than `SIDE_ROOM` beside it. The side's cell of the title bar is as wide as its column, so +// less than `SIDE_ROOM` beside it, and a pane's width besides where one stands at the right +// (`--pane-width`, none without one). The side's cell of the title bar is as wide as its column, so // the line between the two cells falls in the same place in the title bar and under it. const CONTENT_MIN = 192; const SIDE_ROOM = 420; const SIDE_DEFAULTS = - '@container [--content-width:16rem] [--side-room:420px] [--content-split:min(var(--content-width),_100cqw_-_var(--side-room))] [--side-width:calc(100cqw_-_var(--content-split))]'; + '@container [--content-width:16rem] [--side-room:420px] [--pane-width:0px] [--content-split:min(var(--content-width),_100cqw_-_var(--side-room)_-_var(--pane-width))] [--side-width:calc(100cqw_-_var(--content-split)_-_var(--pane-width))]'; +// With a pane, as wide as its settings read well. +const PANE_DEFAULTS = '[--pane-width:22rem]'; // Where in the header the content puts what only it knows, once loaded: the title and its // actions. Null until the frame has drawn them, and where it has none. @@ -185,6 +203,7 @@ export function AppShell({ waiting, contentKey, side, + pane, }: Props) { const {pathname} = useLocation(); const titleBarHeader = useTitleBarHeader(); @@ -194,6 +213,7 @@ export function AppShell({ useFollowRedirect(); const page = useRef(null); const contentColumn = useRef(null); + const paneColumn = useRef(null); // Its own key: the width the chat's wider column was dragged to before it became a second // sidebar, under `proxy-content-width`, would open it far wider than the navigation. const {width: storedContentWidth, setWidth: setContentWidth} = useStoredWidth('proxy-list-width'); @@ -201,20 +221,31 @@ export function AppShell({ // Each address has its own content, and its own failure, unless the page says what it is. const key = contentKey ?? pathname; // The content's column and its cell of the title bar: the rest of the page beside the side's, - // or, on a narrow window, the page's whole width, or none where the side shows in its place. + // or, on a narrow window, the page's whole width, or none where the side shows in its place, + // and none below `xl` beside a pane. const contentSlide = cn( 'flex min-w-0 flex-1 overflow-hidden', side?.narrow === 'side' && 'max-lg:hidden', + pane !== undefined && 'max-xl:hidden', ); // The side's column and its cell of the title bar: as wide as the page less the content's - // column, or, on a narrow window, the page's whole width, or none where the content shows in its - // place. + // column and the pane's, or, on a narrow window, the page's whole width, or none where the + // content or the pane shows in its place. Below `xl` beside a pane, where the content gives way, + // the rest of the page beside the pane. const sideSlide = side !== undefined && cn( - 'flex min-w-0 overflow-hidden max-lg:flex-1 lg:w-(--side-width) lg:shrink-0 lg:border-l', - side.narrow === 'content' && 'max-lg:hidden', + 'flex min-w-0 overflow-hidden lg:border-l', + pane === undefined + ? 'max-lg:flex-1 lg:w-(--side-width) lg:shrink-0' + : 'max-xl:flex-1 xl:w-(--side-width) xl:shrink-0', + (side.narrow === 'content' || pane !== undefined) && 'max-lg:hidden', ); + // The pane's column and its cell of the title bar: its own width at the page's right, or, on a + // narrow window, the page's whole width. + const paneSlide = + pane !== undefined && + 'flex min-w-0 overflow-hidden max-lg:flex-1 lg:w-(--pane-width) lg:shrink-0 lg:border-l'; const content = ( )} + {pane !== undefined && ( +
+
+ + {pane.header} +
+
+ )}
{side.content} )} + {pane !== undefined && ( +
+
{pane.content}
+
+ )} {/* On the line between the content and the side. */} {side !== undefined && ( ({ min: CONTENT_MIN, - max: (page.current?.getBoundingClientRect().width ?? 0) - SIDE_ROOM, + max: + (page.current?.getBoundingClientRect().width ?? 0) - + SIDE_ROOM - + (paneColumn.current?.getBoundingClientRect().width ?? 0), })} apply={(next) => page.current?.style.setProperty('--content-width', `${next}px`)} commit={setContentWidth} - className="absolute inset-y-0 left-(--content-split) z-10 -translate-x-1/2 max-lg:hidden" + className={cn( + 'absolute inset-y-0 left-(--content-split) z-10 -translate-x-1/2 max-lg:hidden', + pane !== undefined && 'max-xl:hidden', + )} /> )} diff --git a/packages/web/src/components/persona-dialog.test.tsx b/packages/web/src/components/persona-dialog.test.tsx index 6ac4de10..c0e35dee 100644 --- a/packages/web/src/components/persona-dialog.test.tsx +++ b/packages/web/src/components/persona-dialog.test.tsx @@ -41,4 +41,28 @@ describe('PersonaDialog', () => { await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); expect(onSave).toHaveBeenCalledWith({name: 'Finance', look, color: 'blue'}); }); + + test('changes the name and the head alone: deleting the agent is in its settings', async () => { + const onSave = mock(async () => null); + const look = {nose: 0.48, noseOut: 0.35, eye: 27, eyeTheta: 55, eyeLat: 8, eyes: 2 as const}; + render( + {}} + onSave={onSave} + />, + ); + + expect( + screen.getByText('Its name and its head. The conversation stays as it is.'), + ).toBeTruthy(); + expect(screen.queryByRole('button', {name: 'Delete'})).toBeNull(); + fireEvent.change(screen.getByLabelText('Name'), {target: {value: 'Accounting'}}); + fireEvent.click(screen.getByRole('radio', {name: 'teal'})); + fireEvent.click(screen.getByRole('button', {name: 'Save'})); + + await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); + expect(onSave).toHaveBeenCalledWith({name: 'Accounting', look, color: 'teal'}); + }); }); diff --git a/packages/web/src/components/persona-dialog.tsx b/packages/web/src/components/persona-dialog.tsx index 9a25cb38..d0ccd08e 100644 --- a/packages/web/src/components/persona-dialog.tsx +++ b/packages/web/src/components/persona-dialog.tsx @@ -20,13 +20,11 @@ import {useCommandEnterSubmit} from '@/hooks/use-command-enter'; type Props = { open: boolean; - // The persona as it is, to change; none to make one. + // The persona's name and head as they are, to change; none to make one. initial: Persona | null; onClose: () => void; // Saves the persona; what went wrong, shown in the dialog, or null once saved. onSave: (persona: Persona) => Promise; - // Deletes the persona with its conversation, where it is one that exists. - onDelete?: () => Promise; }; // The colors as the stylesheet has them, for the swatches. @@ -55,11 +53,12 @@ function fresh(): Persona { const ROUND = 'flex size-9 shrink-0 items-center justify-center rounded-full transition-[box-shadow,background-color] outline-none focus-visible:ring-3 focus-visible:ring-ring/50'; -// Making a persona, or changing one: its name, and its head, which looks at the cursor as the -// person works, in one of the colors, with another look a click away. What runs it, the harness -// and the model, is chosen under the conversation's input (model-switcher.tsx), and a new one -// starts on the server's first. Mount it keyed by what is edited, so the fields start from it. -export function PersonaDialog({open, initial, onClose, onSave, onDelete}: Props) { +// Making a persona, or changing one's name and head: its name, and its head, which looks at the +// cursor as the person works, in one of the colors, with another look a click away. Deleting it is +// in its settings beside its chat (persona-pane.tsx); what runs it, the harness and the model, is +// chosen under the conversation's input (model-switcher.tsx), and a new one starts on the server's +// first. Mount it keyed by what is edited, so the fields start from it. +export function PersonaDialog({open, initial, onClose, onSave}: Props) { const [persona, setPersona] = useState(() => initial ?? fresh()); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); @@ -157,20 +156,6 @@ export function PersonaDialog({open, initial, onClose, onSave, onDelete}: Props) {error &&

{error}

} - {onDelete && ( - { - setBusy(true); - finish(await onDelete()); - }} - > - Delete - - )} Cancel diff --git a/packages/web/src/components/persona-pane.tsx b/packages/web/src/components/persona-pane.tsx new file mode 100644 index 00000000..84890bea --- /dev/null +++ b/packages/web/src/components/persona-pane.tsx @@ -0,0 +1,65 @@ +import type {ChatPersona} from '@proxy/contracts/harness'; +import {PillButton} from '@proxy/ui/components/pill-button'; +import {DangerCard} from '@/components/danger-card'; +import {LiveHead} from '@/components/head'; + +// Whose the agent is, in a line under its name. +function whoseLine(persona: ChatPersona, orgName: string): string { + if (!persona.shared) { + return 'Yours alone'; + } + return `For everyone in ${orgName}`; +} + +// What deleting the agent takes with it: the person's conversation with it, and for one every +// member sees, everyone's. +function deleteCardLine(persona: ChatPersona): string { + const conversations = persona.shared + ? `Every member’s conversation with ${persona.name} goes with it.` + : `Your conversation with ${persona.name} goes with it.`; + return `${conversations} This cannot be undone.`; +} + +// The pane's content, scrolling within itself: the agent, whose it is, and Edit, which opens its +// name and head in their dialog; and, at the pane's foot however short the rest, the card that +// deletes it. Without `mayChange`, it is read alone: neither Edit nor the card. +export function PersonaSettings({ + orgName, + persona, + onEdit, + onDelete, +}: { + orgName: string; + persona: ChatPersona; + onEdit: () => void; + onDelete: () => void; +}) { + return ( +
+
+
+ +
+ {persona.name} + {whoseLine(persona, orgName)} +
+ {persona.mayChange && ( + + Edit + + )} +
+ {persona.mayChange && ( +
+ +
+ )} +
+
+ ); +} diff --git a/packages/web/src/hooks/use-persona-pane.tsx b/packages/web/src/hooks/use-persona-pane.tsx new file mode 100644 index 00000000..e79c5a52 --- /dev/null +++ b/packages/web/src/hooks/use-persona-pane.tsx @@ -0,0 +1,90 @@ +import type {ChatPersona} from '@proxy/contracts/harness'; +import {XIcon} from 'lucide-react'; +import {useMatch} from 'react-router'; +import {type Pane, Waiting} from '@/components/app-shell'; +import {IconButton} from '@/components/icon-button'; +import {PersonaSettings} from '@/components/persona-pane'; + +// What the address of the agent's settings adds to its chat's, or to an open task's. +const SETTINGS = '/settings'; + +/** The address of an agent's settings, beside its chat as `path` has it, with a task open or none. */ +export function settingsPath(path: string): string { + return `${path}${SETTINGS}`; +} + +type Args = { + orgName: string; + // The open chat's agent as the list has it: null while the list loads, and for one it doesn't + // have. + persona: ChatPersona | null; + // Whether the list is still loading, so an agent it lacks may yet come. + pending: boolean; + // The chat's address, or the open task's, which the settings' is under and closing them goes + // back to. + under: string; + // Its name and head change in their dialog (persona-dialog.tsx), and deleting it is confirmed + // in another. + onEdit: (persona: ChatPersona) => void; + onDelete: (persona: ChatPersona) => void; +}; + +/** Whether the address opens the agent's settings, and the pane as the page draws it while it does. */ +export type PersonaPane = {open: boolean; pane: Pane | undefined}; + +/** + * An agent's settings, in a pane at the Chat page's right, beside the task open (`AppShell`'s + * pane), at an address of its own (`settingsPath`) under the chat's or the open task's, so the task + * stays open beside them and Back closes them as their cross does: the agent, whose it is, and + * Edit, which opens its name and head in their dialog; and, at the foot, deleting it. A member who + * may not change it reads it alone. + */ +export function usePersonaPane({ + orgName, + persona, + pending, + under, + onEdit, + onDelete, +}: Args): PersonaPane { + const onChat = useMatch(`/:org/chat/:id${SETTINGS}`) !== null; + const onTask = useMatch(`/:org/chat/:id/threads/:threadId${SETTINGS}`) !== null; + if (!onChat && !onTask) { + return {open: false, pane: undefined}; + } + + const content = () => { + if (persona !== null) { + return ( + onEdit(persona)} + onDelete={() => onDelete(persona)} + /> + ); + } + if (pending) { + return ( +
+ +
+ ); + } + return

This agent does not exist.

; + }; + + const pane: Pane = { + header: ( + <> + Settings + + + + + ), + content: content(), + }; + return {open: true, pane}; +} diff --git a/packages/web/src/pages/chat-page.test.tsx b/packages/web/src/pages/chat-page.test.tsx index 27107033..6ff4f6e8 100644 --- a/packages/web/src/pages/chat-page.test.tsx +++ b/packages/web/src/pages/chat-page.test.tsx @@ -241,7 +241,9 @@ function renderChatPage({ await threadAnswered(); return {thread: views[params.threadId ?? ''] ?? null}; }), + children: [{path: '/:org/chat/:id/threads/:threadId/settings'}], }, + {path: '/:org/chat/:id/settings'}, ], }, ], @@ -515,35 +517,6 @@ describe('ChatPage', () => { } }); - test('edits a changeable agent from its right-click menu', async () => { - fetchMock.mockImplementation((_input, init) => { - if (init?.method === 'PUT') { - return Promise.resolve(Response.json({persona: {...finance, name: 'Accounting'}})); - } - return Promise.resolve(new Response(null, {status: 204})); - }); - renderChatPage(); - - fireEvent.contextMenu(await screen.findByRole('link', {name: /Finance/})); - fireEvent.click(await screen.findByRole('menuitem', {name: 'Edit'})); - expect(screen.getByRole('heading', {name: 'Edit agent'})).toBeDefined(); - expect( - screen.getByText('Its name and its head. The conversation stays as it is.'), - ).toBeDefined(); - fireEvent.change(screen.getByLabelText('Name'), {target: {value: 'Accounting'}}); - fireEvent.click(screen.getByRole('button', {name: 'Save'})); - - await waitFor(() => { - expect(fetchMock).toHaveBeenCalledWith( - '/api/orgs/acme/chat/personas/finance', - expect.objectContaining({ - method: 'PUT', - body: JSON.stringify({name: 'Accounting', look, color: 'blue'}), - }), - ); - }); - }); - test('switches what runs a changeable agent from under the input, keeping its name and head', async () => { fetchMock.mockImplementation((_input, init) => { if (init?.method === 'PUT') { @@ -596,11 +569,12 @@ describe('ChatPage', () => { }); }); - test('does not offer deletion for a protected agent', async () => { + test('offers an agent the person may not change its settings alone in its right-click menu', async () => { renderChatPage(); fireEvent.contextMenu(await screen.findByRole('link', {name: /General/})); + expect(await screen.findByRole('menuitem', {name: 'Settings'})).toBeDefined(); expect(screen.queryByRole('menuitem', {name: 'Edit'})).toBeNull(); expect(screen.queryByRole('menuitem', {name: 'Delete'})).toBeNull(); }); @@ -1733,6 +1707,143 @@ describe('ChatPage', () => { }); }); + describe('the agent’s settings', () => { + const settings = () => screen.getByRole('region', {name: 'Agent settings'}); + + test('open at the page’s right from the agent’s name over its tasks, pressed while open, at an address of their own, and close from it again', async () => { + const {router} = renderChatPage({open: 'finance'}); + const title = await screen.findByRole('button', {name: 'Finance settings'}); + expect(title.getAttribute('aria-pressed')).toBe('false'); + + await follow(title); + await screen.findByRole('region', {name: 'Agent settings'}); + expect(router.state.location.pathname).toBe('/acme/chat/finance/settings'); + expect( + screen.getByRole('button', {name: 'Finance settings'}).getAttribute('aria-pressed'), + ).toBe('true'); + expect(screen.getByLabelText('Tasks')).toBeTruthy(); + expect(screen.getByText('What should Finance do?')).toBeTruthy(); + + await follow(screen.getByRole('button', {name: 'Finance settings'})); + await waitFor(() => + expect(screen.queryByRole('region', {name: 'Agent settings'})).toBeNull(), + ); + expect(router.state.location.pathname).toBe('/acme/chat/finance'); + }); + + test('open beside the open task, which stays open, as another task opens too, and close by their cross back to the task', async () => { + const later = thread('t3', {title: 'Invoice for Northwind'}); + const {router} = renderChatPage({ + threads: [pricing, later], + views: {t1: pricingView, t3: view(later, [said('m5', 'person', 'Send the invoice')])}, + initial: '/acme/chat/general/threads/t1', + }); + await screen.findByLabelText('Thread'); + + await follow(screen.getByRole('button', {name: 'General settings'})); + await screen.findByRole('region', {name: 'Agent settings'}); + expect(router.state.location.pathname).toBe('/acme/chat/general/threads/t1/settings'); + expect(screen.getByLabelText('Thread')).toBeTruthy(); + expect( + screen.getByRole('link', {name: 'Pricing review with Dana'}).getAttribute('aria-current'), + ).toBe('page'); + + await follow(screen.getByRole('link', {name: 'Invoice for Northwind'})); + await screen.findByText('Send the invoice'); + expect(router.state.location.pathname).toBe('/acme/chat/general/threads/t3/settings'); + expect(settings()).toBeTruthy(); + + await follow(screen.getByRole('button', {name: 'Close settings'})); + await waitFor(() => + expect(screen.queryByRole('region', {name: 'Agent settings'})).toBeNull(), + ); + expect(router.state.location.pathname).toBe('/acme/chat/general/threads/t3'); + expect(screen.getByLabelText('Thread')).toBeTruthy(); + }); + + test('open from Settings in the right-click menu, for an agent the person may not change too, read alone, and close with Back', async () => { + const everyone = {...general, shared: true}; + const {router} = renderChatPage({personas: [everyone, finance]}); + await screen.findByText('What should General do?'); + + fireEvent.contextMenu(screen.getByRole('link', {name: /General/})); + await follow(await screen.findByRole('menuitem', {name: 'Settings'})); + const pane = await screen.findByRole('region', {name: 'Agent settings'}); + expect(router.state.location.pathname).toBe('/acme/chat/general/settings'); + expect(within(pane).getByText('For everyone in Acme')).toBeTruthy(); + expect(within(pane).queryByRole('button', {name: 'Edit'})).toBeNull(); + expect(within(pane).queryByRole('button', {name: 'Delete agent'})).toBeNull(); + + await act(async () => { + await router.navigate(-1); + }); + await waitFor(() => + expect(screen.queryByRole('region', {name: 'Agent settings'})).toBeNull(), + ); + }); + + test('show an agent the person may change: its name, whose it is, Edit, and the card that deletes it', async () => { + renderChatPage({open: 'finance', initial: '/acme/chat/finance/settings'}); + const pane = await screen.findByRole('region', {name: 'Agent settings'}); + + expect(within(pane).getByText('Finance')).toBeTruthy(); + expect(within(pane).getByText('Yours alone')).toBeTruthy(); + expect(within(pane).getByRole('button', {name: 'Edit'})).toBeTruthy(); + expect(within(pane).getByRole('heading', {name: 'Delete Finance'})).toBeTruthy(); + expect( + within(pane).getByText( + 'Your conversation with Finance goes with it. This cannot be undone.', + ), + ).toBeTruthy(); + }); + + test('open the name and the head in their dialog from Edit, saved by Save', async () => { + answering((_input, init) => + init?.method === 'PUT' + ? Promise.resolve(Response.json({persona: {...finance, name: 'Accounting'}})) + : null, + ); + renderChatPage({open: 'finance', initial: '/acme/chat/finance/settings'}); + fireEvent.click( + within(await screen.findByRole('region', {name: 'Agent settings'})).getByRole('button', { + name: 'Edit', + }), + ); + + expect(screen.getByRole('heading', {name: 'Edit agent'})).toBeDefined(); + fireEvent.change(screen.getByLabelText('Name'), {target: {value: 'Accounting'}}); + fireEvent.click(screen.getByRole('button', {name: 'Save'})); + + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledWith( + '/api/orgs/acme/chat/personas/finance', + expect.objectContaining({ + method: 'PUT', + body: JSON.stringify({name: 'Accounting', look, color: 'blue'}), + }), + ); + }); + }); + + test('delete the agent from its card after the confirmation, and close with it', async () => { + const {router} = renderChatPage({open: 'finance', initial: '/acme/chat/finance/settings'}); + const pane = await screen.findByRole('region', {name: 'Agent settings'}); + + fireEvent.click(within(pane).getByRole('button', {name: 'Delete agent'})); + expect(screen.getByRole('heading', {name: 'Delete Finance?'})).toBeDefined(); + expect(screen.getByText(/and your conversation with it/)).toBeDefined(); + fireEvent.click(screen.getByRole('button', {name: 'Delete'})); + + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledWith( + '/api/orgs/acme/chat/personas/finance', + expect.objectContaining({method: 'DELETE'}), + ); + }); + await waitFor(() => expect(router.state.location.pathname).not.toContain('/settings')); + }); + }); + describe('sending', () => { // The api as it answers the opening of a thread: as `post` says, the rest as before. function answerSends(post: () => Promise) { diff --git a/packages/web/src/pages/chat-page.tsx b/packages/web/src/pages/chat-page.tsx index fc591ee4..800b2153 100644 --- a/packages/web/src/pages/chat-page.tsx +++ b/packages/web/src/pages/chat-page.tsx @@ -8,7 +8,13 @@ import type { ThreadStanding, ThreadView, } from '@proxy/contracts/harness'; -import {ArchiveIcon, CheckIcon, ChevronLeftIcon, PencilIcon, Trash2Icon} from 'lucide-react'; +import { + ArchiveIcon, + CheckIcon, + ChevronLeftIcon, + SlidersHorizontalIcon, + Trash2Icon, +} from 'lucide-react'; import { memo, Suspense, @@ -55,8 +61,10 @@ import {Dialog, DialogContent, DialogTitle} from '@proxy/ui/components/dialog'; import {LiveHead} from '@/components/head'; import {IconButton} from '@/components/icon-button'; import {PersonaDialog} from '@/components/persona-dialog'; +import {settingsPath, usePersonaPane} from '@/hooks/use-persona-pane'; import {ContentBoundary} from '@/components/route-error'; import {preview} from '@proxy/utils/harness'; +import {PillTab} from '@proxy/ui/components/pill-tab'; import {cn} from '@proxy/ui/lib/utils'; import type {AttachmentInput} from '@/hooks/use-attachments'; import {useChatDraft} from '@/hooks/use-chat-draft'; @@ -65,6 +73,7 @@ import {useLastLoaded, useLoaded} from '@/hooks/use-loaded'; import {personaChatPath, rememberLastThread} from '@/lib/last-thread'; import {rememberedPersonaList} from '@/lib/persona-list'; import {useListMotion} from '@/hooks/use-list-motion'; +import {useHuman} from '@/hooks/use-human'; import {useOrgSlug} from '@/hooks/use-org'; import {usePoll} from '@/hooks/use-poll'; import {useReload} from '@/hooks/use-reload'; @@ -149,15 +158,15 @@ type Shown = {personaId: string; last: LastMessage; draft: string}; // one by what the page shows of it, so what the person just said moves it up at once. It stays as // it is from one chat to the next: the one in the address is lit at once, while it loads. A row // that comes, goes or changes places moves there (`useListMotion`): an agent made, deleted or -// moved up by what was said. At the column's foot, below the agents however many, the button that -// makes a new agent. +// moved up by what was said. Each has a right-click menu, opening its settings beside its chat and, +// where the person may change it, deleting it. At the column's foot, below the agents however +// many, the button that makes a new agent. function PersonaList({ personas, current, shown, recallDraft, onNew, - onEdit, onDelete, }: { personas: ChatPersona[]; @@ -165,10 +174,10 @@ function PersonaList({ shown: Shown | null; recallDraft: (personaId: string) => string | null; onNew: () => void; - onEdit: (persona: ChatPersona) => void; onDelete: (persona: ChatPersona) => void; }) { const org = useOrgSlug(); + const navigate = useNavigate(); const unread = useUnread(); const [hovered, setHovered] = useState(null); const list = useListMotion(); @@ -280,23 +289,23 @@ function PersonaList({ onPointerEnter={() => setHovered(persona.id)} onPointerLeave={() => setHovered(null)} > - {persona.mayChange ? ( - - }>{row} - - onEdit(persona)}> - - Edit - + + }>{row} + + void navigate(settingsPath(personaChatPath(org, persona.id)))} + > + + Settings + + {persona.mayChange && ( onDelete(persona)}> Delete - - - ) : ( - row - )} + )} + + ); })} @@ -519,7 +528,8 @@ function AlertsPendingDialog({ // The page: the organization's agents in the sidebar, beside the person's chat with the one in its // address, a list of its threads as a second sidebar, and beside that, always, the thread the -// address names (pages/chat-thread.tsx), or, with none named, the box that starts a new one. The +// address names (pages/chat-thread.tsx), or, with none named, the box that starts a new one; and, +// where the address opens them, the agent's settings at the right (hooks/use-persona-pane.tsx). The // list of agents is the frame's, so moving to another chat shows it at once, lit in the list and // named in the header, while it loads; the chat is started over as the agent in the address // changes, so what one showed never lingers on another, and stays as it is as one thread of it @@ -555,9 +565,26 @@ export function ChatPage() { rememberLastThread(org, current, threadMissing ? null : (threadId ?? null)); } }, [org, current, threadId, threadMissing]); - // The agent dialog: making a new one, or changing the selected one; closed as null. + // The agent dialog: making a new one, or changing the name and head of one; closed as null. const [editing, setEditing] = useState<'new' | ChatPersona | null>(null); const [deleting, setDeleting] = useState(null); + const human = useHuman(); + const chatTo = `/${org}/chat/${current}`; + const openTo = threadId === undefined ? chatTo : `${chatTo}/threads/${threadId}`; + // The agent's settings at the page's right, at the address of the chat or the open task with + // theirs after it, so opening another task, archiving one or starting one keeps them open. + const {open: settingsOpen, pane} = usePersonaPane({ + orgName: human?.org.name ?? 'the organization', + persona: persona ?? null, + pending: listed.pending, + under: openTo, + onEdit: setEditing, + onDelete: setDeleting, + }); + const withSettings = useCallback( + (path: string) => (settingsOpen ? settingsPath(path) : path), + [settingsOpen], + ); const [error, setError] = useState(null); // The threads the person said are done here, each by its id with when it last had a message // then, and whether its alerts stayed: until something more is said in it, it is done on the @@ -768,14 +795,13 @@ export function ChatPage() { listedThread === null || titleOf(listedThread) === listedThread.title ? listedThread : {...listedThread, title: titleOf(listedThread)}; - const chatTo = `/${org}/chat/${current}`; - // The thread open beside the chat gives its place to a new one's box as it is archived. + // The thread open beside the chat gives its place to the agent's as it is archived. const openArchived = openThread !== null && isArchived(openThread); useEffect(() => { if (openArchived) { - void navigate(chatTo); + void navigate(withSettings(chatTo)); } - }, [openArchived, navigate, chatTo]); + }, [openArchived, navigate, withSettings, chatTo]); const managing = editing !== null || deleting !== null; const composing = composingFor === current && current !== ''; // A new task: its box, floating over the page, with the keyboard's focus. @@ -847,7 +873,13 @@ export function ChatPage() { const title = () => { if (name !== undefined) { - return {name}; + return ( + + ); } // A chat not in the list once it has loaded, as one that could not be. return listed.pending ? : Chat; @@ -864,7 +896,6 @@ export function ChatPage() { shown={shown} recallDraft={recallDraft} onNew={() => setEditing('new')} - onEdit={setEditing} onDelete={setDeleting} /> ); @@ -884,6 +915,7 @@ export function ChatPage() { } contentKey={current} side={side} + pane={pane} > {editing !== null && ( @@ -920,14 +953,6 @@ export function ChatPage() { } onClose={() => setEditing(null)} onSave={savePersona} - onDelete={ - editing !== 'new' - ? async () => { - setDeleting(editing); - return null; - } - : undefined - } /> )} string; }; // The chat the address names, once loaded: started over when the address names another agent. @@ -1117,6 +1145,7 @@ const Chat = memo(function Chat({ onPutAwayNewTask, managing, listError, + withSettings, }: Opened & {loaded: ChatThreads; harnesses: ChatHarness[]}) { const org = useOrgSlug(); const navigate = useNavigate(); @@ -1250,9 +1279,9 @@ const Chat = memo(function Chat({ sent.current = null; onPutAwayNewTask(); if (id !== null) { - void navigate(`/${org}/chat/${personaId}/threads/${id}`); + void navigate(withSettings(`/${org}/chat/${personaId}/threads/${id}`)); } - }, [navigate, org, personaId, onPutAwayNewTask]); + }, [navigate, org, personaId, onPutAwayNewTask, withSettings]); return ( <> @@ -1275,7 +1304,7 @@ const Chat = memo(function Chat({
  • ); } + +// The agent's name in the title bar over its tasks, which opens its settings at the page's right +// and closes them again, lit while they are open. +function SettingsTitle({name, open, to}: {name: string; open: boolean; to: string}) { + const navigate = useNavigate(); + return ( + void navigate(to)} + > + {name} + + ); +} diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsx index 52e65f95..dbd3cc3b 100644 --- a/packages/web/src/router.tsx +++ b/packages/web/src/router.tsx @@ -309,7 +309,12 @@ const routes: RouteObject[] = [ id: THREAD_ROUTE, path: '/:org/chat/:id/threads/:threadId', loader: chatThreadLoader, + // The agent's settings beside the thread, which stays open with them. + children: [{path: '/:org/chat/:id/threads/:threadId/settings'}], }, + // The agent's settings, at the page's right, which the page draws + // (hooks/use-persona-pane.tsx). + {path: '/:org/chat/:id/settings'}, ], }, {path: '/:org/alerts', loader: alertsLoader, element: }, From 434c892daae101374193d67c91c5fe5de5b2bf7c Mon Sep 17 00:00:00 2001 From: hkonsti <45428767+hkonsti@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:17:05 +0000 Subject: [PATCH 2/3] let a member share an agent with the organization, and take one back that nobody else has talked to Whoever made an agent chooses who sees it in a card of its settings pane: only they, or every member, each with a conversation of their own with it. A shared one goes back to its maker alone while no other member has said anything to it; the chats others opened and said nothing in go with that. The list says who made each agent and marks a shared one once anyone else is in the organization. --- packages/api/src/harness/fake-store.ts | 3 + packages/api/src/harness/route.test.ts | 159 +++++++++++++++-- packages/api/src/harness/route.ts | 129 ++++++++++++-- packages/api/src/harness/store.ts | 18 +- packages/contracts/src/contracts.test.ts | 36 ++++ packages/contracts/src/harness.ts | 41 ++++- packages/db/prisma/schema.prisma | 6 +- packages/db/src/harness.ts | 94 +++++++++- packages/db/src/persona-sharing.test.ts | 166 ++++++++++++++++++ packages/docs/content/agents/chat.mdx | 30 +++- packages/docs/content/organizations.mdx | 12 +- packages/web/src/client/harness-client.ts | 8 +- .../src/components/command-palette.test.tsx | 7 +- packages/web/src/components/pane-row.tsx | 2 + packages/web/src/components/persona-pane.tsx | 117 ++++++++++-- packages/web/src/hooks/use-persona-pane.tsx | 14 +- packages/web/src/lib/command-bar.ts | 4 +- packages/web/src/pages/chat-page.test.tsx | 155 +++++++++++++++- packages/web/src/pages/chat-page.tsx | 52 ++++-- 19 files changed, 944 insertions(+), 109 deletions(-) create mode 100644 packages/db/src/persona-sharing.test.ts create mode 100644 packages/web/src/components/pane-row.tsx diff --git a/packages/api/src/harness/fake-store.ts b/packages/api/src/harness/fake-store.ts index 8c1f8dfa..8d390783 100644 --- a/packages/api/src/harness/fake-store.ts +++ b/packages/api/src/harness/fake-store.ts @@ -31,10 +31,13 @@ export function fakeStore(): FakeStore { createAgentTask: mock(), listPersonas: mock(), listAnswers: mock(), + listMemberNames: mock(), ensureFirstPersona: mock(), getPersona: mock(), createPersona: mock(), updatePersona: mock(), + sharePersona: mock(), + takeBackPersona: mock(), deletePersona: mock(), getMemberChat: mock(), ensureMemberChat: mock(), diff --git a/packages/api/src/harness/route.test.ts b/packages/api/src/harness/route.test.ts index 6b2a7817..b3dc8e56 100644 --- a/packages/api/src/harness/route.test.ts +++ b/packages/api/src/harness/route.test.ts @@ -35,6 +35,8 @@ const personaResponse = { draft: null, createdAt: '2026-10-21T10:00:00.000Z', }; +// The same persona as the list has it: the viewer made it, and nobody else has talked to it. +const listedResponse = {...personaResponse, madeBy: 'you' as const, usedByOthers: false, staysShared: null}; // The harnesses the server has, unless a test says otherwise: the loop over OpenRouter, with its // two models, which the viewer's organization is offered with the `openrouter` experiment, and @@ -132,11 +134,12 @@ beforeEach(async () => { store.listDraftAttachments.mockResolvedValue(Ok([])); store.addDraftAttachment.mockResolvedValue(Ok(true)); store.removeDraftAttachment.mockResolvedValue(Ok(true)); + store.listMemberNames.mockResolvedValue(Ok([{orgId: 'org-1', userId: 'user-2', name: 'Dana'}])); const {listPersonas, ensureFirstPersona, getPersona, createPersona, updatePersona, deletePersona, getMemberChat, ensureMemberChat, getChatDraft} = store; deletePersona.mockResolvedValue(Ok(true)); ensureFirstPersona.mockResolvedValue(Ok({...persona, id: 'persona-9', name: 'General', ownerUserId: null, createdById: null})); requireViewer.mockResolvedValue(Ok(viewer)); - listPersonas.mockResolvedValue(Ok([{...persona, lastMessage: {kind: 'assistant', text: 'Your vault\n has one entry.', createdAt: now}, draft: null, draftAttachments: []}])); + listPersonas.mockResolvedValue(Ok([{...persona, lastMessage: {kind: 'assistant', text: 'Your vault\n has one entry.', createdAt: now}, draft: null, draftAttachments: [], usedByOthers: false}])); getPersona.mockResolvedValue(Ok(persona)); createPersona.mockResolvedValue(Ok({...persona, id: 'persona-2'})); updatePersona.mockResolvedValue(Ok(true)); @@ -150,7 +153,7 @@ describe('the chat routes', () => { test('offer OpenRouter only with the openrouter experiment: without it, a persona on it is shown on Claude, and none is made or switched to it', async () => { const {handleCreatePersonaRoute, handleListPersonasRoute, handleUpdatePersonaRoute} = routes; requireViewer.mockResolvedValue(Ok({...viewer, experiments: []})); - store.listPersonas.mockResolvedValue(Ok([{...persona, ownerUserId: null, lastMessage: null, draft: null, draftAttachments: []}])); + store.listPersonas.mockResolvedValue(Ok([{...persona, ownerUserId: null, lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}])); const listed = (await handleListPersonasRoute(request())).unwrap(); expect(listed.harnesses.map((harness) => harness.id)).toEqual(['claude-agent-sdk']); @@ -163,21 +166,22 @@ describe('the chat routes', () => { expect(store.updatePersona).not.toHaveBeenCalled(); await handleCreatePersonaRoute(request({}, {name: 'Finance', look, color: 'blue'})); - expect(store.createPersona).toHaveBeenCalledWith('org-1', 'user-1', {name: 'Finance', look, color: 'blue', harness: 'claude-agent-sdk', chatModel: 'sonnet'}); + expect(store.createPersona).toHaveBeenCalledWith('org-1', 'user-1', {name: 'Finance', look, color: 'blue', harness: 'claude-agent-sdk', chatModel: 'sonnet'}, false); }); test('list the personas the viewer sees, their own and every member’s, with their heads, what runs each, whether the viewer may change each, and the last thing said with each and what the viewer typed and hasn’t sent, on one line, and the harnesses the server has with their models', async () => { const {handleListPersonasRoute} = routes; store.listPersonas.mockResolvedValue( Ok([ - {...persona, lastMessage: {kind: 'assistant', text: 'Your vault\n has one entry.', createdAt: now}, draft: null, draftAttachments: []}, - {...persona, id: 'persona-3', ownerUserId: null, createdById: 'user-2', lastMessage: null, draft: 'Move the **pricing review**\nto Friday', draftAttachments: []}, + {...persona, lastMessage: {kind: 'assistant', text: 'Your vault\n has one entry.', createdAt: now}, draft: null, draftAttachments: [], usedByOthers: false}, + {...persona, id: 'persona-3', ownerUserId: null, createdById: 'user-2', lastMessage: null, draft: 'Move the **pricing review**\nto Friday', draftAttachments: [], usedByOthers: false}, { ...persona, id: 'persona-4', lastMessage: {kind: 'assistant', text: '## Found\n\n- **Three** invoices, see [the list](https://x.test)\n\n| Who | Sum |\n| --- | --- |\n| Dana | 40 |\n\n```\ncode\n```', createdAt: now}, draft: null, draftAttachments: [], + usedByOthers: false, }, ]), ); @@ -185,11 +189,20 @@ describe('the chat routes', () => { const listed = (await handleListPersonasRoute(request())).unwrap(); expect(store.listPersonas).toHaveBeenCalledWith('org-1', 'user-1'); + expect(store.listMemberNames).toHaveBeenCalledWith([{orgId: 'org-1', userId: 'user-2'}]); expect(listed).toEqual({ personas: [ - {...personaResponse, lastMessage: {kind: 'assistant', text: 'Your vault has one entry.', at: '2026-10-21T10:00:00.000Z'}}, - {...personaResponse, id: 'persona-3', shared: true, mayChange: false, draft: 'Move the pricing review to Friday'}, - {...personaResponse, id: 'persona-4', lastMessage: {kind: 'assistant', text: 'Found Three invoices, see the list Who Sum Dana 40', at: '2026-10-21T10:00:00.000Z'}}, + {...listedResponse, lastMessage: {kind: 'assistant', text: 'Your vault has one entry.', at: '2026-10-21T10:00:00.000Z'}}, + { + ...listedResponse, + id: 'persona-3', + shared: true, + mayChange: false, + madeBy: {name: 'Dana'}, + staysShared: 'Only whoever made Finance can make it theirs alone.', + draft: 'Move the pricing review to Friday', + }, + {...listedResponse, id: 'persona-4', lastMessage: {kind: 'assistant', text: 'Found Three invoices, see the list Who Sum Dana 40', at: '2026-10-21T10:00:00.000Z'}}, ], harnesses: offered, }); @@ -227,7 +240,34 @@ describe('the chat routes', () => { const listed = (await handleListPersonasRoute(request())).unwrap(); expect(store.ensureFirstPersona).toHaveBeenCalledWith('org-1'); - expect(listed).toEqual({personas: [{...personaResponse, id: 'persona-9', name: 'General', shared: true, mayChange: false}], harnesses: offered}); + expect(listed).toEqual({ + personas: [{...listedResponse, id: 'persona-9', name: 'General', shared: true, mayChange: false, madeBy: null, staysShared: 'General is every member’s, so it can’t be made anyone’s own.'}], + harnesses: offered, + }); + }); + + test('list who made each persona: the viewer, another member by what they are called, or nobody where its maker has left', async () => { + const {handleListPersonasRoute} = routes; + const listedRow = {lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}; + store.listPersonas.mockResolvedValue( + Ok([ + {...persona, ownerUserId: null, ...listedRow}, + {...persona, id: 'persona-3', ownerUserId: null, createdById: 'user-2', ...listedRow}, + {...persona, id: 'persona-4', ownerUserId: null, createdById: 'user-3', ...listedRow}, + ]), + ); + + const listed = (await handleListPersonasRoute(request())).unwrap(); + + expect(store.listMemberNames).toHaveBeenCalledWith([ + {orgId: 'org-1', userId: 'user-2'}, + {orgId: 'org-1', userId: 'user-3'}, + ]); + expect(listed.personas.map(({id, madeBy}) => [id, madeBy])).toEqual([ + ['persona-1', 'you'], + ['persona-3', {name: 'Dana'}], + ['persona-4', null], + ]); }); test('a viewer who sees personas of their own but none every member’s, as where General was deleted, gets General made again, after their own', async () => { @@ -247,7 +287,7 @@ describe('the chat routes', () => { const made = await handleCreatePersonaRoute(request({}, {name: ' Finance ', look, color: 'blue'})); - expect(store.createPersona).toHaveBeenCalledWith('org-1', 'user-1', {name: 'Finance', look, color: 'blue', harness: 'claude-agent-sdk', chatModel: 'sonnet'}); + expect(store.createPersona).toHaveBeenCalledWith('org-1', 'user-1', {name: 'Finance', look, color: 'blue', harness: 'claude-agent-sdk', chatModel: 'sonnet'}, false); expect(made.unwrap().persona).toEqual({...personaResponse, id: 'persona-2'}); }); @@ -282,13 +322,102 @@ describe('the chat routes', () => { expect((await handleDeletePersonaRoute(request({personaId: 'nope'}))).unwrapErr()).toMatchObject({kind: 'not_found'}); }); + test('make a persona shared with the organization from the start, or the viewer’s own where nothing is said', async () => { + const {handleCreatePersonaRoute} = routes; + store.createPersona.mockResolvedValue(Ok({...persona, id: 'persona-2', ownerUserId: null})); + + const made = await handleCreatePersonaRoute(request({}, {name: 'Finance', look, color: 'blue', shared: true})); + + expect(store.createPersona).toHaveBeenCalledWith('org-1', 'user-1', {name: 'Finance', look, color: 'blue', harness: 'claude-agent-sdk', chatModel: 'sonnet'}, true); + expect(made.unwrap().persona).toEqual({...personaResponse, id: 'persona-2', shared: true}); + + await handleCreatePersonaRoute(request({}, {name: 'Finance', look, color: 'blue'})); + expect(store.createPersona).toHaveBeenLastCalledWith('org-1', 'user-1', {name: 'Finance', look, color: 'blue', harness: 'claude-agent-sdk', chatModel: 'sonnet'}, false); + }); + + test('share the viewer’s own persona with the organization, changing nothing else of it, and leave who sees it as it is where nothing is said', async () => { + const {handleUpdatePersonaRoute} = routes; + store.sharePersona.mockResolvedValue(Ok(true)); + const body = {name: 'Finance', look, color: 'blue' as const}; + + const shared = await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, {...body, shared: true})); + + expect(store.sharePersona).toHaveBeenCalledWith('org-1', 'user-1', 'persona-1'); + expect(store.updatePersona).toHaveBeenCalledWith('org-1', 'persona-1', body); + expect(shared.unwrap().persona).toEqual({...personaResponse, shared: true}); + + store.sharePersona.mockClear(); + await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, body)); + await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, {...body, shared: false})); + expect(store.sharePersona).not.toHaveBeenCalled(); + expect(store.takeBackPersona).not.toHaveBeenCalled(); + }); + + test('make a shared persona its maker’s alone again while nobody else has talked to it, and refuse where others have, saying so, changing nothing', async () => { + const {handleUpdatePersonaRoute} = routes; + const body = {name: 'Finance', look, color: 'blue' as const, shared: false}; + store.getPersona.mockResolvedValue(Ok({...persona, ownerUserId: null})); + store.takeBackPersona.mockResolvedValue(Ok('taken')); + + const taken = await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, body)); + + expect(store.takeBackPersona).toHaveBeenCalledWith('org-1', 'user-1', 'persona-1'); + expect(taken.unwrap().persona).toEqual({...personaResponse, shared: false}); + + store.updatePersona.mockClear(); + store.takeBackPersona.mockResolvedValue(Ok('used')); + expect((await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, body))).unwrapErr()).toEqual(ApiErr.conflict('Others in Acme are using Finance, so it stays shared.')); + expect(store.updatePersona).not.toHaveBeenCalled(); + + store.takeBackPersona.mockResolvedValue(Ok('missing')); + expect((await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, body))).unwrapErr()).toMatchObject({kind: 'not_found'}); + expect(store.updatePersona).not.toHaveBeenCalled(); + }); + + test('keep General every member’s, and a shared persona somebody else made from being taken by the organization’s owner, who may still change and delete it', async () => { + const {handleDeletePersonaRoute, handleUpdatePersonaRoute} = routes; + const body = {name: 'General', look, color: 'blue' as const, shared: false}; + requireViewer.mockResolvedValue(Ok({...viewer, role: 'owner'})); + + store.getPersona.mockResolvedValue(Ok({...persona, name: 'General', ownerUserId: null, createdById: null})); + expect((await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, body))).unwrapErr()).toEqual(ApiErr.conflict('General is every member’s, so it can’t be made anyone’s own.')); + + store.getPersona.mockResolvedValue(Ok({...persona, ownerUserId: null, createdById: 'user-2'})); + expect((await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, {...body, name: 'Finance'}))).unwrapErr()).toEqual(ApiErr.conflict('Only whoever made Finance can make it theirs alone.')); + expect(store.takeBackPersona).not.toHaveBeenCalled(); + expect(store.updatePersona).not.toHaveBeenCalled(); + + const {shared: _shared, ...rename} = body; + expect((await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, {...rename, name: 'Money'}))).isOk()).toBe(true); + expect((await handleDeletePersonaRoute(request({personaId: 'persona-1'}))).isOk()).toBe(true); + }); + + test('list whether others have talked to a shared persona, and why the viewer can’t make it theirs alone, only where they can’t', async () => { + const {handleListPersonasRoute} = routes; + store.listPersonas.mockResolvedValue( + Ok([ + {...persona, ownerUserId: null, lastMessage: null, draft: null, draftAttachments: [], usedByOthers: true}, + {...persona, id: 'persona-3', ownerUserId: null, lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}, + {...persona, id: 'persona-4', lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}, + ]), + ); + + const listed = (await handleListPersonasRoute(request())).unwrap(); + + expect(listed.personas.map(({id, usedByOthers, staysShared}) => [id, usedByOthers, staysShared])).toEqual([ + ['persona-1', true, 'Others in Acme are using Finance, so it stays shared.'], + ['persona-3', false, null], + ['persona-4', false, null], + ]); + }); + test('make a persona on the harness and the model chosen, switch it to another of either, and show what runs it', async () => { const {handleCreatePersonaRoute, handleUpdatePersonaRoute} = routes; const onSdk = {name: 'Finance', look, color: 'blue' as const, harness: 'claude-agent-sdk', chatModel: 'opus'}; store.createPersona.mockResolvedValue(Ok({...persona, id: 'persona-2', harness: 'claude-agent-sdk', chatModel: 'opus'})); const made = await handleCreatePersonaRoute(request({}, onSdk)); - expect(store.createPersona).toHaveBeenCalledWith('org-1', 'user-1', onSdk); + expect(store.createPersona).toHaveBeenCalledWith('org-1', 'user-1', onSdk, false); expect(made.unwrap().persona).toEqual({...personaResponse, id: 'persona-2', harness: 'claude-agent-sdk', chatModel: 'opus'}); // Another model of the harness it has, the harness left out. @@ -329,8 +458,8 @@ describe('the chat routes', () => { registry = {proxy, claudeAgentSdk: null}; store.listPersonas.mockResolvedValue( Ok([ - {...persona, harness: 'claude-agent-sdk', chatModel: 'opus', lastMessage: null, draft: null, draftAttachments: []}, - {...persona, id: 'persona-3', ownerUserId: null, chatModel: 'dropped-long-ago', lastMessage: null, draft: null, draftAttachments: []}, + {...persona, harness: 'claude-agent-sdk', chatModel: 'opus', lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}, + {...persona, id: 'persona-3', ownerUserId: null, chatModel: 'dropped-long-ago', lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}, ]), ); @@ -362,9 +491,9 @@ describe('the chat routes', () => { // The chat opens with it there, and the list says it is waiting where nothing was typed. store.listDraftAttachments.mockResolvedValue(Ok([kept])); expect((await handleListThreadsRoute(request({personaId: 'persona-1'}))).unwrap().draftAttachments).toEqual([shownAttachment]); - store.listPersonas.mockResolvedValue(Ok([{...persona, lastMessage: null, draft: null, draftAttachments: [kept, {...kept, fileId: 'file-2', name: 'chart.png'}]}])); + store.listPersonas.mockResolvedValue(Ok([{...persona, lastMessage: null, draft: null, draftAttachments: [kept, {...kept, fileId: 'file-2', name: 'chart.png'}], usedByOthers: false}])); expect((await handleListPersonasRoute(request())).unwrap().personas[0]?.draft).toBe('pricing.md, chart.png'); - store.listPersonas.mockResolvedValue(Ok([{...persona, lastMessage: null, draft: 'Book the train', draftAttachments: [kept]}])); + store.listPersonas.mockResolvedValue(Ok([{...persona, lastMessage: null, draft: 'Book the train', draftAttachments: [kept], usedByOthers: false}])); expect((await handleListPersonasRoute(request())).unwrap().personas[0]?.draft).toBe('Book the train'); // With as many there as a message carries, the next is refused before its bytes are taken. diff --git a/packages/api/src/harness/route.ts b/packages/api/src/harness/route.ts index fe430c3a..6fc8368a 100644 --- a/packages/api/src/harness/route.ts +++ b/packages/api/src/harness/route.ts @@ -10,6 +10,7 @@ import { type ChatPersona, type ChatThread, type ChatThreads, + type ListedPersona, markReadBodySchema, MAX_ATTACHMENTS, personaBodySchema, @@ -43,7 +44,7 @@ import type {HarnessStore} from './store'; /** * The Chat page's routes, under the organization: the personas the member sees, their own and - * General, which every member does, each named and given a head, all acting through the + * those shared with every member, as General is, each named and given a head, all acting through the * organization's one built-in agent login, and the member's own chat with each, which holds * threads: each message they post in the chat opens one, whose agent works on it and answers them * there, and a reply in a thread goes on with it; the chat lists its threads, and each is read on @@ -59,11 +60,14 @@ import type {HarnessStore} from './store'; export type ChatStore = Pick< HarnessStore, | 'listPersonas' + | 'listMemberNames' | 'listAnswers' | 'ensureFirstPersona' | 'getPersona' | 'createPersona' | 'updatePersona' + | 'sharePersona' + | 'takeBackPersona' | 'deletePersona' | 'getMemberChat' | 'ensureMemberChat' @@ -94,7 +98,7 @@ export type RouteFiles = Pick HarnessRegistry; -// Whether the viewer may rename, reface, switch the harness or the model of, or delete the persona: their own, or one every member sees that they made or whose organization they own (utils/manages.ts). +// Whether the viewer may rename, reface, switch the harness or the model of, share, or delete the persona: their own, or one every member sees that they made or whose organization they own (utils/manages.ts). function managesPersona(viewer: OrgViewer, persona: PersonaRow): boolean { return manages(viewer, {ownerUserId: persona.ownerUserId, byId: persona.createdById}); } @@ -109,6 +113,32 @@ function draftPreview(persona: {draft?: string | null; draftAttachments?: DraftA return names.length === 0 ? null : preview(names.join(', ')); } +// What the page says where another member has said something to a shared persona, which its +// maker then can't make theirs alone again. +function inUse(viewer: OrgViewer, persona: PersonaRow): string { + return `Others in ${viewer.name} are using ${persona.name}, so it stays shared.`; +} + +// Why the viewer can't make a shared persona theirs alone again: General, or another one nobody +// made, is every member's; one somebody else made is theirs to take back, not the organization's +// owner's, and nobody's where they have left; and one another member has said something to stays +// everyone's. Null where they can, and for one that isn't shared. +function staysShared(viewer: OrgViewer, persona: PersonaRow, usedByOthers: boolean): string | null { + if (persona.ownerUserId !== null) { + return null; + } + if (persona.createdById === null) { + return `${persona.name} is every member’s, so it can’t be made anyone’s own.`; + } + if (persona.createdById !== viewer.userId) { + return `Only whoever made ${persona.name} can make it theirs alone.`; + } + if (usedByOthers) { + return inUse(viewer, persona); + } + return null; +} + // What runs a persona or a thread as this server offers the organization, which is what a turn of // its gets; as kept where there is no harness at all, where nothing runs. function asOffered(harnesses: Harnesses, viewer: OrgViewer, model: PersonaModel): PersonaModel { @@ -132,6 +162,35 @@ function toPersona(harnesses: Harnesses, viewer: OrgViewer, persona: PersonaRow }; } +// Who made the persona, as its settings say: the viewer, or another member by what they are called +// (`names`, by their id); nobody for one nobody made, as General, or whose maker has left. +function madeBy(viewer: OrgViewer, persona: PersonaRow, names: ReadonlyMap): ListedPersona['madeBy'] { + if (persona.createdById === null) { + return null; + } + if (persona.createdById === viewer.userId) { + return 'you'; + } + const name = names.get(persona.createdById); + return name === undefined ? null : {name}; +} + +// A persona as the list has it, with who made it, whether another member has said anything to it +// and why the viewer can't make it theirs alone, which its settings say. +function toListedPersona( + harnesses: Harnesses, + viewer: OrgViewer, + persona: PersonaRow & {usedByOthers: boolean; lastMessage?: LastMessage | null; draft?: string | null; draftAttachments?: DraftAttachment[]}, + names: ReadonlyMap, +): ListedPersona { + return { + ...toPersona(harnesses, viewer, persona), + madeBy: madeBy(viewer, persona, names), + usedByOthers: persona.usedByOthers, + staysShared: staysShared(viewer, persona, persona.usedByOthers), + }; +} + // The harnesses a persona of the viewer's organization can run on here, as the dialog offers them. function toHarnesses(registry: HarnessRegistry, viewer: OrgViewer): ChatHarness[] { return harnessesOf(offeredTo(registry, viewer)).map(({id, label, models}) => ({id, label, models})); @@ -141,20 +200,21 @@ function toHarnesses(registry: HarnessRegistry, viewer: OrgViewer): ChatHarness[ // offers it the organization: a harness named has to be one of those, and a model named one of // the harness's; the model left out is the harness's first, or the persona's own where the harness // stays. With neither named, one changed (`existing`) keeps what it has, and a new one gets the -// first harness offered with its first model. -function readPersona(harnesses: Harnesses, viewer: OrgViewer, request: AuthenticatedRequest, existing: PersonaModel | null): Result { +// first harness offered with its first model. Apart from it, whether it is to be shared with the +// organization, where that is said. +function readPersona(harnesses: Harnesses, viewer: OrgViewer, request: AuthenticatedRequest, existing: PersonaModel | null): Result<{persona: Persona; shared: boolean | undefined}, ApiError> { const parsed = parseSchema(personaBodySchema, request.body); if (parsed.isErr()) { return Err(parsed.error); } - const {harness, chatModel, ...persona} = parsed.value; + const {harness, chatModel, shared, ...persona} = parsed.value; if (existing !== null && harness === undefined && chatModel === undefined) { - return Ok(persona); + return Ok({persona, shared}); } const sameHarness = harness === undefined || harness === existing?.harness; const chosen = chosenFor(offeredTo(harnesses(), viewer), {harness: harness ?? existing?.harness ?? '', chatModel: chatModel ?? (sameHarness ? (existing?.chatModel ?? '') : '')}); if (chosen === null) { - return Ok(persona); + return Ok({persona, shared}); } if (harness !== undefined && chosen.harness.id !== harness) { return Err(ApiErr.validationError(`This server has no harness ${harness}.`)); @@ -162,7 +222,38 @@ function readPersona(harnesses: Harnesses, viewer: OrgViewer, request: Authentic if (chatModel !== undefined && chosen.model !== chatModel) { return Err(ApiErr.validationError(`${chosen.harness.label} has no model ${chatModel}.`)); } - return Ok({...persona, harness: chosen.harness.id, chatModel: chosen.model}); + return Ok({persona: {...persona, harness: chosen.harness.id, chatModel: chosen.model}, shared}); +} + +// The persona shared with the organization, or made the viewer's alone again, where `shared` says +// it is to be and it isn't yet: their own is theirs to share; a shared one is made theirs again +// only by whoever made it, and only while no other member has said anything to it, the refusal +// saying why. What it is to be, whether the viewer is the only one who has talked to it. +function reshare(store: ChatStore, viewer: OrgViewer, persona: PersonaRow, shared: boolean | undefined): Promise> { + return Do(async ($) => { + const isShared = persona.ownerUserId === null; + if (shared === undefined || shared === isShared) { + return persona; + } + if (shared && !$(await store.sharePersona(viewer.orgId, viewer.userId, persona.id))) { + return $(Err(ApiErr.notFound('persona', persona.id))); + } + if (shared) { + return {...persona, ownerUserId: null}; + } + const refused = staysShared(viewer, persona, false); + if (refused !== null) { + return $(Err(ApiErr.conflict(refused))); + } + const taken = $(await store.takeBackPersona(viewer.orgId, viewer.userId, persona.id)); + if (taken === 'used') { + return $(Err(ApiErr.conflict(inUse(viewer, persona)))); + } + if (taken === 'missing') { + return $(Err(ApiErr.notFound('persona', persona.id))); + } + return {...persona, ownerUserId: viewer.userId}; + }); } // The persona in the address, one of the organization's the viewer sees: another member's own is not found. @@ -203,12 +294,17 @@ function handleListPersonasRoute(store: ChatStore, harnesses: Harnesses, request const viewer = $(await requireViewer(request)); const personas = $(await store.listPersonas(viewer.orgId, viewer.userId)); const offered = toHarnesses(harnesses(), viewer); - const listed = personas.map((persona) => toPersona(harnesses, viewer, persona)); + // What the other members who made the shared ones are called. + const makers = new Set(personas.flatMap(({createdById}) => (createdById === null || createdById === viewer.userId ? [] : [createdById]))); + const named = $(await store.listMemberNames([...makers].map((userId) => ({orgId: viewer.orgId, userId})))); + const names = new Map(named.map(({userId, name}) => [userId, name])); + const listed = personas.map((persona) => toListedPersona(harnesses, viewer, persona, names)); if (personas.some((persona) => persona.ownerUserId === null)) { return {personas: listed, harnesses: offered}; } + // Just made, with nothing said to it yet. const general = $(await store.ensureFirstPersona(viewer.orgId)); - return {personas: [...listed, toPersona(harnesses, viewer, general)], harnesses: offered}; + return {personas: [...listed, toListedPersona(harnesses, viewer, {...general, usedByOthers: false}, names)], harnesses: offered}; }); } @@ -232,26 +328,27 @@ function handleListAnswersRoute(store: ChatStore, request: AuthenticatedRequest) }); } -/** `POST /api/orgs/:org/chat/personas` with `{name, look, color, harness?, chatModel?}`: a new persona, the viewer's own. */ +/** `POST /api/orgs/:org/chat/personas` with `{name, look, color, harness?, chatModel?, shared?}`: a new persona, the viewer's own, or every member's where `shared`. */ function handleCreatePersonaRoute(store: ChatStore, harnesses: Harnesses, request: AuthenticatedRequest): Promise, ApiError>> { return Do(async ($) => { const viewer = $(await requireViewer(request)); - const persona = $(readPersona(harnesses, viewer, request, null)); - const made = $(await store.createPersona(viewer.orgId, viewer.userId, persona)); + const {persona, shared} = $(readPersona(harnesses, viewer, request, null)); + const made = $(await store.createPersona(viewer.orgId, viewer.userId, persona, shared ?? false)); return {persona: toPersona(harnesses, viewer, made)}; }); } -/** `PUT /api/orgs/:org/chat/personas/:personaId` with `{name, look, color, harness?, chatModel?}`: the persona renamed, with another head, or switched to another harness or model from its next turn on, in every thread of every chat with it. */ +/** `PUT /api/orgs/:org/chat/personas/:personaId` with `{name, look, color, harness?, chatModel?, shared?}`: the persona renamed, with another head, or switched to another harness or model from its next turn on, in every thread of every chat with it; and shared with the organization, or made the viewer's alone again (`reshare`), first, so a refusal changes nothing. */ function handleUpdatePersonaRoute(store: ChatStore, harnesses: Harnesses, request: AuthenticatedRequest): Promise, ApiError>> { return Do(async ($) => { const viewer = $(await requireViewer(request)); const existing = $(await requireManagedPersona(store, viewer, request)); - const persona = $(readPersona(harnesses, viewer, request, existing)); + const {persona, shared} = $(readPersona(harnesses, viewer, request, existing)); + const reshared = $(await reshare(store, viewer, existing, shared)); if (!$(await store.updatePersona(viewer.orgId, existing.id, persona))) { return $(Err(ApiErr.notFound('persona', existing.id))); } - return {persona: toPersona(harnesses, viewer, {...existing, ...persona})}; + return {persona: toPersona(harnesses, viewer, {...reshared, ...persona})}; }); } diff --git a/packages/api/src/harness/store.ts b/packages/api/src/harness/store.ts index becaeb22..b6ef9761 100644 --- a/packages/api/src/harness/store.ts +++ b/packages/api/src/harness/store.ts @@ -25,6 +25,7 @@ import type { Persona, PersonaModel, PersonaRow, + TakeBack, ThreadOpening, SaidToParent, SubAgentRow, @@ -38,6 +39,7 @@ import type {TranscriptKey, TranscriptLine} from '@proxy/db/harness-transcript'; import {type AgentTaskRow, createAgentTask, getAgentTask, type NewAgentTask} from '@proxy/db/task'; import type {SignedInAgent} from '@proxy/db/agent'; import {getUserTimeZone} from '@proxy/db/user'; +import {listMemberNames} from '@proxy/db/organization'; /** * What the harness reads and writes: the job queue, each thread's log and its jobs, the Chat @@ -79,12 +81,21 @@ export type HarnessStore = { getAgentTask: (orgId: string, agentId: string, taskId: string) => Promise>; createAgentTask: (task: NewAgentTask) => Promise>; - listPersonas: (orgId: string, userId: string) => Promise, ApiError>>; + listPersonas: ( + orgId: string, + userId: string, + ) => Promise, ApiError>>; listAnswers: (orgId: string, userId: string) => Promise>; + /** What the members who made shared personas are called, those still in the organization, as the list says who made one. */ + listMemberNames: typeof listMemberNames; ensureFirstPersona: (orgId: string) => Promise>; getPersona: (orgId: string, userId: string, personaId: string) => Promise>; - createPersona: (orgId: string, userId: string, persona: Persona) => Promise>; + createPersona: (orgId: string, userId: string, persona: Persona, shared: boolean) => Promise>; updatePersona: (orgId: string, personaId: string, persona: Persona) => Promise>; + /** The member's own persona shared with the organization; false for no such persona of theirs. */ + sharePersona: (orgId: string, userId: string, personaId: string) => Promise>; + /** A shared persona its maker's own again, refused where another member has said anything to it. */ + takeBackPersona: (orgId: string, userId: string, personaId: string) => Promise>; deletePersona: (orgId: string, personaId: string) => Promise>; getMemberChat: (personaId: string, userId: string) => Promise>; ensureMemberChat: (data: {orgId: string; agentId: string; personaId: string; userId: string}) => Promise>; @@ -186,10 +197,13 @@ export const harnessStore: HarnessStore = { listPersonas: harness.listPersonas, listAnswers: harness.listAnswers, + listMemberNames, ensureFirstPersona: harness.ensureFirstPersona, getPersona: harness.getPersona, createPersona: harness.createPersona, updatePersona: harness.updatePersona, + sharePersona: harness.sharePersona, + takeBackPersona: harness.takeBackPersona, deletePersona: harness.deletePersona, getMemberChat: harness.getMemberChat, ensureMemberChat: harness.ensureMemberChat, diff --git a/packages/contracts/src/contracts.test.ts b/packages/contracts/src/contracts.test.ts index d99da098..27cc17f7 100644 --- a/packages/contracts/src/contracts.test.ts +++ b/packages/contracts/src/contracts.test.ts @@ -143,4 +143,40 @@ describe('contracts', () => { const {summary: _summary, ...withoutSummary} = thread; expect(harness.chatThreadSchema.safeParse(withoutSummary).success).toBe(false); }); + + test('a persona is made or changed shared with the organization or not, or left as it is, and is listed with who made it, whether others use it and why it stays shared', () => { + const look = {nose: 0.5, noseOut: 0.3, eye: 25, eyeTheta: 50, eyeLat: 8, eyes: 2 as const}; + const body = {name: 'Finance', look, color: 'teal' as const}; + expect(harness.personaBodySchema.parse({...body, shared: true}).shared).toBe(true); + expect(harness.personaBodySchema.parse({...body, shared: false}).shared).toBe(false); + expect(harness.personaBodySchema.parse(body).shared).toBeUndefined(); + expect(harness.personaBodySchema.safeParse({...body, shared: 'everyone'}).success).toBe(false); + + const persona: harness.ListedPersona = { + id: 'p1', + name: 'Finance', + look, + color: 'teal', + harness: 'claude-agent-sdk', + chatModel: 'sonnet', + shared: true, + mayChange: true, + madeBy: 'you', + usedByOthers: true, + staysShared: 'Others in Acme are using Finance, so it stays shared.', + lastMessage: null, + draft: null, + createdAt: '2026-03-02T09:24:00.000Z', + }; + expect(harness.listedPersonaSchema.parse(persona)).toEqual(persona); + expect( + harness.listedPersonaSchema.parse({...persona, staysShared: null}).staysShared, + ).toBeNull(); + expect(harness.listedPersonaSchema.parse({...persona, madeBy: {name: 'Dana'}}).madeBy).toEqual({ + name: 'Dana', + }); + expect(harness.listedPersonaSchema.parse({...persona, madeBy: null}).madeBy).toBeNull(); + const {usedByOthers: _used, ...withoutUse} = persona; + expect(harness.listedPersonaSchema.safeParse(withoutUse).success).toBe(false); + }); }); diff --git a/packages/contracts/src/harness.ts b/packages/contracts/src/harness.ts index 062eded7..ecd0d6f4 100644 --- a/packages/contracts/src/harness.ts +++ b/packages/contracts/src/harness.ts @@ -4,8 +4,8 @@ import {z} from 'zod'; /** * The Chat page (`/api/orgs/:org/chat/…`): the personas the person sees in the organization, - * their own and General, which every member does, each named and given a head, and the person's - * own chat with each: its threads, each opened by what they said in the chat, and what is said in + * their own and those shared with every member, General among them, each named and given a head, + * and the person's own chat with each: its threads, each opened by what they said in the chat, and what is said in * each. */ @@ -15,7 +15,10 @@ import {z} from 'zod'; * by its id, and the model it answers with, one of that harness's, by its id * (`chatHarnessSchema`). With the harness left out, a new one gets the server's first and one * changed keeps its own; with the model left out, it is the harness's first, or the persona's own - * where the harness stays. One the server hasn't got is refused. + * where the harness stays. One the server hasn't got is refused. `shared` says who sees it: every + * member, each in a chat of their own with it, or the person alone; left out, a new one is theirs + * alone and one changed stays as it is. Their own is shared by them; a shared one is made theirs + * alone again only by whoever made it, and only while no other member has said anything to it. */ export const personaBodySchema = z.object({ name: z.string().trim().pipe(z.string().min(1).max(AGENT_NAME_MAX)), @@ -23,6 +26,7 @@ export const personaBodySchema = z.object({ color: z.enum(AVATAR_COLORS), harness: z.string().optional(), chatModel: z.string().optional(), + shared: z.boolean().optional(), }); export type Persona = z.input; @@ -41,8 +45,8 @@ export const chatPersonaSchema = z.object({ /** Every member's, as General is, rather than the person's own, which nobody else sees. */ shared: z.boolean(), /** - * Whether the person may rename, reface, switch the harness or the model of, or delete it: it - * is their own, or one every member sees that they made or whose organization they own. + * Whether the person may rename, reface, switch the harness or the model of, share, or delete + * it: it is their own, or one every member sees that they made or whose organization they own. */ mayChange: z.boolean(), /** @@ -61,6 +65,31 @@ export const chatPersonaSchema = z.object({ export type ChatPersona = z.infer; +/** + * A persona as the list has it, with what its settings say of whose it is, of sharing it and of + * deleting it, read for the list alone. + */ +export const listedPersonaSchema = chatPersonaSchema.extend({ + /** + * Who made it: the person, or another member, by their name; null for one nobody made, as + * General, or whose maker is no longer in the organization. + */ + madeBy: z.union([z.literal('you'), z.object({name: z.string()})]).nullable(), + /** + * Whether another member has said anything to it, in a chat of theirs, which deleting it + * deletes too. + */ + usedByOthers: z.boolean(), + /** + * Why the person can't make it theirs alone, where it is shared, as the page says it: General, + * which nobody made; one somebody else made; or one others have said something to. Null where + * they can, and for their own. + */ + staysShared: z.string().nullable(), +}); + +export type ListedPersona = z.infer; + /** * A harness a persona can run on, as the model switcher offers it: its id, what it is called, and * the models it answers with, the first its default. @@ -79,7 +108,7 @@ export type ChatHarness = z.infer; * server has for a persona to run on, the first what a new one gets. */ export const personaListSchema = z.object({ - personas: z.array(chatPersonaSchema), + personas: z.array(listedPersonaSchema), harnesses: z.array(chatHarnessSchema), }); diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma index ad561af5..3dd140b5 100644 --- a/packages/db/prisma/schema.prisma +++ b/packages/db/prisma/schema.prisma @@ -782,8 +782,10 @@ model Persona { harness String @default("claude-agent-sdk") chatModel String @default("sonnet") // The member whose persona it is, which nobody else in the organization sees, its owner - // included; null for one every member sees, as General is, and as one from before personas - // were anyone's is where others had talked to it. + // included; null for one every member sees, as General is, as one its maker shared with the + // organization is, and as one from before personas were anyone's is where others had talked to + // it. Its maker makes a shared one theirs again only while no other member has said anything + // to it. ownerUserId String? // Who made it: who may change one every member sees, beside the organization's owner. A plain // id rather than a relation, so such a persona stays when they are gone. diff --git a/packages/db/src/harness.ts b/packages/db/src/harness.ts index 9f61d90e..34c225f0 100644 --- a/packages/db/src/harness.ts +++ b/packages/db/src/harness.ts @@ -28,8 +28,8 @@ import {signedInAgentSelect, type SignedInAgent, toSignedInAgent} from './signed import type {NewAgentTask} from './task'; /** - * The Chat page: the organization's personas, each its maker's but General, which is every - * member's, with a chat per member who sees it, and the chat's threads, each with its log and its + * The Chat page: the organization's personas, each its maker's alone or shared with every member, + * as General is, with a chat per member who sees it, and the chat's threads, each with its log and its * jobs. A chat runs no agent of its own: it keeps what the member typed and hasn't sent, the files * in its input and how far they have read, and every message they post in it opens a thread, whose * agent answers them there. The member's reply, or an alert set in the thread, takes the thread up @@ -291,6 +291,16 @@ export const personaSelect = { createdAt: true, } as const; +// The threads of other members than `userId` with a persona that hold anything said: a thread +// opened in their chat, or an entry in the chat itself, as one from before chats held threads may +// have. A chat no more than opened, with a draft at most, is not talking to it. +function saidToByOthers(userId: string) { + return { + userId: {not: userId}, + OR: [{parentThreadId: {not: null}}, {entries: {some: {}}}], + } satisfies Prisma.AgentThreadWhereInput; +} + // The organization's personas a member sees: their own, and those every member does. function seenBy(orgId: string, userId: string) { return { @@ -373,8 +383,9 @@ function toToolCalls(kept: string | null): ToolCall[] | null { /** * The organization's personas the member sees, their own and those every member does, with the * last thing said in the member's chat with each, across the chat and its threads, what they typed - * in it and the files they put in its input and haven't sent, the one last active first: the last - * thing said in it, or, before anything was, its making. + * in it and the files they put in its input and haven't sent, and whether any other member has + * said anything to it, the one last active first: the last thing said in it, or, before anything + * was, its making. */ export async function listPersonas( orgId: string, @@ -386,6 +397,7 @@ export async function listPersonas( lastMessage: LastMessage | null; draft: string | null; draftAttachments: DraftAttachment[]; + usedByOthers: boolean; } >, ApiError @@ -396,6 +408,7 @@ export async function listPersonas( where: seenBy(orgId, userId), select: { ...personaSelect, + _count: {select: {threads: {where: saidToByOthers(userId)}}}, // The member's chat and its threads, but those an alert opened and its agent dismissed // (or the member archived), which said nothing to them. threads: { @@ -421,8 +434,9 @@ export async function listPersonas( }, orderBy: {createdAt: 'desc'}, }); - const listed = personas.map(({threads, ...persona}) => ({ + const listed = personas.map(({threads, _count, ...persona}) => ({ persona, + usedByOthers: _count.threads > 0, chat: threads.find((thread) => thread.parentThreadId === null), last: threads.flatMap((thread) => thread.entries).toSorted((a, b) => b.seq - a.seq)[0], })); @@ -437,10 +451,11 @@ export async function listPersonas( }); const textOf = new Map(said.map((entry) => [entry.id, entry.text])); return listed - .map(({persona, chat, last}) => { + .map(({persona, usedByOthers, chat, last}) => { const text = last ? textOf.get(last.id) : undefined; return { ...toPersona(persona), + usedByOthers, lastMessage: last && text !== undefined && (last.kind === 'person' || last.kind === 'assistant') ? {kind: last.kind, text, createdAt: last.createdAt} @@ -618,18 +633,19 @@ export async function getPersona( ).map((persona) => (persona ? toPersona(persona) : null)); } -/** A new persona in the organization, the member's own, which they made. */ +/** A new persona in the organization, which the member made: their own, or, `shared`, every member's from the start. */ export async function createPersona( orgId: string, userId: string, persona: Persona, + shared = false, ): Promise> { return ( await wrapDb(() => db.persona.create({ data: { orgId, - ownerUserId: userId, + ownerUserId: shared ? null : userId, createdById: userId, name: persona.name, look: JSON.stringify(persona.look), @@ -665,6 +681,68 @@ export async function updatePersona( ).map(({count}) => count > 0); } +/** + * Shares the member's own persona with the organization: every member sees it from then on, each + * with a chat of their own with it, and the member's chat stays as it is. `Ok(false)` means no + * such persona of theirs in the organization. + */ +export async function sharePersona( + orgId: string, + userId: string, + personaId: string, +): Promise> { + return ( + await wrapDb(() => + db.persona.updateMany({ + where: {id: personaId, orgId, ownerUserId: userId}, + data: {ownerUserId: null}, + }), + ) + ).map(({count}) => count > 0); +} + +/** + * What making a shared persona its maker's own again came to: done; refused, since another member + * has said something to it; or no such persona, shared and made by them, in the organization. + */ +export type TakeBack = 'taken' | 'used' | 'missing'; + +/** + * Makes a shared persona its maker's own again, while no other member has said anything to it: + * their chat stays as it is, and the chats other members opened with it and said nothing in, a + * draft at most, go. The persona's row is locked, so no member's first chat with it is made + * meanwhile (ensureMemberChat), and so are the other members' chats with it, so no thread is opened + * in one meanwhile (openThread): what was said before is seen, and nothing is said after. + */ +export async function takeBackPersona( + orgId: string, + userId: string, + personaId: string, +): Promise> { + return wrapDb(() => + db.$transaction(async (tx): Promise => { + const locked = await tx.$queryRaw>` + SELECT "id" FROM "Persona" + WHERE "id" = ${personaId} AND "orgId" = ${orgId} AND "ownerUserId" IS NULL + AND "createdById" = ${userId} + FOR UPDATE`; + if (locked.length === 0) { + return 'missing'; + } + await tx.$queryRaw` + SELECT "id" FROM "AgentThread" + WHERE "personaId" = ${personaId} AND "parentThreadId" IS NULL AND "userId" <> ${userId} + FOR UPDATE`; + if ((await tx.agentThread.count({where: {personaId, ...saidToByOthers(userId)}})) > 0) { + return 'used'; + } + await tx.agentThread.deleteMany({where: {personaId, userId: {not: userId}}}); + await tx.persona.update({where: {id: personaId}, data: {ownerUserId: userId}}); + return 'taken'; + }), + ); +} + /** Deletes a persona with every chat with it; `Ok(false)` means no such persona in the organization. */ export async function deletePersona( orgId: string, diff --git a/packages/db/src/persona-sharing.test.ts b/packages/db/src/persona-sharing.test.ts new file mode 100644 index 00000000..0674e592 --- /dev/null +++ b/packages/db/src/persona-sharing.test.ts @@ -0,0 +1,166 @@ +import {afterAll, beforeAll, describe, expect, test} from 'bun:test'; +import type {Result} from 'ts-results-es'; + +import type {ApiError} from '@proxy/utils'; +import {readyForInference} from '@proxy/utils/harness'; + +import {db} from '.'; +import { + createPersona, + ensureFirstPersona, + ensureMemberChat, + getMemberChat, + getPersona, + listPersonas, + openThread, + saveChatDraft, + sharePersona, + takeBackPersona, + type ThreadRow, +} from './harness'; + +// Sharing a persona with the organization and taking it back, against a database, as +// harness.test.ts runs: with `bun run test:db` from the repository's root; skipped without +// DATABASE_URL. Everything made here is one organization's, deleted at the end. +const databaseUrl = process.env.DATABASE_URL; + +function unwrap(result: Result): T { + if (result.isErr()) { + throw new Error(JSON.stringify(result.error)); + } + return result.value; +} + +const look = {nose: 0.5, noseOut: 0.3, eye: 25, eyeTheta: 50, eyeLat: 8, eyes: 2 as const}; + +describe.skipIf(!databaseUrl)('sharing a persona, against the database', () => { + const stamp = `${Date.now()}-${process.pid}`; + let maker = ''; + let other = ''; + let orgId = ''; + let agentId = ''; + + // The member's chat with the persona, made where they have none. + function chatOf(personaId: string, userId: string): Promise { + return ensureMemberChat({orgId, agentId, personaId, userId}).then(unwrap); + } + + // A thread the member opens in their chat with what they say. + async function say(chat: ThreadRow, text: string) { + const task = { + orgId, + agentId, + ownerUserId: chat.userId, + personaId: chat.personaId, + parentId: null, + title: text, + goal: text, + via: 'harness' as const, + }; + return unwrap(await openThread(chat.id, text, {title: text, task}, readyForInference)); + } + + // Whether others have talked to the persona, as the list `userId` sees says. + async function usedByOthers(userId: string, personaId: string) { + return unwrap(await listPersonas(orgId, userId)).find(({id}) => id === personaId)?.usedByOthers; + } + + beforeAll(async () => { + maker = (await db.user.create({data: {email: `sharing-test-${stamp}@example.test`}})).id; + other = (await db.user.create({data: {email: `sharing-test-other-${stamp}@example.test`}})).id; + const org = await db.organization.create({ + data: {name: 'Sharing test', slug: `sharing-test-${stamp}`, ownerUserId: maker}, + }); + orgId = org.id; + await db.orgMember.createMany({ + data: [ + {orgId, userId: maker}, + {orgId, userId: other}, + ], + }); + const agent = await db.agent.create({ + data: { + orgId, + providerId: 'proxy', + name: 'Built in', + username: `sharing-test-${stamp}`, + passwordHash: '', + }, + }); + agentId = agent.id; + unwrap(await ensureFirstPersona(orgId)); + }); + + afterAll(async () => { + if (orgId !== '') { + await db.organization.delete({where: {id: orgId}}); + } + await db.user.deleteMany({where: {id: {in: [maker, other].filter((id) => id !== '')}}}); + await db.$disconnect(); + }); + + test('a persona shared with the organization is seen by every member, the maker’s chat staying theirs, and another member’s starting empty', async () => { + const finance = unwrap( + await createPersona(orgId, maker, {name: 'Finance', look, color: 'teal'}), + ); + const makersChat = await chatOf(finance.id, maker); + await say(makersChat, 'Sum up the invoices from March.'); + expect(unwrap(await getPersona(orgId, other, finance.id))).toBeNull(); + + // Only its owner shares it. + expect(unwrap(await sharePersona(orgId, other, finance.id))).toBe(false); + expect(unwrap(await sharePersona(orgId, maker, finance.id))).toBe(true); + + expect(unwrap(await getPersona(orgId, other, finance.id))).toMatchObject({ + ownerUserId: null, + createdById: maker, + }); + expect(unwrap(await getMemberChat(finance.id, maker))?.id).toBe(makersChat.id); + expect(unwrap(await getMemberChat(finance.id, other))).toBeNull(); + const othersChat = await chatOf(finance.id, other); + expect(othersChat.id).not.toBe(makersChat.id); + const listed = unwrap(await listPersonas(orgId, other)).find(({id}) => id === finance.id); + expect(listed).toMatchObject({lastMessage: null, draft: null, usedByOthers: true}); + // The maker sees nobody else has said anything to it yet: a chat opened is not talking. + expect(await usedByOthers(maker, finance.id)).toBe(false); + }); + + test('a persona made shared is every member’s from the start, and its maker takes it back while others have only opened their chat with it, which goes', async () => { + const travel = unwrap( + await createPersona(orgId, maker, {name: 'Travel', look, color: 'blue'}, true), + ); + expect(travel).toMatchObject({ownerUserId: null, createdById: maker}); + const makersChat = await chatOf(travel.id, maker); + await say(makersChat, 'Book the train to Lyon.'); + const othersChat = await chatOf(travel.id, other); + unwrap(await saveChatDraft(othersChat.id, 'Find a hotel near')); + + // Only the maker takes it back. + expect(unwrap(await takeBackPersona(orgId, other, travel.id))).toBe('missing'); + expect(unwrap(await takeBackPersona(orgId, maker, travel.id))).toBe('taken'); + + expect(unwrap(await getPersona(orgId, maker, travel.id))?.ownerUserId).toBe(maker); + expect(unwrap(await getPersona(orgId, other, travel.id))).toBeNull(); + expect(unwrap(await getMemberChat(travel.id, maker))?.id).toBe(makersChat.id); + expect(await db.agentThread.count({where: {parentThreadId: makersChat.id}})).toBe(1); + expect(await db.agentThread.count({where: {id: othersChat.id}})).toBe(0); + // Its own already: nothing to take back. + expect(unwrap(await takeBackPersona(orgId, maker, travel.id))).toBe('missing'); + }); + + test('a shared persona another member has said something to stays shared, as General always does', async () => { + const billing = unwrap( + await createPersona(orgId, maker, {name: 'Billing', look, color: 'pink'}, true), + ); + await say(await chatOf(billing.id, other), 'Which invoices are still open?'); + + expect(await usedByOthers(maker, billing.id)).toBe(true); + expect(unwrap(await takeBackPersona(orgId, maker, billing.id))).toBe('used'); + expect(unwrap(await getPersona(orgId, other, billing.id))?.ownerUserId).toBeNull(); + + const general = unwrap(await ensureFirstPersona(orgId)); + expect(general.createdById).toBeNull(); + expect(unwrap(await takeBackPersona(orgId, maker, general.id))).toBe('missing'); + expect(unwrap(await getPersona(orgId, other, general.id))?.ownerUserId).toBeNull(); + }); +}); diff --git a/packages/docs/content/agents/chat.mdx b/packages/docs/content/agents/chat.mdx index fef510d9..12bdc1f6 100644 --- a/packages/docs/content/agents/chat.mdx +++ b/packages/docs/content/agents/chat.mdx @@ -8,19 +8,30 @@ organization starts with one, **General**, which every member sees. An agent you alone: make one with **New agent**, giving it a name and a head, or ask for one from [the command bar](/quick-actions#handing-it-to-an-agent), and nobody else in the organization sees it, its owner included; you rename it, change its head or delete it. General is renamed or deleted -by the organization's owner. All of them act through one entry on the **External agents** page, +by the organization's owner, and stays everyone's. All of them act through one entry on the +**External agents** page, Chat, shared with everyone, as Claude or ChatGPT are one entry each however many assistants run inside them: what the agents may do with each connection is set in its column, once for all of them, and every call any of them makes is in the activity log, by the task it was made for, which says which agent it was. Click an agent's name over its list of tasks, or choose **Settings** from its right-click menu in -the list, to open its settings at the right, beside the task you have open: whose it is, and -deleting it at the foot. **Edit** there changes its name and head. Click the name again, press -Back or the cross to close them. - -Your chat with an agent is yours alone, as a direct message is, General's too: nobody else in the -organization sees it. In it, the agent acts as you, so it reaches what you use: the connections +the list, to open its settings at the right, beside the task you have open: whose it is, who sees +it, and deleting it at the foot. **Edit** there changes its name and head; who sees it holds as soon +as you choose it. Click the name again, press Back or the cross to close them. + +You can share an agent of yours with the organization: in its settings, under **Who sees it**, +choose **Everyone in** it. Every member then sees it, each with a chat of their own with it, as +with General, and it answers each of them as them. Its name, head, model and harness are the same +for everyone. Your own chat with it, and its tasks, stay as they were. Once anyone else is in the +organization, a shared agent has a mark beside its name in the list. You can make it yours alone +again with **Only you** while nobody else has said anything to it; once someone has, it stays +shared, and its settings say so. A shared agent is renamed, changed or deleted by whoever made it +and by the organization's owner, who can't make it theirs alone. Deleting a shared agent deletes +every member's chat with it. + +Your chat with an agent is yours alone, as a direct message is, a shared agent's too: nobody else +in the organization sees it. In it, the agent acts as you, so it reaches what you use: the connections shared with everyone, the ones shared with you by name, the ones you connected yourself and your own vault. Chat has a column on every connection's **Permissions**, beside your other agents, which whoever changes the connection's defaults changes: you on your own connections, the organization's @@ -35,13 +46,14 @@ member's own [Claude account](#your-claude-subscription). Under the message box, a chat says what runs its agent: the **model**, and beside it the **harness**, the loop that runs its turns. For whoever may change the agent, you for one of your -own and the organization's owner for General, it opens the harnesses down the side, each by its +own, whoever made a shared one, and the organization's owner for any shared one, General among +them, it opens the harnesses down the side, each by its mark, with the models of the one you look at beside them to switch between. The choice is the agent's: every thread opened from then on, in any member's chat with the agent, starts with it. Threads already open keep what they run on. A thread's own message box says what runs it, and you can switch it there, in any thread of yours, -General's included: it holds for that thread alone from its next turn on, and the thread goes on +a shared agent's included: it holds for that thread alone from its next turn on, and the thread goes on from where it was. The agent, and its other threads, stay as they are. - **Claude** runs on each member's own [Claude account](#your-claude-subscription), with diff --git a/packages/docs/content/organizations.mdx b/packages/docs/content/organizations.mdx index b294e6ee..23406fee 100644 --- a/packages/docs/content/organizations.mdx +++ b/packages/docs/content/organizations.mdx @@ -56,6 +56,14 @@ An agent login is yours or shared with the organization, the same way a connecti as whoever talks to it, so it reaches every connection they use, and has a column on each. Its settings on a connection are changed by whoever changes the connection's defaults. +An agent you make on the Chat page is yours alone until you share it: in its settings (click its +name over its list of tasks), **Everyone in** the organization under **Who sees it** shows it to +every member, each with a chat of their own with it that nobody else reads, and in each it acts as +whoever is talking to it, with what they use, as General does. You can make it yours alone again +with **Only you** as long as nobody else has said anything to it; after that it stays shared. +Whoever made it and the organization's owner rename it, change it and delete it, with every +member's chat with it. + Once anyone else is in the organization, or invited to it, **New agent** asks who the agent is for, and **External agents** lists the two apart. On the page of an agent of your own, **Share with everyone** under **Sharing** shares it, for good. What it did on connections shared with everyone so far @@ -86,9 +94,9 @@ one. Your own account is under **Account**, at the foot of the sidebar, with eve organization you are in. Leaving, or being removed, disconnects what you connected there, what you shared with members by name included, and deletes your own agents there, the agents you made in [Chat](/agents/chat) and -your chats there among them, and signs out the MCP clients you signed in as its shared +kept to yourself and your chats there among them, and signs out the MCP clients you signed in as its shared agents. What you shared with everyone stays, the organization's owner's from then on, -and so do the shared agents. The shared agents you made, whose passwords you were shown, get one +and so do the shared agents, those of Chat among them, which the owner changes from then on. The shared agents you made, whose passwords you were shown, get one nobody knows and are signed out everywhere, until the owner hands them a new one; another shared agent's password a former member knows keeps working until whoever manages the agent resets it. Deleting an organization disconnects every connection in it, whoever's it is, and deletes its vaults, every agent and its diff --git a/packages/web/src/client/harness-client.ts b/packages/web/src/client/harness-client.ts index 4860fc18..abd9caf5 100644 --- a/packages/web/src/client/harness-client.ts +++ b/packages/web/src/client/harness-client.ts @@ -22,10 +22,10 @@ import type {z} from 'zod'; import {apiRequest, apiSend, apiUpload, orgApi} from '@/client/request'; import {rememberPersonaList} from '@/lib/persona-list'; -// The Chat page's api: the personas the person sees, their own and General, which every member -// does, each named and given a head, and the person's own chat with each: its threads, each -// opened by what they said in the chat and read on its own, what they reply in one, what they -// typed in the chat and haven't sent, and how far they have read it. +// The Chat page's api: the personas the person sees, their own and those shared with every +// member, General among them, each named and given a head, and the person's own chat with each: +// its threads, each opened by what they said in the chat and read on its own, what they reply in +// one, what they typed in the chat and haven't sent, and how far they have read it. // How long a list asked for ahead of Chat's opening is fresh enough not to ask again. const PREFETCH_GAP_MS = 10 * 1000; diff --git a/packages/web/src/components/command-palette.test.tsx b/packages/web/src/components/command-palette.test.tsx index 6a2b9aa6..64a8e83e 100644 --- a/packages/web/src/components/command-palette.test.tsx +++ b/packages/web/src/components/command-palette.test.tsx @@ -2,7 +2,7 @@ import type {AgentLogin} from '@proxy/contracts/agents'; import type {Connection} from '@proxy/contracts/connections'; -import type {ChatPersona} from '@proxy/contracts/harness'; +import type {ListedPersona} from '@proxy/contracts/harness'; import {afterEach, beforeEach, describe, expect, setSystemTime, test} from 'bun:test'; import {cleanup, fireEvent, render, screen, waitFor, within} from '@testing-library/react'; import {createMemoryRouter, RouterProvider, useLocation} from 'react-router'; @@ -14,12 +14,15 @@ import {clearWidgetLookups} from '@/test-widgets-api'; const look = {nose: 0.48, noseOut: 0.35, eye: 27, eyeTheta: 55, eyeLat: 8, eyes: 2 as const}; -function persona(id: string, name: string, shared: boolean): ChatPersona { +function persona(id: string, name: string, shared: boolean): ListedPersona { return { id, name, shared, mayChange: true, + madeBy: 'you', + usedByOthers: false, + staysShared: null, look, color: 'blue', harness: 'proxy', diff --git a/packages/web/src/components/pane-row.tsx b/packages/web/src/components/pane-row.tsx new file mode 100644 index 00000000..d38da9fd --- /dev/null +++ b/packages/web/src/components/pane-row.tsx @@ -0,0 +1,2 @@ +/** A card of a pane beside a page: outlined, as the card that deletes something is, so each setting stands on its own. */ +export const PANE_CARD = 'rounded-xl border bg-card p-4'; diff --git a/packages/web/src/components/persona-pane.tsx b/packages/web/src/components/persona-pane.tsx index 84890bea..2c1e7355 100644 --- a/packages/web/src/components/persona-pane.tsx +++ b/packages/web/src/components/persona-pane.tsx @@ -1,28 +1,54 @@ -import type {ChatPersona} from '@proxy/contracts/harness'; +import type {ListedPersona} from '@proxy/contracts/harness'; +import {useState} from 'react'; import {PillButton} from '@proxy/ui/components/pill-button'; +import {PillTab} from '@proxy/ui/components/pill-tab'; +import {cn} from '@proxy/ui/lib/utils'; +import {updatePersona} from '@/client/harness-client'; import {DangerCard} from '@/components/danger-card'; import {LiveHead} from '@/components/head'; +import {PANE_CARD} from '@/components/pane-row'; +import {useOrgSlug} from '@/hooks/use-org'; +import {useReload} from '@/hooks/use-reload'; +import {describeApiError} from '@/lib/loader-utils'; -// Whose the agent is, in a line under its name. -function whoseLine(persona: ChatPersona, orgName: string): string { +const LINE = 'text-sm text-muted-foreground'; + +// Whose the agent is, in a line under its name: a shared one by who made it, or, where nobody did, +// as General, or its maker has left the organization, just whom it is for. +function whoseLine(persona: ListedPersona, orgName: string): string { if (!persona.shared) { return 'Yours alone'; } + if (persona.madeBy === 'you') { + return `Made by you, for everyone in ${orgName}`; + } + if (persona.madeBy !== null) { + return `Made by ${persona.madeBy.name}`; + } return `For everyone in ${orgName}`; } -// What deleting the agent takes with it: the person's conversation with it, and for one every -// member sees, everyone's. -function deleteCardLine(persona: ChatPersona): string { - const conversations = persona.shared - ? `Every member’s conversation with ${persona.name} goes with it.` +// What the choice of who sees it means, in a line. +function sharingLine(shared: boolean, orgName: string): string { + if (shared) { + return 'Each person’s conversation with it is their own.'; + } + return `Nobody else in ${orgName} sees it.`; +} + +// What deleting the agent takes with it: every member's conversation where others have talked to +// it, the person's own otherwise. +function deleteCardLine(persona: ListedPersona): string { + const conversations = persona.usedByOthers + ? `Every member’s conversation with ${persona.name} goes with it, not only yours: others have talked to it.` : `Your conversation with ${persona.name} goes with it.`; return `${conversations} This cannot be undone.`; } // The pane's content, scrolling within itself: the agent, whose it is, and Edit, which opens its -// name and head in their dialog; and, at the pane's foot however short the rest, the card that -// deletes it. Without `mayChange`, it is read alone: neither Edit nor the card. +// name and head in their dialog; a card for who sees it, which holds as it is chosen; and, at the +// pane's foot however short the rest, the card that deletes it. Without `mayChange`, it is read +// alone: who sees it said, and neither Edit, the choice nor the card. export function PersonaSettings({ orgName, persona, @@ -30,10 +56,40 @@ export function PersonaSettings({ onDelete, }: { orgName: string; - persona: ChatPersona; + persona: ListedPersona; onEdit: () => void; onDelete: () => void; }) { + const org = useOrgSlug(); + const reload = useReload(); + // Who sees it as just chosen, while the server is told; and what it refused it with. + const [choosing, setChoosing] = useState(null); + const [refused, setRefused] = useState(null); + const shared = choosing ?? persona.shared; + // A shared one that can't go back to the person alone: why, said up front. + const keptShared = persona.shared && persona.staysShared !== null; + + const choose = async (next: boolean) => { + if (next === shared || choosing !== null) { + return; + } + setChoosing(next); + setRefused(null); + const changed = await updatePersona(org, persona.id, { + name: persona.name, + look: persona.look, + color: persona.color, + shared: next, + }); + if (changed.isErr()) { + setChoosing(null); + setRefused(describeApiError(changed.error)); + return; + } + await reload(); + setChoosing(null); + }; + return (
    @@ -41,7 +97,7 @@ export function PersonaSettings({
    {persona.name} - {whoseLine(persona, orgName)} + {whoseLine(persona, orgName)}
    {persona.mayChange && ( @@ -49,6 +105,43 @@ export function PersonaSettings({ )}
    +
    +
    +

    Who sees it

    +

    + {persona.mayChange + ? sharingLine(shared, orgName) + : `Everyone in ${orgName}. Each person’s conversation with it is their own.`} +

    +
    + {persona.mayChange && ( +
    + void choose(false)} + > + Only you + + void choose(true)} + > + Everyone in {orgName} + +
    + )} + {persona.mayChange && keptShared &&

    {persona.staysShared}

    } + {refused !== null &&

    {refused}

    } +
    {persona.mayChange && (
    void; - onDelete: (persona: ChatPersona) => void; + // in another; who sees it is chosen in the pane itself. + onEdit: (persona: ListedPersona) => void; + onDelete: (persona: ListedPersona) => void; }; /** Whether the address opens the agent's settings, and the pane as the page draws it while it does. */ @@ -36,8 +36,8 @@ export type PersonaPane = {open: boolean; pane: Pane | undefined}; * An agent's settings, in a pane at the Chat page's right, beside the task open (`AppShell`'s * pane), at an address of its own (`settingsPath`) under the chat's or the open task's, so the task * stays open beside them and Back closes them as their cross does: the agent, whose it is, and - * Edit, which opens its name and head in their dialog; and, at the foot, deleting it. A member who - * may not change it reads it alone. + * Edit, which opens its name and head in their dialog; who sees it, the person alone or everyone in + * the organization; and, at the foot, deleting it. A member who may not change it reads it alone. */ export function usePersonaPane({ orgName, diff --git a/packages/web/src/lib/command-bar.ts b/packages/web/src/lib/command-bar.ts index 4172abac..2ef65ae2 100644 --- a/packages/web/src/lib/command-bar.ts +++ b/packages/web/src/lib/command-bar.ts @@ -339,8 +339,8 @@ function mentionedPersona(text: string, personas: ChatPersona[]): ChatPersona | return patternsOf(personas).find(({named}) => named.test(text))?.persona ?? null; } -// The persona a message goes to when it names none: General, which is the one every member -// sees, the oldest of them; without one, the conversation last active. +// The persona a message goes to when it names none: the oldest of those every member sees, which +// is General where the organization has it; without one, the conversation last active. function defaultPersona(personas: ChatPersona[]): ChatPersona | null { const [general] = personas .filter((persona) => persona.shared) diff --git a/packages/web/src/pages/chat-page.test.tsx b/packages/web/src/pages/chat-page.test.tsx index 6ff4f6e8..8e684da8 100644 --- a/packages/web/src/pages/chat-page.test.tsx +++ b/packages/web/src/pages/chat-page.test.tsx @@ -3,9 +3,9 @@ import type { ChatAnswer, ChatAttachment, - ChatPersona, ChatThread, ChatThreads, + ListedPersona, ThreadMessage, ThreadView, } from '@proxy/contracts/harness'; @@ -29,12 +29,15 @@ const realFetch = globalThis.fetch; const fetchMock = mock<(input: string, init?: RequestInit) => Promise>(); const look = {nose: 0.48, noseOut: 0.35, eye: 27, eyeTheta: 55, eyeLat: 8, eyes: 2 as const}; -function persona(id: string, name: string, mayChange: boolean): ChatPersona { +function persona(id: string, name: string, mayChange: boolean): ListedPersona { return { id, name, shared: false, mayChange, + madeBy: 'you', + usedByOthers: false, + staysShared: null, look, color: 'blue', harness: 'proxy', @@ -57,7 +60,8 @@ const harnesses = [ }, ]; -const general = persona('general', 'General', false); +// General, which nobody made. +const general = {...persona('general', 'General', false), madeBy: null}; const finance = persona('finance', 'Finance', true); // A thread of General's chat, as the chat lists it: one the person opened, stopped, unless a test @@ -182,15 +186,16 @@ function renderChatPage({ draft = null, draftAttachments = [], chatAlerts = 0, + others = false, answered = () => Promise.resolve(), threadAnswered = () => Promise.resolve(), initial, }: { - personas?: ChatPersona[]; + personas?: ListedPersona[]; // The open chat's threads, as the chat is read each time. threads?: ChatThread[]; listThreads?: () => ChatThread[]; - listPersonas?: () => ChatPersona[]; + listPersonas?: () => ListedPersona[]; // Each thread as its page shows it, by its id. views?: Record; // The agent whose chat is open, by its id. @@ -200,6 +205,8 @@ function renderChatPage({ draftAttachments?: ChatThreads['draftAttachments']; // How many of the open chat's alerts open threads of their own. chatAlerts?: number; + // Whether anyone else is in the organization. + others?: boolean; // When the api answers for a chat: at once, unless a test holds it back. answered?: (personaId: string) => Promise; // When the api answers for a thread: at once, unless a test holds it back. @@ -212,7 +219,7 @@ function renderChatPage({ [ { id: 'human', - loader: () => testHuman(testOrg), + loader: () => testHuman({...testOrg, memberCount: others ? 3 : 1}), element: , children: [ { @@ -569,6 +576,34 @@ describe('ChatPage', () => { }); }); + test('marks a shared agent beside its name once anyone else is in the organization, and not while the person is alone in it', async () => { + const travel = {...persona('travel', 'Travel', true), shared: true}; + renderChatPage({personas: [{...general, shared: true}, finance, travel], others: true}); + + const row = await screen.findByRole('link', {name: /Travel/}); + expect(within(row).getByRole('img', {name: 'Everyone in Acme'})).toBeDefined(); + expect( + within(screen.getByRole('link', {name: /Finance/})).queryByRole('img', { + name: 'Everyone in Acme', + }), + ).toBeNull(); + cleanup(); + + renderChatPage({personas: [{...general, shared: true}, finance, travel]}); + const alone = await screen.findByRole('link', {name: /Travel/}); + expect(within(alone).queryByRole('img', {name: 'Everyone in Acme'})).toBeNull(); + }); + + test('says deleting a shared agent others have talked to deletes their conversations with it too', async () => { + const travel = {...persona('travel', 'Travel', true), shared: true, usedByOthers: true}; + renderChatPage({personas: [general, finance, travel], others: true}); + + fireEvent.contextMenu(await screen.findByRole('link', {name: /Travel/})); + fireEvent.click(await screen.findByRole('menuitem', {name: 'Delete'})); + + expect(screen.getByText(/every member's conversation with it, not only yours/)).toBeDefined(); + }); + test('offers an agent the person may not change its settings alone in its right-click menu', async () => { renderChatPage(); @@ -1771,7 +1806,13 @@ describe('ChatPage', () => { const pane = await screen.findByRole('region', {name: 'Agent settings'}); expect(router.state.location.pathname).toBe('/acme/chat/general/settings'); expect(within(pane).getByText('For everyone in Acme')).toBeTruthy(); + expect( + within(pane).getByText( + 'Everyone in Acme. Each person’s conversation with it is their own.', + ), + ).toBeTruthy(); expect(within(pane).queryByRole('button', {name: 'Edit'})).toBeNull(); + expect(within(pane).queryByRole('button', {name: 'Only you'})).toBeNull(); expect(within(pane).queryByRole('button', {name: 'Delete agent'})).toBeNull(); await act(async () => { @@ -1782,13 +1823,18 @@ describe('ChatPage', () => { ); }); - test('show an agent the person may change: its name, whose it is, Edit, and the card that deletes it', async () => { + test('show an agent the person may change: its name, whose it is, Edit, who sees it, and the card that deletes it', async () => { renderChatPage({open: 'finance', initial: '/acme/chat/finance/settings'}); const pane = await screen.findByRole('region', {name: 'Agent settings'}); expect(within(pane).getByText('Finance')).toBeTruthy(); expect(within(pane).getByText('Yours alone')).toBeTruthy(); expect(within(pane).getByRole('button', {name: 'Edit'})).toBeTruthy(); + expect(within(pane).getByRole('region', {name: 'Who sees it'})).toBeTruthy(); + expect( + within(pane).getByRole('button', {name: 'Only you'}).getAttribute('aria-pressed'), + ).toBe('true'); + expect(within(pane).getByText('Nobody else in Acme sees it.')).toBeTruthy(); expect(within(pane).getByRole('heading', {name: 'Delete Finance'})).toBeTruthy(); expect( within(pane).getByText( @@ -1797,6 +1843,100 @@ describe('ChatPage', () => { ).toBeTruthy(); }); + test('say whose a shared agent is: made by the person, by another member, or, where nobody did or its maker has left, whom it is for', async () => { + const travel = {...persona('travel', 'Travel', true), shared: true}; + const research = { + ...persona('research', 'Research', false), + shared: true, + madeBy: {name: 'Dana'}, + }; + const everyone = {...general, shared: true}; + const lines: Array<[ListedPersona, string]> = [ + [travel, 'Made by you, for everyone in Acme'], + [research, 'Made by Dana'], + [everyone, 'For everyone in Acme'], + ]; + for (const [shown, line] of lines) { + renderChatPage({ + personas: [everyone, travel, research], + open: shown.id, + initial: `/acme/chat/${shown.id}/settings`, + }); + const pane = await screen.findByRole('region', {name: 'Agent settings'}); + expect(within(pane).getByText(line)).toBeTruthy(); + cleanup(); + } + }); + + test('share the agent as soon as everyone is chosen, without a Save', async () => { + answering((_input, init) => + init?.method === 'PUT' + ? Promise.resolve(Response.json({persona: {...finance, shared: true}})) + : null, + ); + renderChatPage({open: 'finance', initial: '/acme/chat/finance/settings', others: true}); + const pane = await screen.findByRole('region', {name: 'Agent settings'}); + + fireEvent.click(within(pane).getByRole('button', {name: 'Everyone in Acme'})); + + expect( + within(pane).getByRole('button', {name: 'Everyone in Acme'}).getAttribute('aria-pressed'), + ).toBe('true'); + expect( + within(pane).getByText('Each person’s conversation with it is their own.'), + ).toBeTruthy(); + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledWith( + '/api/orgs/acme/chat/personas/finance', + expect.objectContaining({ + method: 'PUT', + body: JSON.stringify({name: 'Finance', look, color: 'blue', shared: true}), + }), + ); + }); + expect(within(pane).queryByRole('button', {name: 'Save'})).toBeNull(); + }); + + test('say in place why the agent can’t be the person’s alone, up front and where the api refuses it', async () => { + const refusal = 'Others in Acme are using Finance, so it stays shared.'; + const kept = {...finance, shared: true, usedByOthers: true, staysShared: refusal}; + renderChatPage({ + personas: [general, kept], + open: 'finance', + initial: '/acme/chat/finance/settings', + }); + let pane = await screen.findByRole('region', {name: 'Agent settings'}); + expect(within(pane).getByRole('button', {name: 'Only you'}).hasAttribute('disabled')).toBe( + true, + ); + expect(within(pane).getByText(refusal)).toBeTruthy(); + expect( + within(pane).getByText( + 'Every member’s conversation with Finance goes with it, not only yours: others have talked to it. This cannot be undone.', + ), + ).toBeTruthy(); + cleanup(); + + // Someone said something to it since the list was read. + answering((_input, init) => + init?.method === 'PUT' + ? Promise.resolve(Response.json({error: 'conflict', message: refusal}, {status: 409})) + : null, + ); + renderChatPage({ + personas: [general, {...finance, shared: true}], + open: 'finance', + initial: '/acme/chat/finance/settings', + }); + pane = await screen.findByRole('region', {name: 'Agent settings'}); + fireEvent.click(within(pane).getByRole('button', {name: 'Only you'})); + + expect(await within(pane).findByText(refusal)).toBeTruthy(); + expect( + within(pane).getByRole('button', {name: 'Everyone in Acme'}).getAttribute('aria-pressed'), + ).toBe('true'); + }); + test('open the name and the head in their dialog from Edit, saved by Save', async () => { answering((_input, init) => init?.method === 'PUT' @@ -1811,6 +1951,7 @@ describe('ChatPage', () => { ); expect(screen.getByRole('heading', {name: 'Edit agent'})).toBeDefined(); + expect(within(screen.getByRole('dialog')).queryByText('Who sees it')).toBeNull(); fireEvent.change(screen.getByLabelText('Name'), {target: {value: 'Accounting'}}); fireEvent.click(screen.getByRole('button', {name: 'Save'})); diff --git a/packages/web/src/pages/chat-page.tsx b/packages/web/src/pages/chat-page.tsx index 800b2153..01a6e6a9 100644 --- a/packages/web/src/pages/chat-page.tsx +++ b/packages/web/src/pages/chat-page.tsx @@ -4,6 +4,7 @@ import type { ChatPersona, ChatThread, ChatThreads, + ListedPersona, Persona, ThreadStanding, ThreadView, @@ -14,6 +15,7 @@ import { ChevronLeftIcon, SlidersHorizontalIcon, Trash2Icon, + UsersIcon, } from 'lucide-react'; import { memo, @@ -81,6 +83,7 @@ import {useSending} from '@/hooks/use-sending'; import {useUnread} from '@/hooks/use-unread'; import {rowDraftPreview} from '@/lib/chat-sidebar-preview'; import {formatAgo} from '@/lib/format'; +import {hasOtherPeople} from '@/lib/orgs'; import {describeApiError, describeFetchError} from '@/lib/loader-utils'; import {isDesktopApp} from '@/lib/desktop'; import {isShortcut} from '@/lib/platform'; @@ -151,9 +154,10 @@ type ShownSaid = {personaId: string; last: LastMessage}; type ShownDraft = {personaId: string; draft: string}; type Shown = {personaId: string; last: LastMessage; draft: string}; -// The personas the person sees, their own and General, in the sidebar, each with its head, its -// name and the last thing said between it and the person, marked where the person hasn't seen it, -// or what they typed and haven't sent, the open one's as it is typed, the open one lit, each head +// The personas the person sees, their own and those shared with everyone, General among them, in +// the sidebar, each with its head, its name, a shared one marked beside it once anyone else is in +// the organization or invited, and the last thing said between it and the person, marked where the +// person hasn't seen it, or what they typed and haven't sent, the open one's as it is typed, the open one lit, each head // watching the pointer while it is over that agent's row. The one last active is on top, the open // one by what the page shows of it, so what the person just said moves it up at once. It stays as // it is from one chat to the next: the one in the address is lit at once, while it loads. A row @@ -169,15 +173,19 @@ function PersonaList({ onNew, onDelete, }: { - personas: ChatPersona[]; + personas: ListedPersona[]; current: string; shown: Shown | null; recallDraft: (personaId: string) => string | null; onNew: () => void; - onDelete: (persona: ChatPersona) => void; + onDelete: (persona: ListedPersona) => void; }) { const org = useOrgSlug(); + const human = useHuman(); const navigate = useNavigate(); + // Who sees a shared one, said beside it only where that is anyone but the person. + const everyone = + human !== null && hasOtherPeople(human.org) ? `Everyone in ${human.org.name}` : null; const unread = useUnread(); const [hovered, setHovered] = useState(null); const list = useListMotion(); @@ -238,8 +246,17 @@ function PersonaList({ /> - - {persona.name} + + {persona.name} + {persona.shared && everyone !== null && ( + + {everyone} + + )} {last && ( @@ -566,8 +583,8 @@ export function ChatPage() { } }, [org, current, threadId, threadMissing]); // The agent dialog: making a new one, or changing the name and head of one; closed as null. - const [editing, setEditing] = useState<'new' | ChatPersona | null>(null); - const [deleting, setDeleting] = useState(null); + const [editing, setEditing] = useState<'new' | ListedPersona | null>(null); + const [deleting, setDeleting] = useState(null); const human = useHuman(); const chatTo = `/${org}/chat/${current}`; const openTo = threadId === undefined ? chatTo : `${chatTo}/threads/${threadId}`; @@ -755,7 +772,7 @@ export function ChatPage() { // Deletes a persona with the chats with it: the person's, and for one every member sees, // everyone's. If it was open, opens whichever is first; otherwise refreshes the list around the // chat that stays open. - const removePersona = async (persona: ChatPersona) => { + const removePersona = async (persona: ListedPersona) => { const removed = await deletePersona(org, persona.id); if (removed.isErr()) { setError(describeFetchError(removed.error)); @@ -964,11 +981,7 @@ export function ChatPage() { setDeleting(null)} @@ -983,6 +996,15 @@ export function ChatPage() { ); } +// What deleting a persona takes with it: the person's conversation, and every other member's where +// anyone else has said something to it. +function deleteLine(persona: ListedPersona): string { + if (persona.usedByOthers) { + return `This deletes ${persona.name} and every member's conversation with it, not only yours: others have talked to it. This cannot be undone.`; + } + return `This deletes ${persona.name} and your conversation with it. This cannot be undone.`; +} + // What the page gives the chat open in it. type Opened = { // The thread open beside the chat, as it shows it, fresher than the list; and its id, from the From a90c3112f3973972e9eaa00c3d0954036e0017d7 Mon Sep 17 00:00:00 2001 From: hkonsti <45428767+hkonsti@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:34:02 +0000 Subject: [PATCH 3/3] make General an ordinary shared agent, made by the organization's owner with the organization and never again A new organization starts with General, shared and made by its owner, in the transaction that makes the organization; nothing makes it again, so one whose agents were all deleted has none, and Chat and the command bar say so and offer to make one. No rule knows General by its having no maker: it is shared, taken back, changed and deleted as any shared agent is. The migration makes every shared agent nobody made its organization's owner's, and gives General to every organization with no agent at all. --- packages/api/scripts/seed.ts | 3 +- packages/api/src/harness/fake-store.ts | 1 - packages/api/src/harness/route.test.ts | 85 +++++++--- packages/api/src/harness/route.ts | 26 +-- packages/api/src/harness/store.ts | 2 - packages/contracts/src/harness.ts | 19 +-- .../migration.sql | 27 ++++ packages/db/prisma/schema.prisma | 19 ++- packages/db/src/alerts.test.ts | 14 +- .../db/src/general-maker-migration.test.ts | 150 ++++++++++++++++++ packages/db/src/harness.test.ts | 27 ++-- packages/db/src/harness.ts | 41 +---- packages/db/src/organization.ts | 22 ++- packages/db/src/persona-sharing.test.ts | 106 +++++++++---- packages/db/src/sub-agents.test.ts | 14 +- packages/docs/content/agents/chat.mdx | 25 +-- packages/docs/content/organizations.mdx | 5 +- packages/docs/content/quick-actions.mdx | 12 +- packages/web/src/client/harness-client.ts | 2 +- packages/web/src/components/command-bar.tsx | 20 ++- .../src/components/command-palette.test.tsx | 35 +++- packages/web/src/components/persona-pane.tsx | 4 +- .../src/components/unread-provider.test.tsx | 18 +++ .../src/components/widgets/agent-widget.tsx | 2 +- .../components/widgets/new-agent-widget.tsx | 47 +++++- packages/web/src/lib/command-bar.test.ts | 4 +- packages/web/src/lib/command-bar.ts | 13 +- packages/web/src/loaders.ts | 9 +- packages/web/src/pages/chat-page.test.tsx | 68 +++++++- packages/web/src/pages/chat-page.tsx | 50 +++++- 30 files changed, 664 insertions(+), 206 deletions(-) create mode 100644 packages/db/prisma/migrations/v077_make_general_the_owners/migration.sql create mode 100644 packages/db/src/general-maker-migration.test.ts diff --git a/packages/api/scripts/seed.ts b/packages/api/scripts/seed.ts index 2dfa4b68..6bd88547 100644 --- a/packages/api/scripts/seed.ts +++ b/packages/api/scripts/seed.ts @@ -100,7 +100,8 @@ if (existing) { // ---- User and organization ------------------------------------------------------------------ -// Made as a sign-up makes them, the organization with its owner's vault, then dated back. +// Made as a sign-up makes them, the organization with its owner's vault and Chat, its built-in agent +// and General, then dated back. const provisioned = must( await provisionOrganization({ owner: { diff --git a/packages/api/src/harness/fake-store.ts b/packages/api/src/harness/fake-store.ts index 8d390783..2db1e8ec 100644 --- a/packages/api/src/harness/fake-store.ts +++ b/packages/api/src/harness/fake-store.ts @@ -32,7 +32,6 @@ export function fakeStore(): FakeStore { listPersonas: mock(), listAnswers: mock(), listMemberNames: mock(), - ensureFirstPersona: mock(), getPersona: mock(), createPersona: mock(), updatePersona: mock(), diff --git a/packages/api/src/harness/route.test.ts b/packages/api/src/harness/route.test.ts index b3dc8e56..2b776019 100644 --- a/packages/api/src/harness/route.test.ts +++ b/packages/api/src/harness/route.test.ts @@ -135,9 +135,8 @@ beforeEach(async () => { store.addDraftAttachment.mockResolvedValue(Ok(true)); store.removeDraftAttachment.mockResolvedValue(Ok(true)); store.listMemberNames.mockResolvedValue(Ok([{orgId: 'org-1', userId: 'user-2', name: 'Dana'}])); - const {listPersonas, ensureFirstPersona, getPersona, createPersona, updatePersona, deletePersona, getMemberChat, ensureMemberChat, getChatDraft} = store; + const {listPersonas, getPersona, createPersona, updatePersona, deletePersona, getMemberChat, ensureMemberChat, getChatDraft} = store; deletePersona.mockResolvedValue(Ok(true)); - ensureFirstPersona.mockResolvedValue(Ok({...persona, id: 'persona-9', name: 'General', ownerUserId: null, createdById: null})); requireViewer.mockResolvedValue(Ok(viewer)); listPersonas.mockResolvedValue(Ok([{...persona, lastMessage: {kind: 'assistant', text: 'Your vault\n has one entry.', createdAt: now}, draft: null, draftAttachments: [], usedByOthers: false}])); getPersona.mockResolvedValue(Ok(persona)); @@ -224,7 +223,7 @@ describe('the chat routes', () => { const listed = (await handleListAnswersRoute(request())).unwrap(); expect(store.listAnswers).toHaveBeenCalledWith('org-1', 'user-1'); - expect(store.ensureFirstPersona).not.toHaveBeenCalled(); + expect(store.createPersona).not.toHaveBeenCalled(); expect(listed).toEqual({ answers: [ {personaId: 'persona-1', name: 'Finance', answer: {id: 'e9', text: 'Your vault has one entry.'}, unread: [{threadId: 'thread-2', answer: {id: 'e7', text: 'Paid both.'}, ended: true}]}, @@ -232,18 +231,33 @@ describe('the chat routes', () => { }); }); - test('a viewer who sees no persona gets the organization’s General one, every member’s, on their first listing', async () => { + test('an organization whose personas were all deleted lists none, and listing makes none', async () => { const {handleListPersonasRoute} = routes; store.listPersonas.mockResolvedValue(Ok([])); - store.ensureFirstPersona.mockResolvedValue(Ok({...persona, id: 'persona-9', name: 'General', ownerUserId: null, createdById: null})); const listed = (await handleListPersonasRoute(request())).unwrap(); - expect(store.ensureFirstPersona).toHaveBeenCalledWith('org-1'); - expect(listed).toEqual({ - personas: [{...listedResponse, id: 'persona-9', name: 'General', shared: true, mayChange: false, madeBy: null, staysShared: 'General is every member’s, so it can’t be made anyone’s own.'}], - harnesses: offered, - }); + expect(listed).toEqual({personas: [], harnesses: offered}); + expect(store.createPersona).not.toHaveBeenCalled(); + }); + + test('list General, which the organization started with, as its owner made it: theirs to change and to take back, and only to change for another member', async () => { + const {handleListPersonasRoute} = routes; + const general = {...persona, id: 'persona-9', name: 'General', ownerUserId: null, createdById: 'user-2', lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}; + store.listPersonas.mockResolvedValue(Ok([general])); + store.listMemberNames.mockResolvedValue(Ok([])); + requireViewer.mockResolvedValue(Ok({...viewer, userId: 'user-2', role: 'owner'})); + + expect((await handleListPersonasRoute(request())).unwrap().personas).toEqual([ + {...listedResponse, id: 'persona-9', name: 'General', shared: true, mayChange: true, madeBy: 'you', staysShared: null}, + ]); + + store.listMemberNames.mockResolvedValue(Ok([{orgId: 'org-1', userId: 'user-2', name: 'Dana'}])); + requireViewer.mockResolvedValue(Ok(viewer)); + expect((await handleListPersonasRoute(request())).unwrap().personas).toEqual([ + {...listedResponse, id: 'persona-9', name: 'General', shared: true, mayChange: false, madeBy: {name: 'Dana'}, staysShared: 'Only whoever made General can make it theirs alone.'}, + ]); + expect(store.createPersona).not.toHaveBeenCalled(); }); test('list who made each persona: the viewer, another member by what they are called, or nobody where its maker has left', async () => { @@ -270,16 +284,13 @@ describe('the chat routes', () => { ]); }); - test('a viewer who sees personas of their own but none every member’s, as where General was deleted, gets General made again, after their own', async () => { + test('a viewer who sees personas of their own but none every member’s gets their own alone', async () => { const {handleListPersonasRoute} = routes; const listed = (await handleListPersonasRoute(request())).unwrap(); - expect(store.ensureFirstPersona).toHaveBeenCalledWith('org-1'); - expect(listed.personas.map(({id, shared}) => [id, shared])).toEqual([ - ['persona-1', false], - ['persona-9', true], - ]); + expect(listed.personas.map(({id, shared}) => [id, shared])).toEqual([['persona-1', false]]); + expect(store.createPersona).not.toHaveBeenCalled(); }); test('make a persona as given, the viewer’s own, on the server’s first harness with its first model where none was chosen, with the organization’s built-in login where there is none', async () => { @@ -374,16 +385,46 @@ describe('the chat routes', () => { expect(store.updatePersona).not.toHaveBeenCalled(); }); - test('keep General every member’s, and a shared persona somebody else made from being taken by the organization’s owner, who may still change and delete it', async () => { - const {handleDeletePersonaRoute, handleUpdatePersonaRoute} = routes; + test('let the organization’s owner take back General, which they made, while nobody else has talked to it, and refuse them once someone has, as anyone', async () => { + const {handleUpdatePersonaRoute} = routes; const body = {name: 'General', look, color: 'blue' as const, shared: false}; requireViewer.mockResolvedValue(Ok({...viewer, role: 'owner'})); + store.getPersona.mockResolvedValue(Ok({...persona, name: 'General', ownerUserId: null, createdById: 'user-1'})); + + store.takeBackPersona.mockResolvedValue(Ok('taken')); + expect((await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, body))).unwrap().persona).toMatchObject({name: 'General', shared: false}); + expect(store.takeBackPersona).toHaveBeenCalledWith('org-1', 'user-1', 'persona-1'); + + store.takeBackPersona.mockResolvedValue(Ok('used')); + expect((await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, body))).unwrapErr()).toEqual(ApiErr.conflict('Others in Acme are using General, so it stays shared.')); + }); - store.getPersona.mockResolvedValue(Ok({...persona, name: 'General', ownerUserId: null, createdById: null})); - expect((await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, body))).unwrapErr()).toEqual(ApiErr.conflict('General is every member’s, so it can’t be made anyone’s own.')); + test('keep a shared persona whose maker has left, or that names none, everyone’s: the organization’s owner changes it but nobody takes it back, and the list names no maker', async () => { + const {handleListPersonasRoute, handleUpdatePersonaRoute} = routes; + requireViewer.mockResolvedValue(Ok({...viewer, role: 'owner'})); + store.listMemberNames.mockResolvedValue(Ok([])); + for (const createdById of ['user-gone', null]) { + const scout = {...persona, name: 'Scout', ownerUserId: null, createdById}; + store.getPersona.mockResolvedValue(Ok(scout)); + store.listPersonas.mockResolvedValue(Ok([{...scout, lastMessage: null, draft: null, draftAttachments: [], usedByOthers: false}])); + + expect((await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, {name: 'Scout', look, color: 'blue', shared: false}))).unwrapErr()).toEqual( + ApiErr.conflict('Only whoever made Scout can make it theirs alone.'), + ); + expect((await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, {name: 'Scout', look, color: 'teal'}))).isOk()).toBe(true); + const [listed] = (await handleListPersonasRoute(request())).unwrap().personas; + expect(listed).toMatchObject({madeBy: null, mayChange: true, staysShared: 'Only whoever made Scout can make it theirs alone.'}); + } + expect(store.takeBackPersona).not.toHaveBeenCalled(); + }); + + test('keep a shared persona somebody else made from being taken by the organization’s owner, who may still change and delete it', async () => { + const {handleDeletePersonaRoute, handleUpdatePersonaRoute} = routes; + const body = {name: 'Finance', look, color: 'blue' as const, shared: false}; + requireViewer.mockResolvedValue(Ok({...viewer, role: 'owner'})); store.getPersona.mockResolvedValue(Ok({...persona, ownerUserId: null, createdById: 'user-2'})); - expect((await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, {...body, name: 'Finance'}))).unwrapErr()).toEqual(ApiErr.conflict('Only whoever made Finance can make it theirs alone.')); + expect((await handleUpdatePersonaRoute(request({personaId: 'persona-1'}, body))).unwrapErr()).toEqual(ApiErr.conflict('Only whoever made Finance can make it theirs alone.')); expect(store.takeBackPersona).not.toHaveBeenCalled(); expect(store.updatePersona).not.toHaveBeenCalled(); @@ -775,7 +816,7 @@ describe('the chat’s threads', () => { test('switch what runs a thread of the viewer’s chat, of any persona they see, without changing the persona; refuse a harness or a model the server hasn’t got, and say where there is no such thread', async () => { const {handleSetThreadModelRoute} = routes; store.setThreadModel.mockResolvedValue(Ok(true)); - // General, which the viewer may not change, as a member. + // A shared one another member made, which the viewer may not change. store.getPersona.mockResolvedValue(Ok({...persona, ownerUserId: null, createdById: 'user-2'})); const asked = (body: unknown, threadId = 'thread-2') => handleSetThreadModelRoute(request({personaId: 'persona-1', threadId}, body)); diff --git a/packages/api/src/harness/route.ts b/packages/api/src/harness/route.ts index 6fc8368a..24b4ec47 100644 --- a/packages/api/src/harness/route.ts +++ b/packages/api/src/harness/route.ts @@ -44,7 +44,7 @@ import type {HarnessStore} from './store'; /** * The Chat page's routes, under the organization: the personas the member sees, their own and - * those shared with every member, as General is, each named and given a head, all acting through the + * those shared with every member, each named and given a head, all acting through the * organization's one built-in agent login, and the member's own chat with each, which holds * threads: each message they post in the chat opens one, whose agent works on it and answers them * there, and a reply in a thread goes on with it; the chat lists its threads, and each is read on @@ -62,7 +62,6 @@ export type ChatStore = Pick< | 'listPersonas' | 'listMemberNames' | 'listAnswers' - | 'ensureFirstPersona' | 'getPersona' | 'createPersona' | 'updatePersona' @@ -119,17 +118,14 @@ function inUse(viewer: OrgViewer, persona: PersonaRow): string { return `Others in ${viewer.name} are using ${persona.name}, so it stays shared.`; } -// Why the viewer can't make a shared persona theirs alone again: General, or another one nobody -// made, is every member's; one somebody else made is theirs to take back, not the organization's -// owner's, and nobody's where they have left; and one another member has said something to stays -// everyone's. Null where they can, and for one that isn't shared. +// Why the viewer can't make a shared persona theirs alone again: only whoever made it takes it +// back, not the organization's owner, and nobody where they have left or it names no maker; and one +// another member has said something to stays everyone's. Null where they can, and for one that +// isn't shared. function staysShared(viewer: OrgViewer, persona: PersonaRow, usedByOthers: boolean): string | null { if (persona.ownerUserId !== null) { return null; } - if (persona.createdById === null) { - return `${persona.name} is every member’s, so it can’t be made anyone’s own.`; - } if (persona.createdById !== viewer.userId) { return `Only whoever made ${persona.name} can make it theirs alone.`; } @@ -163,7 +159,7 @@ function toPersona(harnesses: Harnesses, viewer: OrgViewer, persona: PersonaRow } // Who made the persona, as its settings say: the viewer, or another member by what they are called -// (`names`, by their id); nobody for one nobody made, as General, or whose maker has left. +// (`names`, by their id); nobody for one whose maker has left, or that names none. function madeBy(viewer: OrgViewer, persona: PersonaRow, names: ReadonlyMap): ListedPersona['madeBy'] { if (persona.createdById === null) { return null; @@ -288,7 +284,7 @@ function ensureChat(store: ChatStore, viewer: OrgViewer, persona: PersonaRow): P }); } -/** `GET /api/orgs/:org/chat/personas`: the organization's personas the viewer sees, their own and those every member does, the one last active in the viewer's chat with it first, and the harnesses the server has for one to run on; a General one, every member's, is made where there is none, after the viewer's own, so a message that names no agent always has one to go to. */ +/** `GET /api/orgs/:org/chat/personas`: the organization's personas the viewer sees, their own and those every member does, the one last active in the viewer's chat with it first, and the harnesses the server has for one to run on. It makes none: an organization whose personas were all deleted lists none. */ function handleListPersonasRoute(store: ChatStore, harnesses: Harnesses, request: AuthenticatedRequest): Promise, ApiError>> { return Do(async ($) => { const viewer = $(await requireViewer(request)); @@ -298,13 +294,7 @@ function handleListPersonasRoute(store: ChatStore, harnesses: Harnesses, request const makers = new Set(personas.flatMap(({createdById}) => (createdById === null || createdById === viewer.userId ? [] : [createdById]))); const named = $(await store.listMemberNames([...makers].map((userId) => ({orgId: viewer.orgId, userId})))); const names = new Map(named.map(({userId, name}) => [userId, name])); - const listed = personas.map((persona) => toListedPersona(harnesses, viewer, persona, names)); - if (personas.some((persona) => persona.ownerUserId === null)) { - return {personas: listed, harnesses: offered}; - } - // Just made, with nothing said to it yet. - const general = $(await store.ensureFirstPersona(viewer.orgId)); - return {personas: [...listed, toListedPersona(harnesses, viewer, {...general, usedByOthers: false}, names)], harnesses: offered}; + return {personas: personas.map((persona) => toListedPersona(harnesses, viewer, persona, names)), harnesses: offered}; }); } diff --git a/packages/api/src/harness/store.ts b/packages/api/src/harness/store.ts index b6ef9761..c0f269ee 100644 --- a/packages/api/src/harness/store.ts +++ b/packages/api/src/harness/store.ts @@ -88,7 +88,6 @@ export type HarnessStore = { listAnswers: (orgId: string, userId: string) => Promise>; /** What the members who made shared personas are called, those still in the organization, as the list says who made one. */ listMemberNames: typeof listMemberNames; - ensureFirstPersona: (orgId: string) => Promise>; getPersona: (orgId: string, userId: string, personaId: string) => Promise>; createPersona: (orgId: string, userId: string, persona: Persona, shared: boolean) => Promise>; updatePersona: (orgId: string, personaId: string, persona: Persona) => Promise>; @@ -198,7 +197,6 @@ export const harnessStore: HarnessStore = { listPersonas: harness.listPersonas, listAnswers: harness.listAnswers, listMemberNames, - ensureFirstPersona: harness.ensureFirstPersona, getPersona: harness.getPersona, createPersona: harness.createPersona, updatePersona: harness.updatePersona, diff --git a/packages/contracts/src/harness.ts b/packages/contracts/src/harness.ts index ecd0d6f4..c50c54d4 100644 --- a/packages/contracts/src/harness.ts +++ b/packages/contracts/src/harness.ts @@ -4,9 +4,9 @@ import {z} from 'zod'; /** * The Chat page (`/api/orgs/:org/chat/…`): the personas the person sees in the organization, - * their own and those shared with every member, General among them, each named and given a head, - * and the person's own chat with each: its threads, each opened by what they said in the chat, and what is said in - * each. + * their own and those shared with every member, General among them where the organization keeps + * the one it started with, each named and given a head, and the person's own chat with each: its + * threads, each opened by what they said in the chat, and what is said in each. */ /** @@ -42,7 +42,7 @@ export const chatPersonaSchema = z.object({ /** The harness that runs it and the model it answers with, by their ids, as this server has them. */ harness: z.string(), chatModel: z.string(), - /** Every member's, as General is, rather than the person's own, which nobody else sees. */ + /** Every member's rather than the person's own, which nobody else sees. */ shared: z.boolean(), /** * Whether the person may rename, reface, switch the harness or the model of, share, or delete @@ -71,8 +71,8 @@ export type ChatPersona = z.infer; */ export const listedPersonaSchema = chatPersonaSchema.extend({ /** - * Who made it: the person, or another member, by their name; null for one nobody made, as - * General, or whose maker is no longer in the organization. + * Who made it: the person, or another member, by their name; null for one whose maker is no + * longer in the organization. */ madeBy: z.union([z.literal('you'), z.object({name: z.string()})]).nullable(), /** @@ -81,8 +81,8 @@ export const listedPersonaSchema = chatPersonaSchema.extend({ */ usedByOthers: z.boolean(), /** - * Why the person can't make it theirs alone, where it is shared, as the page says it: General, - * which nobody made; one somebody else made; or one others have said something to. Null where + * Why the person can't make it theirs alone, where it is shared, as the page says it: one + * somebody else made, or whose maker has left; or one others have said something to. Null where * they can, and for their own. */ staysShared: z.string().nullable(), @@ -137,7 +137,8 @@ export type ChatAnswer = z.infer; /** * `GET chat/answers`: the last answer in each of the person's chats that has one, as every page - * asks every so often; it makes nothing, where `GET chat/personas` makes General. + * asks every so often. Neither it nor `GET chat/personas` makes anything: an organization whose + * personas were all deleted has none, and no answers. */ export const chatAnswersSchema = z.object({answers: z.array(chatAnswerSchema)}); diff --git a/packages/db/prisma/migrations/v077_make_general_the_owners/migration.sql b/packages/db/prisma/migrations/v077_make_general_the_owners/migration.sql new file mode 100644 index 00000000..523c9299 --- /dev/null +++ b/packages/db/prisma/migrations/v077_make_general_the_owners/migration.sql @@ -0,0 +1,27 @@ +-- General is now the agent of the Chat page an organization starts with, made with it, shared with +-- every member and made by its owner, and never made again; nothing knows it any more by its +-- having no maker. Data only. + +-- Every shared persona nobody made, which is General as it was made until now on a first listing +-- of Chat, is its organization's owner's making from here on: they change it, as they could, and +-- may make it theirs alone while nobody else has talked to it. One whose maker has left the +-- organization keeps them, and stays everyone's. +UPDATE "Persona" AS p SET "createdById" = o."ownerUserId" +FROM "Organization" AS o +WHERE o."id" = p."orgId" AND p."ownerUserId" IS NULL AND p."createdById" IS NULL; + +-- Every organization with no persona at all, as one whose members never opened Chat, starts as a +-- new one does: with General, shared, made by its owner, with the first look +-- (`@proxy/utils/harness` DEFAULT_LOOK), in blue, run as the database's defaults have it. One +-- with personas of its members' own and none shared is left as it is. +INSERT INTO "Persona" ("id", "orgId", "name", "look", "color", "ownerUserId", "createdById") +SELECT + gen_random_uuid()::text, + o."id", + 'General', + '{"nose":0.48,"noseOut":0.35,"eye":27,"eyeTheta":55,"eyeLat":8,"eyes":2}', + 'blue', + NULL, + o."ownerUserId" +FROM "Organization" AS o +WHERE NOT EXISTS (SELECT 1 FROM "Persona" AS p WHERE p."orgId" = o."id"); diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma index 3dd140b5..0293d35e 100644 --- a/packages/db/prisma/schema.prisma +++ b/packages/db/prisma/schema.prisma @@ -763,9 +763,10 @@ model FileChange { } // A persona of the Chat page: an agent Personal Agent Proxy runs itself, named and given a head, -// one of any number. It is whoever made it's, who alone sees it, talks to it and changes it; General, -// which every organization starts with, is nobody's, so every member sees it and has a -// chat of their own with it. Every persona acts through the organization's one built-in +// one of any number. It is whoever made it's, who alone sees it, talks to it and changes it, until +// they share it with the organization: every member then sees it and has a chat of their own with +// it, as with General, which an organization starts with, shared, made by its owner. Every persona +// acts through the organization's one built-in // agent login (Agent, provider `proxy`), whose grants are every persona's: a persona is who did // the work, the login is what it may do. model Persona { @@ -782,13 +783,15 @@ model Persona { harness String @default("claude-agent-sdk") chatModel String @default("sonnet") // The member whose persona it is, which nobody else in the organization sees, its owner - // included; null for one every member sees, as General is, as one its maker shared with the - // organization is, and as one from before personas were anyone's is where others had talked to - // it. Its maker makes a shared one theirs again only while no other member has said anything + // included; null for one every member sees, as one its maker shared with the organization is, + // General among them, and as one from before personas were anyone's is where others had talked + // to it. Its maker makes a shared one theirs again only while no other member has said anything // to it. ownerUserId String? - // Who made it: who may change one every member sees, beside the organization's owner. A plain - // id rather than a relation, so such a persona stays when they are gone. + // Who made it: who may change one every member sees, beside the organization's owner, and the + // only one who may make it theirs again (General's is the organization's owner). A plain id + // rather than a relation, so a shared one stays when they are gone, and then nobody can take it + // back. createdById String? createdAt DateTime @default(now()) diff --git a/packages/db/src/alerts.test.ts b/packages/db/src/alerts.test.ts index 898d8a32..9cdb21a9 100644 --- a/packages/db/src/alerts.test.ts +++ b/packages/db/src/alerts.test.ts @@ -2,7 +2,7 @@ import {afterAll, beforeAll, describe, expect, test} from 'bun:test'; import type {Result} from 'ts-results-es'; import type {ApiError} from '@proxy/utils'; -import {readyForInference} from '@proxy/utils/harness'; +import {DEFAULT_LOOK, readyForInference} from '@proxy/utils/harness'; import {db} from '.'; import { @@ -21,7 +21,7 @@ import { import { claimJob, completeInference, - ensureFirstPersona, + createPersona, ensureMemberChat, finishJob, type JobRow, @@ -93,7 +93,15 @@ describe.skipIf(!databaseUrl)('the alerts, against the database', () => { }); connectionId = connection.id; poll = {connectionId, collectionId: 'emails', cursor: null}; - const persona = unwrap(await ensureFirstPersona(orgId)); + // General, shared, as an organization starts with it. + const persona = unwrap( + await createPersona( + orgId, + userId, + {name: 'General', look: DEFAULT_LOOK, color: 'blue'}, + true, + ), + ); chat = unwrap( await ensureMemberChat({orgId, agentId: agent.id, personaId: persona.id, userId}), ); diff --git a/packages/db/src/general-maker-migration.test.ts b/packages/db/src/general-maker-migration.test.ts new file mode 100644 index 00000000..7544425d --- /dev/null +++ b/packages/db/src/general-maker-migration.test.ts @@ -0,0 +1,150 @@ +import {readdirSync, readFileSync} from 'node:fs'; + +import {PGlite} from '@electric-sql/pglite'; +import {afterAll, beforeAll, describe, expect, test} from 'bun:test'; + +import {DEFAULT_LOOK} from '@proxy/utils/harness'; + +// The migration that gives every shared persona nobody made its organization's owner for a maker, +// and General to every organization with no persona at all (v077), run on rows as they were: a +// database of its own, in this process, which PGlite keeps in memory, made with every migration +// before it, as reshape-chats-migration.test.ts makes one. Nothing here needs the local database. +const MIGRATION = 'v077_make_general_the_owners'; + +const migrations = new URL('../prisma/migrations/', import.meta.url); + +function migrationSql(name: string): string { + return readFileSync(new URL(`${name}/migration.sql`, migrations), 'utf8'); +} + +// Prisma applies the migrations in the order their names sort as text (migrations.test.ts). +const before = readdirSync(migrations, {withFileTypes: true}) + .filter((entry) => entry.isDirectory() && entry.name < MIGRATION) + .map((entry) => entry.name) + .sort(); + +type Value = string | null; + +const pg = new PGlite(); + +async function insert(table: string, row: Record): Promise { + const columns = Object.keys(row); + await pg.query( + `INSERT INTO "${table}" (${columns.map((column) => `"${column}"`).join(', ')}) VALUES (${columns.map((_, index) => `$${index + 1}`).join(', ')})`, + Object.values(row), + ); +} + +type PersonaRow = { + id: string; + name: string; + look: string; + color: string; + ownerUserId: string | null; + createdById: string | null; + harness: string; + chatModel: string; +}; + +// An organization's personas by id: those made within a millisecond of each other have no order +// by when they were made. +async function personasOf(orgId: string): Promise { + return ( + await pg.query( + `SELECT "id", "name", "look", "color", "ownerUserId", "createdById", "harness", "chatModel" FROM "Persona" WHERE "orgId" = $1 ORDER BY "id"`, + [orgId], + ) + ).rows; +} + +async function org(id: string, ownerUserId: string): Promise { + await insert('Organization', {id, name: id, slug: id, ownerUserId}); + await insert('OrgMember', {id: `${id}-${ownerUserId}`, orgId: id, userId: ownerUserId}); +} + +async function persona( + id: string, + orgId: string, + fields: {ownerUserId: string | null; createdById: string | null}, +): Promise { + await insert('Persona', {id, orgId, name: id, look: '{}', color: 'green', ...fields}); +} + +// Four organizations, as the migration finds them: Harbor, whose General was made on a first +// listing of Chat by nobody, beside a shared one Omar made and one of his own; Orchard, whose +// shared Scout was made by a member who has since left; Meadow, whose members never opened Chat; +// and Quarry, with only a persona of Ivo's own. +async function seed(): Promise { + for (const id of ['lena', 'omar', 'ruth', 'gone', 'ivo', 'pia']) { + await insert('User', {id, email: `${id}@example.com`}); + } + await org('harbor', 'lena'); + await insert('OrgMember', {id: 'harbor-omar', orgId: 'harbor', userId: 'omar'}); + await persona('harbor-general', 'harbor', {ownerUserId: null, createdById: null}); + await persona('harbor-research', 'harbor', {ownerUserId: null, createdById: 'omar'}); + await persona('harbor-omar', 'harbor', {ownerUserId: 'omar', createdById: 'omar'}); + + await org('orchard', 'ruth'); + await persona('orchard-scout', 'orchard', {ownerUserId: null, createdById: 'gone'}); + + await org('meadow', 'pia'); + + await org('quarry', 'ivo'); + await persona('quarry-ivo', 'quarry', {ownerUserId: 'ivo', createdById: 'ivo'}); +} + +beforeAll(async () => { + for (const name of before) { + await pg.exec(migrationSql(name)); + } + await seed(); + await pg.exec(migrationSql(MIGRATION)); +}); + +afterAll(async () => { + await pg.close(); +}); + +describe(MIGRATION, () => { + test('a shared persona nobody made is its organization’s owner’s making, and every other keeps its maker', async () => { + expect( + (await personasOf('harbor')).map(({id, ownerUserId, createdById}) => ({ + id, + ownerUserId, + createdById, + })), + ).toEqual([ + {id: 'harbor-general', ownerUserId: null, createdById: 'lena'}, + {id: 'harbor-omar', ownerUserId: 'omar', createdById: 'omar'}, + {id: 'harbor-research', ownerUserId: null, createdById: 'omar'}, + ]); + }); + + test('a shared persona whose maker left keeps them, and stays everyone’s', async () => { + expect( + (await personasOf('orchard')).map(({id, ownerUserId, createdById}) => ({ + id, + ownerUserId, + createdById, + })), + ).toEqual([{id: 'orchard-scout', ownerUserId: null, createdById: 'gone'}]); + }); + + test('an organization with no persona gets General, shared, made by its owner, with the first look in blue', async () => { + const [general, ...more] = await personasOf('meadow'); + expect(more).toEqual([]); + expect(general).toMatchObject({ + name: 'General', + color: 'blue', + ownerUserId: null, + createdById: 'pia', + harness: 'claude-agent-sdk', + chatModel: 'sonnet', + }); + expect(general?.look).toBe(JSON.stringify(DEFAULT_LOOK)); + }); + + test('an organization with personas but none shared is left as it is', async () => { + expect((await personasOf('quarry')).map(({id}) => id)).toEqual(['quarry-ivo']); + }); +}); diff --git a/packages/db/src/harness.test.ts b/packages/db/src/harness.test.ts index 586daaaa..88548e6c 100644 --- a/packages/db/src/harness.test.ts +++ b/packages/db/src/harness.test.ts @@ -2,7 +2,7 @@ import {afterAll, beforeAll, describe, expect, test} from 'bun:test'; import type {Result} from 'ts-results-es'; import type {ApiError} from '@proxy/utils'; -import {readyForInference} from '@proxy/utils/harness'; +import {DEFAULT_LOOK, readyForInference} from '@proxy/utils/harness'; import {db} from '.'; import { @@ -14,7 +14,6 @@ import { completeInference, completeToolJob, createPersona, - ensureFirstPersona, ensureMemberChat, failJob, finishJob, @@ -36,6 +35,7 @@ import { requeueJob, saveChatDraft, saveThreadDraft, + type PersonaRow, type ThreadRow, } from './harness'; import {removeMembership} from './organization'; @@ -65,7 +65,9 @@ describe.skipIf(!databaseUrl)('the harness, against the database', () => { let userId = ''; let orgId = ''; let agentId = ''; - // The member's chat with General, and the thread the tests below go on in. + // General, shared, as the organization starts with it; the member's chat with it, and the + // thread the tests below go on in. + let general: PersonaRow; let chat: ThreadRow; let thread: ThreadRow; @@ -125,8 +127,15 @@ describe.skipIf(!databaseUrl)('the harness, against the database', () => { }, }); agentId = agent.id; - const persona = unwrap(await ensureFirstPersona(orgId)); - chat = unwrap(await ensureMemberChat({orgId, agentId, personaId: persona.id, userId})); + general = unwrap( + await createPersona( + orgId, + userId, + {name: 'General', look: DEFAULT_LOOK, color: 'blue'}, + true, + ), + ); + chat = unwrap(await ensureMemberChat({orgId, agentId, personaId: general.id, userId})); thread = (await open(chat, 'Find my invoices')).thread; }); @@ -281,7 +290,7 @@ describe.skipIf(!databaseUrl)('the harness, against the database', () => { }); test('each thread’s last answer is unread until the thread is read up to it, never back, each thread on its own; a reply reads the thread up to it', async () => { - const persona = unwrap(await ensureFirstPersona(orgId)); + const persona = general; const lastAnswer = async () => unwrap(await listAnswers(orgId, userId)).find( (candidate) => candidate.personaId === persona.id, @@ -366,7 +375,6 @@ describe.skipIf(!databaseUrl)('the harness, against the database', () => { }); test('the personas are listed the one last active first: the last thing said in it, or its making before anything was', async () => { - const general = unwrap(await ensureFirstPersona(orgId)); const look = {nose: 0.5, noseOut: 0.3, eye: 25, eyeTheta: 50, eyeLat: 8, eyes: 2 as const}; const travel = unwrap( await createPersona(orgId, userId, {name: 'Travel', look, color: 'teal'}), @@ -393,8 +401,7 @@ describe.skipIf(!databaseUrl)('the harness, against the database', () => { unwrap(await finishJob(job.id, 'worker-p')); }); - test('a persona is its maker’s, which no other member lists or finds, where General is every member’s, and it goes when its maker leaves', async () => { - const general = unwrap(await ensureFirstPersona(orgId)); + test('a persona is its maker’s, which no other member lists or finds, where a shared one is every member’s, and it goes when its maker leaves', async () => { const look = {nose: 0.5, noseOut: 0.3, eye: 25, eyeTheta: 50, eyeLat: 8, eyes: 2 as const}; const other = await db.user.create({data: {email: `harness-test-other-${stamp}@example.test`}}); await db.orgMember.create({data: {orgId, userId: other.id}}); @@ -413,8 +420,6 @@ describe.skipIf(!databaseUrl)('the harness, against the database', () => { expect(unwrap(await getPersona(orgId, userId, own.id))?.id).toBe(own.id); expect(unwrap(await getPersona(orgId, other.id, own.id))).toBeNull(); expect(unwrap(await getPersona(orgId, other.id, general.id))?.id).toBe(general.id); - // General is the one every member sees, however many of their own there are. - expect(unwrap(await ensureFirstPersona(orgId)).id).toBe(general.id); unwrap(await removeMembership({orgId, userId: other.id, sharedAgentPasswordHash: ''})); expect(await db.persona.findUnique({where: {id: theirs.id}})).toBeNull(); diff --git a/packages/db/src/harness.ts b/packages/db/src/harness.ts index 34c225f0..074176be 100644 --- a/packages/db/src/harness.ts +++ b/packages/db/src/harness.ts @@ -9,7 +9,6 @@ import {Err, Ok, type Result} from 'ts-results-es'; import {ApiErr, type ApiError, wrapDb} from '@proxy/utils'; import { - DEFAULT_LOOK, type HarnessSession, type Look, type LogEntry, @@ -29,8 +28,7 @@ import type {NewAgentTask} from './task'; /** * The Chat page: the organization's personas, each its maker's alone or shared with every member, - * as General is, with a chat per member who sees it, and the chat's threads, each with its log and its - * jobs. A chat runs no agent of its own: it keeps what the member typed and hasn't sent, the files + * with a chat per member who sees it, and the chat's threads, each with its log and its jobs. A chat runs no agent of its own: it keeps what the member typed and hasn't sent, the files * in its input and how far they have read, and every message they post in it opens a thread, whose * agent answers them there. The member's reply, or an alert set in the thread, takes the thread up * again; its answer with no calls ends its turn, and where it then stands, whether it waits for the @@ -96,8 +94,8 @@ export type Persona = {name: string; look: Look; color: string} & Partial & PersonaModel & { @@ -571,39 +569,6 @@ export async function listAnswers( }); } -/** - * The organization's first persona, General, every member's, made by nobody in particular where - * it has none every member sees: the organization's row is locked meanwhile, so two first - * openings of Chat make one. The one there is otherwise, which is the oldest of them. - */ -export async function ensureFirstPersona(orgId: string): Promise> { - return ( - await wrapDb(() => - db.$transaction(async (tx) => { - await tx.$queryRaw`SELECT "id" FROM "Organization" WHERE "id" = ${orgId} FOR UPDATE`; - const existing = await tx.persona.findFirst({ - where: {orgId, ownerUserId: null}, - select: personaSelect, - orderBy: {createdAt: 'asc'}, - }); - if (existing) { - return existing; - } - return tx.persona.create({ - data: { - orgId, - createdById: null, - name: 'General', - look: JSON.stringify(DEFAULT_LOOK), - color: 'blue', - }, - select: personaSelect, - }); - }), - ) - ).map(toPersona); -} - /** Personas by id, those of the organization among `ids`, for what names them. */ export async function listPersonasById( orgId: string, diff --git a/packages/db/src/organization.ts b/packages/db/src/organization.ts index 3b48fb56..08a08803 100644 --- a/packages/db/src/organization.ts +++ b/packages/db/src/organization.ts @@ -3,6 +3,7 @@ import {Prisma} from '@prisma/client'; import {Err, Ok, type Result} from 'ts-results-es'; import {BUILT_IN_AGENT_PROVIDER} from '@proxy/utils/agent-providers'; +import {DEFAULT_LOOK} from '@proxy/utils/harness'; import { ApiErr, @@ -294,10 +295,12 @@ export async function createStarterConnections( } /** - * A new organization with its owner's membership, its built-in agent and its starter connections, in one - * transaction: the owner a person there is, or one made with it, so no user exists without an - * organization. Its slug is `slugSource`'s (buildBaseSlug), numbered where taken; picking is tried - * again when a parallel creation took the same one. + * A new organization with its owner's membership, its built-in agent, its starter connections and + * its first agent of the Chat page, General, in one transaction: the owner a person there is, or + * one made with it, so no user exists without an organization. General is shared with every + * member and made by the owner, with the first look in blue; from then on it is an agent like any + * other, and nothing makes it again. Its slug is `slugSource`'s (buildBaseSlug), numbered where + * taken; picking is tried again when a parallel creation took the same one. */ export async function provisionOrganization(data: { owner: {userId: string} | {user: NewUser}; @@ -335,6 +338,17 @@ export async function provisionOrganization(data: { select: {id: true}, }); await createStarterConnections(tx, connections, {orgId: org.id, userId, name}); + await tx.persona.create({ + data: { + orgId: org.id, + ownerUserId: null, + createdById: userId, + name: 'General', + look: JSON.stringify(DEFAULT_LOOK), + color: 'blue', + }, + select: {id: true}, + }); return {org, ownerUserId: userId}; }), ); diff --git a/packages/db/src/persona-sharing.test.ts b/packages/db/src/persona-sharing.test.ts index 0674e592..b04bd424 100644 --- a/packages/db/src/persona-sharing.test.ts +++ b/packages/db/src/persona-sharing.test.ts @@ -2,12 +2,12 @@ import {afterAll, beforeAll, describe, expect, test} from 'bun:test'; import type {Result} from 'ts-results-es'; import type {ApiError} from '@proxy/utils'; -import {readyForInference} from '@proxy/utils/harness'; +import {DEFAULT_LOOK, readyForInference} from '@proxy/utils/harness'; import {db} from '.'; import { createPersona, - ensureFirstPersona, + deletePersona, ensureMemberChat, getMemberChat, getPersona, @@ -18,6 +18,7 @@ import { takeBackPersona, type ThreadRow, } from './harness'; +import {provisionOrganization, removeMembership} from './organization'; // Sharing a persona with the organization and taking it back, against a database, as // harness.test.ts runs: with `bun run test:db` from the repository's root; skipped without @@ -37,7 +38,10 @@ describe.skipIf(!databaseUrl)('sharing a persona, against the database', () => { const stamp = `${Date.now()}-${process.pid}`; let maker = ''; let other = ''; + let leaver = ''; let orgId = ''; + // Organizations made in the tests besides the one they share. + const alsoMade: string[] = []; let agentId = ''; // The member's chat with the persona, made where they have none. @@ -65,37 +69,41 @@ describe.skipIf(!databaseUrl)('sharing a persona, against the database', () => { return unwrap(await listPersonas(orgId, userId)).find(({id}) => id === personaId)?.usedByOthers; } + // An organization `owner` owns, made as a new one is, with its built-in agent and General. + async function provision(owner: string, name: string): Promise { + const made = unwrap( + await provisionOrganization({ + owner: {userId: owner}, + name, + slugSource: `${name}-${stamp}`, + onboardedAt: new Date(), + builtInAgent: {name: 'Chat', username: `${name}-${stamp}`, passwordHash: ''}, + connections: [], + }), + ); + return made.org.id; + } + beforeAll(async () => { maker = (await db.user.create({data: {email: `sharing-test-${stamp}@example.test`}})).id; other = (await db.user.create({data: {email: `sharing-test-other-${stamp}@example.test`}})).id; - const org = await db.organization.create({ - data: {name: 'Sharing test', slug: `sharing-test-${stamp}`, ownerUserId: maker}, - }); - orgId = org.id; + leaver = (await db.user.create({data: {email: `sharing-test-leaver-${stamp}@example.test`}})) + .id; + orgId = await provision(maker, 'sharing-test'); await db.orgMember.createMany({ data: [ - {orgId, userId: maker}, {orgId, userId: other}, + {orgId, userId: leaver}, ], }); - const agent = await db.agent.create({ - data: { - orgId, - providerId: 'proxy', - name: 'Built in', - username: `sharing-test-${stamp}`, - passwordHash: '', - }, - }); - agentId = agent.id; - unwrap(await ensureFirstPersona(orgId)); + agentId = (await db.agent.findFirstOrThrow({where: {orgId, providerId: 'proxy'}})).id; }); afterAll(async () => { - if (orgId !== '') { - await db.organization.delete({where: {id: orgId}}); - } - await db.user.deleteMany({where: {id: {in: [maker, other].filter((id) => id !== '')}}}); + await db.organization.deleteMany({where: {id: {in: [orgId, ...alsoMade]}}}); + await db.user.deleteMany({ + where: {id: {in: [maker, other, leaver].filter((id) => id !== '')}}, + }); await db.$disconnect(); }); @@ -148,7 +156,7 @@ describe.skipIf(!databaseUrl)('sharing a persona, against the database', () => { expect(unwrap(await takeBackPersona(orgId, maker, travel.id))).toBe('missing'); }); - test('a shared persona another member has said something to stays shared, as General always does', async () => { + test('a shared persona another member has said something to stays shared', async () => { const billing = unwrap( await createPersona(orgId, maker, {name: 'Billing', look, color: 'pink'}, true), ); @@ -157,10 +165,54 @@ describe.skipIf(!databaseUrl)('sharing a persona, against the database', () => { expect(await usedByOthers(maker, billing.id)).toBe(true); expect(unwrap(await takeBackPersona(orgId, maker, billing.id))).toBe('used'); expect(unwrap(await getPersona(orgId, other, billing.id))?.ownerUserId).toBeNull(); + }); + + test('General, which the organization started with, is its owner’s making: they take it back while nobody else has talked to it, and not once someone has', async () => { + const [general] = unwrap(await listPersonas(orgId, other)).filter( + ({name}) => name === 'General', + ); + expect(general).toMatchObject({ + ownerUserId: null, + createdById: maker, + look: DEFAULT_LOOK, + color: 'blue', + }); + const id = general?.id ?? ''; + await chatOf(id, other); + + expect(unwrap(await takeBackPersona(orgId, other, id))).toBe('missing'); + expect(unwrap(await takeBackPersona(orgId, maker, id))).toBe('taken'); + expect(unwrap(await getPersona(orgId, other, id))).toBeNull(); + + expect(unwrap(await sharePersona(orgId, maker, id))).toBe(true); + await say(await chatOf(id, other), 'What is on this week?'); + expect(unwrap(await takeBackPersona(orgId, maker, id))).toBe('used'); + expect(unwrap(await getPersona(orgId, other, id))?.ownerUserId).toBeNull(); + }); + + test('a shared persona whose maker left the organization stays everyone’s, and nobody can take it back', async () => { + const scout = unwrap( + await createPersona(orgId, leaver, {name: 'Scout', look, color: 'green'}, true), + ); + unwrap(await removeMembership({orgId, userId: leaver, sharedAgentPasswordHash: '-'})); + + expect(unwrap(await getPersona(orgId, other, scout.id))).toMatchObject({ + ownerUserId: null, + createdById: leaver, + }); + expect(unwrap(await takeBackPersona(orgId, maker, scout.id))).toBe('missing'); + expect(unwrap(await takeBackPersona(orgId, other, scout.id))).toBe('missing'); + }); + + test('an organization whose agents were all deleted has none, and listing them makes none', async () => { + const emptied = await provision(other, 'emptied-test'); + alsoMade.push(emptied); + const [general, ...more] = unwrap(await listPersonas(emptied, other)); + expect(more).toEqual([]); + expect(general).toMatchObject({name: 'General', ownerUserId: null, createdById: other}); - const general = unwrap(await ensureFirstPersona(orgId)); - expect(general.createdById).toBeNull(); - expect(unwrap(await takeBackPersona(orgId, maker, general.id))).toBe('missing'); - expect(unwrap(await getPersona(orgId, other, general.id))?.ownerUserId).toBeNull(); + expect(unwrap(await deletePersona(emptied, general?.id ?? ''))).toBe(true); + expect(unwrap(await listPersonas(emptied, other))).toEqual([]); + expect(unwrap(await listPersonas(emptied, other))).toEqual([]); }); }); diff --git a/packages/db/src/sub-agents.test.ts b/packages/db/src/sub-agents.test.ts index 6e621263..da293a7c 100644 --- a/packages/db/src/sub-agents.test.ts +++ b/packages/db/src/sub-agents.test.ts @@ -2,7 +2,7 @@ import {afterAll, beforeAll, describe, expect, test} from 'bun:test'; import type {Result} from 'ts-results-es'; import type {ApiError} from '@proxy/utils'; -import {readyForInference} from '@proxy/utils/harness'; +import {DEFAULT_LOOK, readyForInference} from '@proxy/utils/harness'; import {db} from '.'; import { @@ -10,7 +10,7 @@ import { claimJob, type ClaimedJob, completeInference, - ensureFirstPersona, + createPersona, ensureMemberChat, failJob, getChatThread, @@ -106,7 +106,15 @@ describe.skipIf(!databaseUrl)('sub-agents, against the database', () => { }, }); agentId = agent.id; - const persona = unwrap(await ensureFirstPersona(orgId)); + // General, shared, as an organization starts with it. + const persona = unwrap( + await createPersona( + orgId, + userId, + {name: 'General', look: DEFAULT_LOOK, color: 'blue'}, + true, + ), + ); chat = unwrap(await ensureMemberChat({orgId, agentId, personaId: persona.id, userId})); const task = { orgId, diff --git a/packages/docs/content/agents/chat.mdx b/packages/docs/content/agents/chat.mdx index 12bdc1f6..3edfd00a 100644 --- a/packages/docs/content/agents/chat.mdx +++ b/packages/docs/content/agents/chat.mdx @@ -4,11 +4,13 @@ description: Talk to an agent Personal Agent Proxy runs itself, with the same ac --- **Chat** in the sidebar is where you talk to agents Personal Agent Proxy runs itself. Every -organization starts with one, **General**, which every member sees. An agent you make is yours -alone: make one with **New agent**, giving it a name and a head, or ask for one from -[the command bar](/quick-actions#handing-it-to-an-agent), and nobody else in the organization sees -it, its owner included; you rename it, change its head or delete it. General is renamed or deleted -by the organization's owner, and stays everyone's. All of them act through one entry on the +organization starts with one, **General**, shared with every member and made by the organization's +owner; otherwise it is an agent like any other, which can be renamed, changed, made the owner's +alone or deleted. An agent you make is yours alone: make one with **New agent**, giving it a name +and a head, or ask for one from [the command bar](/quick-actions#handing-it-to-an-agent), and +nobody else in the organization sees it, its owner included; you rename it, change its head or +delete it. An organization whose agents were all deleted has none until someone makes one: Chat +says so, with **New agent**. All of them act through one entry on the **External agents** page, Chat, shared with everyone, as Claude or ChatGPT are one entry each however many assistants run inside them: what the agents may do with each connection is set in its column, once for all of them, @@ -21,14 +23,15 @@ it, and deleting it at the foot. **Edit** there changes its name and head; who s as you choose it. Click the name again, press Back or the cross to close them. You can share an agent of yours with the organization: in its settings, under **Who sees it**, -choose **Everyone in** it. Every member then sees it, each with a chat of their own with it, as -with General, and it answers each of them as them. Its name, head, model and harness are the same +choose **Everyone in** it. Every member then sees it, each with a chat of their own with it, and +it answers each of them as them. Its name, head, model and harness are the same for everyone. Your own chat with it, and its tasks, stay as they were. Once anyone else is in the organization, a shared agent has a mark beside its name in the list. You can make it yours alone again with **Only you** while nobody else has said anything to it; once someone has, it stays shared, and its settings say so. A shared agent is renamed, changed or deleted by whoever made it -and by the organization's owner, who can't make it theirs alone. Deleting a shared agent deletes -every member's chat with it. +and by the organization's owner, who can't make it theirs alone unless they made it, as they made +General. One whose maker has left the organization is for everyone in it, and nobody can make it +theirs alone. Deleting a shared agent deletes every member's chat with it. Your chat with an agent is yours alone, as a direct message is, a shared agent's too: nobody else in the organization sees it. In it, the agent acts as you, so it reaches what you use: the connections @@ -46,8 +49,8 @@ member's own [Claude account](#your-claude-subscription). Under the message box, a chat says what runs its agent: the **model**, and beside it the **harness**, the loop that runs its turns. For whoever may change the agent, you for one of your -own, whoever made a shared one, and the organization's owner for any shared one, General among -them, it opens the harnesses down the side, each by its +own, whoever made a shared one, and the organization's owner for any shared one, it opens the +harnesses down the side, each by its mark, with the models of the one you look at beside them to switch between. The choice is the agent's: every thread opened from then on, in any member's chat with the agent, starts with it. Threads already open keep what they run on. diff --git a/packages/docs/content/organizations.mdx b/packages/docs/content/organizations.mdx index 23406fee..5b13802f 100644 --- a/packages/docs/content/organizations.mdx +++ b/packages/docs/content/organizations.mdx @@ -59,8 +59,9 @@ settings on a connection are changed by whoever changes the connection's default An agent you make on the Chat page is yours alone until you share it: in its settings (click its name over its list of tasks), **Everyone in** the organization under **Who sees it** shows it to every member, each with a chat of their own with it that nobody else reads, and in each it acts as -whoever is talking to it, with what they use, as General does. You can make it yours alone again -with **Only you** as long as nobody else has said anything to it; after that it stays shared. +whoever is talking to it, with what they use. An organization starts with one shared agent, +**General**, made by its owner. You can make it yours alone again with **Only you** as long as +nobody else has said anything to it; after that it stays shared. Whoever made it and the organization's owner rename it, change it and delete it, with every member's chat with it. diff --git a/packages/docs/content/quick-actions.mdx b/packages/docs/content/quick-actions.mdx index 665f967d..36ad3a24 100644 --- a/packages/docs/content/quick-actions.mdx +++ b/packages/docs/content/quick-actions.mdx @@ -45,11 +45,13 @@ login's access. In an organization with [Chat](/agents/chat), the bar also works with the agents Personal Agent Proxy runs itself: -- **What no quick action does** becomes a message to one of them: the bar says **Send this to - General**, or to another agent where what you typed names one, and the agent's name there opens - the others to pick from. **Enter**, or **Send**, sends it as you typed it, opening a thread, and - opens the chat, where the agent answers in the thread. Enter pressed before the bar says so sends it as soon as - the bar knows no quick action does it. +- **What no quick action does** becomes a message to one of them: the bar says **Send this to** + the agent what you typed names, else the oldest agent shared with everyone, such as **General**, + else the first in Chat's list, and the agent's name there opens the others to pick from. + **Enter**, or **Send**, sends it as you typed it, opening a thread, and opens the chat, where + the agent answers in the thread. Enter pressed before the bar says so sends it as soon as the bar knows + no quick action does it. With no agent in Chat at all, the bar says so and shows a new one to + make, told what you typed first: name it, and **Enter**, or **Create agent**, makes it. - **Say it to an agent by name** to skip the quick actions altogether: `ask Finance …`, `tell Finance …`, `@Finance …` or `Finance, …`, the name also as `my Finance agent` or `the Finance assistant`, is a message to Finance whatever else it reads like, such as a question a diff --git a/packages/web/src/client/harness-client.ts b/packages/web/src/client/harness-client.ts index abd9caf5..70742e4c 100644 --- a/packages/web/src/client/harness-client.ts +++ b/packages/web/src/client/harness-client.ts @@ -23,7 +23,7 @@ import {apiRequest, apiSend, apiUpload, orgApi} from '@/client/request'; import {rememberPersonaList} from '@/lib/persona-list'; // The Chat page's api: the personas the person sees, their own and those shared with every -// member, General among them, each named and given a head, and the person's own chat with each: +// member, each named and given a head, and the person's own chat with each: // its threads, each opened by what they said in the chat and read on its own, what they reply in // one, what they typed in the chat and haven't sent, and how far they have read it. diff --git a/packages/web/src/components/command-bar.tsx b/packages/web/src/components/command-bar.tsx index 0953093e..c92be499 100644 --- a/packages/web/src/components/command-bar.tsx +++ b/packages/web/src/components/command-bar.tsx @@ -9,6 +9,7 @@ import {fillIntent, type Intent, pickIntent} from '@/client/intent-client'; import {AnimatedHeight} from '@/components/animated-height'; import {CommandRows} from '@/components/command-rows'; import {AgentWidget} from '@/components/widgets/agent-widget'; +import {NoAgentWidget} from '@/components/widgets/new-agent-widget'; import {FillingWidget, IntentWidget} from '@/components/widgets/intent-widget'; import {UnsupportedWidget} from '@/components/widgets/unsupported-widget'; import {Input} from '@proxy/ui/components/input'; @@ -105,8 +106,10 @@ type Props = { * external agents the words lead to, which Enter opens; the api picks the widget for what is * typed every 300 ms while typing goes on, which shows at once and fills in when its fields come. * In an organization with Chat, a wish for a new agent opens into one to make, and what no quick - * action does into a message to one of Chat's agents, General unless the text names another; - * Enter makes the one and sends the other, and leads to the conversation. A text said to an agent + * action does into a message to one of Chat's agents, the one the text names, else the oldest + * shared one, else the first listed (lib/command-bar.ts personaFor), or, with no agent at all, into + * one to make that starts on it; Enter makes the one and sends the other, and leads to the + * conversation. A text said to an agent * by name ("ask Finance …") is a message to it, of what follows the name, without being classified * at all. */ @@ -448,7 +451,18 @@ export function CommandBar({connections, agents, personas, open: up, onClose}: P if (rows.length > 0) { return null; } - if (personas !== null && personas.length > 0) { + if (personas !== null && personas.length === 0) { + return { + key: 'no-agent', + view: ( + + ), + }; + } + if (personas !== null) { return { key: 'agent', view: ( diff --git a/packages/web/src/components/command-palette.test.tsx b/packages/web/src/components/command-palette.test.tsx index 64a8e83e..e2893f82 100644 --- a/packages/web/src/components/command-palette.test.tsx +++ b/packages/web/src/components/command-palette.test.tsx @@ -66,6 +66,8 @@ const claude: AgentLogin = { }; const personas = [persona('finance', 'Finance', false), persona('general', 'General', true)]; +// Chat's agents as the api lists them: those above, unless a test says otherwise. +let listedPersonas: ListedPersona[] = personas; // What the bar sends the api, as far as the tests look at it: what is typed, sent with the files // attached, which from the bar are none, or kept as a draft, and the name of an agent made. @@ -102,7 +104,7 @@ async function answer(path: string, method: string): Promise { return Response.json({fields: await fields, ms: 1}); } if (path.endsWith('/chat/personas') && method === 'GET') { - return Response.json({personas, harnesses: []}); + return Response.json({personas: listedPersonas, harnesses: []}); } if (path.endsWith('/chat/personas') && method === 'POST') { return Response.json({persona: persona('made', 'Stretch reminders', false)}); @@ -142,6 +144,7 @@ async function answer(path: string, method: string): Promise { beforeEach(() => { asked = []; + listedPersonas = personas; picked = {widget: 'none'}; fields = []; messageSent = null; @@ -355,7 +358,7 @@ describe('the command bar over any page', () => { await arrivedAt('/acme/members'); }); - test('what no quick action does is a message to General, sent on Enter, which leads to the conversation', async () => { + test('what no quick action does is a message to the oldest shared agent, General here, sent on Enter, which leads to the conversation', async () => { renderApp(); const input = await openBar(); @@ -376,6 +379,34 @@ describe('the command bar over any page', () => { expect(barIsOpen()).toBe(false); }); + test('with no agent in Chat, what no quick action does says there is none to send it to, and offers to make one that starts on it, once named', async () => { + listedPersonas = []; + renderApp(); + const input = await openBar(); + + fireEvent.change(input, {target: {value: 'plan my trip to Lisbon in March'}}); + const card = await cardNamed('New agent'); + expect(card.textContent).toContain('There is no agent to send this to yet.'); + expect( + (within(card).getByRole('textbox', {name: 'What it does'}) as HTMLTextAreaElement).value, + ).toBe('plan my trip to Lisbon in March'); + const create = within(card).getByRole('button', {name: 'Create agent'}) as HTMLButtonElement; + expect(create.disabled).toBe(true); + fireEvent.keyDown(input, {key: 'Enter'}); + expect(posts('/chat/personas')).toEqual([]); + + fireEvent.change(within(card).getByRole('textbox', {name: 'Name'}), { + target: {value: 'Trips'}, + }); + fireEvent.keyDown(input, {key: 'Enter'}); + + await arrivedAt('/acme/chat/made'); + expect(posts('/chat/personas').map((one) => one.body)).toMatchObject([{name: 'Trips'}]); + expect(posts('/chat/personas/made/threads').map((one) => one.body)).toEqual([ + {text: 'plan my trip to Lisbon in March', attachments: []}, + ]); + }); + test('it goes to the agent the text names, or the one picked', async () => { renderApp(); const input = await openBar(); diff --git a/packages/web/src/components/persona-pane.tsx b/packages/web/src/components/persona-pane.tsx index 2c1e7355..94b0e4f2 100644 --- a/packages/web/src/components/persona-pane.tsx +++ b/packages/web/src/components/persona-pane.tsx @@ -13,8 +13,8 @@ import {describeApiError} from '@/lib/loader-utils'; const LINE = 'text-sm text-muted-foreground'; -// Whose the agent is, in a line under its name: a shared one by who made it, or, where nobody did, -// as General, or its maker has left the organization, just whom it is for. +// Whose the agent is, in a line under its name: a shared one by who made it, or, where its maker +// has left the organization, just whom it is for. function whoseLine(persona: ListedPersona, orgName: string): string { if (!persona.shared) { return 'Yours alone'; diff --git a/packages/web/src/components/unread-provider.test.tsx b/packages/web/src/components/unread-provider.test.tsx index 23cd71e1..2f18b28b 100644 --- a/packages/web/src/components/unread-provider.test.tsx +++ b/packages/web/src/components/unread-provider.test.tsx @@ -201,6 +201,24 @@ describe('UnreadProvider', () => { expect(readCalls()).toHaveLength(1); }); + test('counts nothing and tells of nothing where there is no conversation at all, as once every agent was deleted', async () => { + serve(() => []); + renderProvider(); + + await waitFor(() => { + expect(listCalls()).toHaveLength(1); + }); + comeBack(); + await waitFor(() => { + expect(listCalls()).toHaveLength(2); + }); + expect(screen.getByTestId('count').textContent).toBe('0'); + expect(screen.getByTestId('answers').textContent).toBe(''); + expect(document.title).toBe('Personal Agent Proxy'); + expect(notifyDesktop).not.toHaveBeenCalled(); + expect(readCalls()).toHaveLength(0); + }); + test('reads nothing while the window is not the one the person is in', async () => { renderProvider(); await waitFor(() => { diff --git a/packages/web/src/components/widgets/agent-widget.tsx b/packages/web/src/components/widgets/agent-widget.tsx index db1c2b1f..3d22b199 100644 --- a/packages/web/src/components/widgets/agent-widget.tsx +++ b/packages/web/src/components/widgets/agent-widget.tsx @@ -48,7 +48,7 @@ function AgentPicker({ // A message to one of Chat's agents, which makes the bar Chat's message box: under the input, a // widget that is only its foot, a line as the one that names the model there, saying whom it goes -// to, beside the Send button, the card's main one. What no quick action does is sent as it was typed ("Send this to General"); what was +// to, beside the Send button, the card's main one. What no quick action does is sent as it was typed ("Send this to Finance"); what was // said to an agent by name, without the name ("Send “pay the invoice” to Finance"). The agent is // `suggested`, or another picked in the line. Enter in the bar's input sends it, as in Chat, and // the app goes to the conversation, where the agent answers. diff --git a/packages/web/src/components/widgets/new-agent-widget.tsx b/packages/web/src/components/widgets/new-agent-widget.tsx index 3650893d..7406f74a 100644 --- a/packages/web/src/components/widgets/new-agent-widget.tsx +++ b/packages/web/src/components/widgets/new-agent-widget.tsx @@ -35,11 +35,49 @@ export function NewAgentWidget({ typed: string; bar: BarAction; }) { - const org = useOrgSlug(); - const [name, setName] = useSuggested( - (fieldTexts(intent, 'agentName')[0] ?? '').slice(0, AGENT_NAME_MAX), + return ( + + ); +} + +// What no quick action does, where there is no agent in Chat to send it to, as in an organization +// whose agents were all deleted: it says so, and offers to make one, told what was typed as its +// first message, once the person names it. +export function NoAgentWidget({typed, bar}: {typed: string; bar: BarAction}) { + return ( + ); - const [task, setTask] = useSuggested(fieldTexts(intent, 'agentTask')[0] ?? ''); +} + +// The card that makes an agent, named and told what to do as suggested, under `lead` where there is +// one. +function AgentMaker({ + lead, + suggestedName, + suggestedTask, + typed, + bar, +}: { + lead?: string; + suggestedName: string; + suggestedTask: string; + typed: string; + bar: BarAction; +}) { + const org = useOrgSlug(); + const [name, setName] = useSuggested(suggestedName.slice(0, AGENT_NAME_MAX)); + const [task, setTask] = useSuggested(suggestedTask); const [head, setHead] = useState(freshHead); const [status, setStatus] = useWriteStatus(typed); // Made once, however fast Enter is pressed again. @@ -82,6 +120,7 @@ export function NewAgentWidget({ } > + {lead !== undefined &&

    {lead}

    } {/* As an agent's row in Chat's list: its head, its name, and under it what is said first. */}
    } contentKey={current} - side={side} + // No agent is open at Chat's own address, as where the person sees none: no task's place + // beside what the page shows instead. + side={current === '' ? undefined : side} pane={pane} > setEditing('new')} /> {editing !== null && ( @@ -1040,12 +1042,44 @@ type Opened = { withSettings: (path: string) => string; }; +// What Chat's routes load: an agent's chat, or, at Chat's own address, no chat where the person +// sees no agent (`chatIndexLoader`, which goes to the first otherwise). +type ChatLoaders = typeof chatLoader | typeof chatIndexLoader; + // The chat the address names, once loaded: started over when the address names another agent. -function OpenChat(opened: Opened) { - const {chat, harnesses} = useLoaded(); +// Without one, as where the person sees no agent, what there is to do instead: `onNewAgent` opens +// the dialog that makes one. +function OpenChat({onNewAgent, ...opened}: Opened & {onNewAgent: () => void}) { + const {chat, harnesses} = useLoaded(); + if (chat === null) { + return ; + } return ; } +// Chat with no agent to talk to, as in an organization whose agents were all deleted, across the +// page beside the list that says so: what an agent is, and the way to make one. +function NoAgents({onNew}: {onNew: () => void}) { + return ( +
    + +

    No agents yet

    +

    + An agent works on what you ask it, each task on its own, with what is shared with everyone + and what you connected yourself, as far as its access allows. Make one for yourself, and + share it with everyone if you like. +

    +
    + +
    +
    + ); +} + // What the person said in the chat to open a thread; null for a thread something else opened. function openerText(thread: ChatThread): string | null { return thread.opener?.kind === 'person' ? thread.opener.text : null;