Skip to content

Self-improving AI Employees for everyone

feat(home): rename an employee and give them a photo

trohitg1e69e88d54dd
diff --git a/CLAUDE.md b/CLAUDE.md
index f26e58af..568d395a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2514,7 +2514,7 @@ Updated `client_left` and presence handlers use `has_real_android_devices()` ins
| **Usage/Compaction** | `get_api_usage_summary`, `get_compaction_stats`, `configure_compaction`, `get_provider_usage_summary` |
| **Agent Teams** | `create_team`, `get_team`, `get_team_status`, `dissolve_team`, `add_team_task`, `claim_team_task`, `complete_team_task`, `get_team_tasks`, `send_team_message`, `get_team_messages` |
| **Model Registry** | `get_model_constraints`, `refresh_model_registry` |
-| **Employees (Normal mode)** | `list_employees`, `get_employee`, `get_employee_usage`, `generate_employee_setup`, `cancel_employee_setup`, `hire_employee`, `start_employee`, `enable_employee_talk`, `apply_employee_changes` (see [normal_mode.md](./docs-internal/normal_mode.md)) |
+| **Employees (Normal mode)** | `list_employees`, `get_employee`, `get_employee_usage`, `generate_employee_setup`, `cancel_employee_setup`, `hire_employee`, `start_employee`, `enable_employee_talk`, `apply_employee_changes`, `rename_employee`, `set_employee_photo` (see [normal_mode.md](./docs-internal/normal_mode.md)) |
| **Approvals** | `list_approvals`, `decide_approval` (the `approvalGate` node's drafts) |
#### Broadcast Messages (Server -> All Clients)
diff --git a/client/src/components/catalog/primitives.tsx b/client/src/components/catalog/primitives.tsx
index c5e5e5a2..6e96dbb9 100644
--- a/client/src/components/catalog/primitives.tsx
+++ b/client/src/components/catalog/primitives.tsx
@@ -1,10 +1,21 @@
-/** Shared catalogue brand marks and search fields. */
+/** Shared catalogue brand marks, avatar faces and search fields. */
+import { useState } from 'react';
import { Search } from 'lucide-react';
import { NodeIcon } from '@/assets/icons';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import { theme } from '@/styles/theme';
-import { AVATAR_CLASS, type ColorRole } from './presentation';
+import { AVATAR_CLASS, initialOf, type ColorRole } from './presentation';
+
+/** What an avatar disc shows: the photo when one is given and loads, else
+ * the first letter of the name. */
+export function AvatarFace({ name, photo }: { name: string; photo?: string | null }) {
+ const [broken, setBroken] = useState<string | null>(null);
+ if (photo && broken !== photo) {
+ return <img src={photo} alt="" draggable={false} onError={() => setBroken(photo)} className="size-full rounded-full object-cover" />;
+ }
+ return <>{initialOf(name)}</>;
+}
const MARK_SIZE = {
xs: { box: 'size-5', icon: theme.iconSize.xs },
diff --git a/client/src/features/chat/host.ts b/client/src/features/chat/host.ts
index 6fb3efb8..1b2aa265 100644
--- a/client/src/features/chat/host.ts
+++ b/client/src/features/chat/host.ts
@@ -16,6 +16,8 @@ export type ChatHostKind = 'home' | 'dev';
export interface ChatPersona {
name: string;
colorRole: ColorRole;
+ /** Their photo, when the owner gave them one. */
+ photo?: string | null;
}
/**
diff --git a/client/src/features/chat/thread/ChatAvatar.tsx b/client/src/features/chat/thread/ChatAvatar.tsx
index 2caee4e6..edbc7cb7 100644
--- a/client/src/features/chat/thread/ChatAvatar.tsx
+++ b/client/src/features/chat/thread/ChatAvatar.tsx
@@ -1,10 +1,11 @@
/**
- * The answering employee's avatar beside their turns: their initial in
- * their role colour, and a spinning ring while they work (design handoff
- * chat, "Streaming": the live ring).
+ * The answering employee's avatar beside their turns: their photo, else
+ * their initial, in their role colour, and a spinning ring while they work
+ * (design handoff chat, "Streaming": the live ring).
*/
-import { AVATAR_CLASS, initialOf } from '@/components/catalog/presentation';
+import { AVATAR_CLASS } from '@/components/catalog/presentation';
+import { AvatarFace } from '@/components/catalog/primitives';
import { cn } from '@/lib/utils';
import type { ChatPersona } from '../host';
@@ -19,7 +20,7 @@ export function ChatAvatar({ persona, live = false, compact = false }: { persona
compact ? 'text-2xs' : 'text-xs',
)}
>
- {initialOf(persona.name)}
+ <AvatarFace name={persona.name} photo={persona.photo} />
</span>
</span>
);
diff --git a/client/src/features/home/__tests__/homeHeader.test.tsx b/client/src/features/home/__tests__/homeHeader.test.tsx
index c167920b..08c189bc 100644
--- a/client/src/features/home/__tests__/homeHeader.test.tsx
+++ b/client/src/features/home/__tests__/homeHeader.test.tsx
@@ -1,8 +1,9 @@
/**
* The Home header: on an employee's page it says who they are (name, role
* and apps, status) and offers New conversation, which asks first; the
- * Normal/Dev switch opens that employee's workflow there, and elsewhere
- * what the editor last had.
+ * owner renames them and changes their photo there; the Normal/Dev switch
+ * opens that employee's workflow there, and elsewhere what the editor last
+ * had.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -22,12 +23,15 @@ vi.mock('../../../app/ShellModeSwitch', () => ({ useShellMode: () => 'normal' })
vi.mock('../workspace/WorkspaceButton', () => ({ WorkspaceButton: () => null }));
vi.mock('../header/ThemeButton', () => ({ ThemeButton: () => null }));
vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));
+vi.mock('@/lib/workspaceUpload', () => ({ uploadToWorkspace: vi.fn() }));
import { normalizeWorkflowControlStatus } from '@/contexts/WebSocketContext';
+import { uploadToWorkspace } from '@/lib/workspaceUpload';
import { enterDev } from '../../../app/useShellActions';
import { parseEmployee } from '../data/schemas';
import { HomeHeader } from '../header/HomeHeader';
import { useHomeStore } from '../state/homeStore';
+import { pillToast } from '../ui/pillToast';
const maya = parseEmployee({
workflow_id: 'w1',
@@ -86,6 +90,80 @@ describe('HomeHeader', () => {
expect(enterDev).toHaveBeenCalledWith({ workflowId: 'w1' });
});
+ it('renames them from the pencil beside their name', async () => {
+ const user = userEvent.setup();
+ let answer: (value: unknown) => void = () => {};
+ sendRequest.mockImplementation((type: string) =>
+ type === 'rename_employee' ? new Promise((resolve) => (answer = resolve)) : Promise.resolve({ success: true }),
+ );
+ useHomeStore.setState({ view: { kind: 'employee', workflowId: 'w1' } });
+ wrap(<HomeHeader title="Maya" employee={maya} scrolled={false} />);
+ await user.click(screen.getByRole('button', { name: 'Rename Maya' }));
+ const box = screen.getByRole('textbox', { name: 'Name' });
+ expect(box).toHaveValue('Maya');
+ await user.clear(box);
+ await user.type(box, ' Ana Lopez {Enter}');
+ expect(sendRequest).toHaveBeenCalledWith('rename_employee', { workflow_id: 'w1', name: 'Ana Lopez' });
+ // The new name shows while it saves.
+ expect(screen.getByRole('heading', { name: 'Ana Lopez' })).toBeInTheDocument();
+ answer({ success: true });
+ });
+
+ it('keeps the name when the owner presses Escape', async () => {
+ const user = userEvent.setup();
+ useHomeStore.setState({ view: { kind: 'employee', workflowId: 'w1' } });
+ wrap(<HomeHeader title="Maya" employee={maya} scrolled={false} />);
+ await user.click(screen.getByRole('button', { name: 'Rename Maya' }));
+ await user.type(screen.getByRole('textbox', { name: 'Name' }), ' Lopez{Escape}');
+ expect(screen.getByRole('heading', { name: 'Maya' })).toBeInTheDocument();
+ expect(sendRequest).not.toHaveBeenCalledWith('rename_employee', expect.anything());
+ });
+
+ it('gives a hired employee a photo they upload', async () => {
+ const user = userEvent.setup();
+ vi.mocked(uploadToWorkspace).mockResolvedValue({ path: 'uploads/me.png' } as Awaited<ReturnType<typeof uploadToWorkspace>>);
+ useHomeStore.setState({ view: { kind: 'employee', workflowId: 'w1' } });
+ wrap(<HomeHeader title="Maya" employee={{ ...maya, derived: false }} scrolled={false} />);
+ await user.click(screen.getByRole('button', { name: 'Change Maya’s photo' }));
+ expect(screen.queryByRole('menuitem', { name: 'Remove photo' })).not.toBeInTheDocument();
+ await user.click(await screen.findByRole('menuitem', { name: 'Upload photo…' }));
+ const photo = new File(['png'], 'me.png', { type: 'image/png' });
+ await user.upload(screen.getByTestId('employee-photo-input'), photo);
+ await waitFor(() => expect(sendRequest).toHaveBeenCalledWith('set_employee_photo', { workflow_id: 'w1', path: 'uploads/me.png' }));
+ expect(uploadToWorkspace).toHaveBeenCalledWith(photo, 'w1');
+ });
+
+ it('refuses a file that is not a photo before uploading it', async () => {
+ vi.mocked(uploadToWorkspace).mockClear();
+ useHomeStore.setState({ view: { kind: 'employee', workflowId: 'w1' } });
+ wrap(<HomeHeader title="Maya" employee={{ ...maya, derived: false }} scrolled={false} />);
+ fireEvent.change(screen.getByTestId('employee-photo-input'), { target: { files: [new File(['x'], 'notes.txt', { type: 'text/plain' })] } });
+ await waitFor(() => expect(pillToast).toHaveBeenCalledWith('A photo is a PNG, JPEG, WebP or GIF image.', { tone: 'error' }));
+ expect(uploadToWorkspace).not.toHaveBeenCalled();
+ expect(sendRequest).not.toHaveBeenCalledWith('set_employee_photo', expect.anything());
+ });
+
+ it('shows the photo, takes it away, and falls back to the initial when it will not load', async () => {
+ const user = userEvent.setup();
+ useHomeStore.setState({ view: { kind: 'employee', workflowId: 'w1' } });
+ const photoUrl = '/api/workspace/w1/files/uploads/me.png?v=1';
+ const { container } = wrap(<HomeHeader title="Maya" employee={{ ...maya, derived: false, photo_url: photoUrl }} scrolled={false} />);
+ const image = container.querySelector('img');
+ expect(image).toHaveAttribute('src', photoUrl);
+ await user.click(screen.getByRole('button', { name: 'Change Maya’s photo' }));
+ await user.click(await screen.findByRole('menuitem', { name: 'Remove photo' }));
+ await waitFor(() => expect(sendRequest).toHaveBeenCalledWith('set_employee_photo', { workflow_id: 'w1', path: null }));
+ fireEvent.error(image!);
+ expect(container.querySelector('img')).toBeNull();
+ expect(screen.getByRole('button', { name: 'Change Maya’s photo' })).toHaveTextContent('M');
+ });
+
+ it('keeps the initial of an employee built in the editor', () => {
+ useHomeStore.setState({ view: { kind: 'employee', workflowId: 'w1' } });
+ wrap(<HomeHeader title="Maya" employee={maya} scrolled={false} />);
+ expect(screen.queryByRole('button', { name: 'Change Maya’s photo' })).not.toBeInTheDocument();
+ });
+
it('opens what the editor last had from the hire view', () => {
useHomeStore.setState({ view: { kind: 'hire' } });
wrap(<HomeHeader title="New employee" employee={null} scrolled={false} />);
diff --git a/client/src/features/home/data/identity.ts b/client/src/features/home/data/identity.ts
new file mode 100644
index 00000000..976d4a61
--- /dev/null
+++ b/client/src/features/home/data/identity.ts
@@ -0,0 +1,55 @@
+/**
+ * Who an employee is: their name and their photo (server
+ * services/employees/handlers.py `rename_employee`, `set_employee_photo`).
+ * Both refresh the team afterwards; the server tells every other client.
+ *
+ * A photo is uploaded into the employee's workspace (`uploads/`, through the
+ * same route the chat's attachments use) and then given to them by path;
+ * the server checks it is an image it can show.
+ */
+
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { useWebSocketActions } from '@/contexts/WebSocketContext';
+import { uploadToWorkspace } from '@/lib/workspaceUpload';
+import { refreshEmployee } from './employees';
+
+/** The images a photo may be; the server refuses any other. */
+export const PHOTO_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif'] as const;
+/** Mirrors `EMPLOYEE_PHOTO_MAX_BYTES` in server/services/media/limits.py. The
+ * server decides; checking here only gives a better message sooner. */
+export const PHOTO_MAX_BYTES = 5 * 1024 * 1024;
+
+type Reply = { success?: boolean; error?: string; detail?: string };
+
+/** Rename an employee. Errors carry the server's code. */
+export function useRenameEmployee() {
+ const { sendRequest } = useWebSocketActions();
+ const queryClient = useQueryClient();
+ return useMutation<void, Error, { workflowId: string; name: string }>({
+ mutationFn: async ({ workflowId, name }) => {
+ const reply = await sendRequest<Reply>('rename_employee', { workflow_id: workflowId, name });
+ if (reply?.success === false) throw new Error(reply.error || 'failed');
+ },
+ onSettled: (_data, _error, { workflowId }) => refreshEmployee(queryClient, workflowId),
+ });
+}
+
+/** Give an employee a photo, or take it away (`file: null`). Errors carry a
+ * message the owner can act on. */
+export function useSetEmployeePhoto() {
+ const { sendRequest } = useWebSocketActions();
+ const queryClient = useQueryClient();
+ return useMutation<void, Error, { workflowId: string; file: File | null }>({
+ mutationFn: async ({ workflowId, file }) => {
+ let path: string | null = null;
+ if (file) {
+ if (!(PHOTO_TYPES as readonly string[]).includes(file.type)) throw new Error('A photo is a PNG, JPEG, WebP or GIF image.');
+ if (file.size > PHOTO_MAX_BYTES) throw new Error(`A photo is at most ${PHOTO_MAX_BYTES / (1024 * 1024)} MB.`);
+ path = (await uploadToWorkspace(file, workflowId)).path;
+ }
+ const reply = await sendRequest<Reply>('set_employee_photo', { workflow_id: workflowId, path });
+ if (reply?.success === false) throw new Error(reply.detail || 'That photo couldn’t be used. Try another.');
+ },
+ onSettled: (_data, _error, { workflowId }) => refreshEmployee(queryClient, workflowId),
+ });
+}
diff --git a/client/src/features/home/data/schemas.ts b/client/src/features/home/data/schemas.ts
index 12047b10..fe875fd3 100644
--- a/client/src/features/home/data/schemas.ts
+++ b/client/src/features/home/data/schemas.ts
@@ -38,6 +38,8 @@ const appList = z.array(appRefSchema).catch([]);
export const employeeSummarySchema = z.object({
workflow_id: z.string().min(1),
name: z.string(),
+ /** The photo the owner gave them (the workspace file route); null shows their initial. */
+ photo_url: z.string().nullable().catch(null),
role: z.string().catch(''),
color_role: z.enum(COLOR_ROLES).catch('agent'),
derived: z.boolean().catch(true),
diff --git a/client/src/features/home/employee/EmployeeChat.tsx b/client/src/features/home/employee/EmployeeChat.tsx
index 9e6fadb6..4cd1355d 100644
--- a/client/src/features/home/employee/EmployeeChat.tsx
+++ b/client/src/features/home/employee/EmployeeChat.tsx
@@ -147,7 +147,7 @@ export function EmployeeChat({
kind: 'home',
sessionId: workflowId,
scope: 'all',
- persona: { name, colorRole: employee.color_role },
+ persona: { name, colorRole: employee.color_role, photo: employee.photo_url },
composer,
notices: <Notices employee={employee} control={control} queued={lane?.state === 'queued'} />,
top: (
diff --git a/client/src/features/home/genui/index.ts b/client/src/features/home/genui/index.ts
index af3a1954..5a3c7f44 100644
--- a/client/src/features/home/genui/index.ts
+++ b/client/src/features/home/genui/index.ts
@@ -6,6 +6,7 @@
* exported here brings json-render with it.
*/
+export { HIRE_LIMITS } from './hirePayload';
export { HireDraftPanel } from './HireDraftPanel';
export { MessagePreview as DraftMessagePreview } from './MessagePreview';
export { useHireComposer } from './useHireComposer';
diff --git a/client/src/features/home/header/HomeHeader.tsx b/client/src/features/home/header/HomeHeader.tsx
index 8f953d6e..955a58c7 100644
--- a/client/src/features/home/header/HomeHeader.tsx
+++ b/client/src/features/home/header/HomeHeader.tsx
@@ -2,22 +2,31 @@
* Normal mode's header (design handoff "Main header"; chat "Header"): with
* the sidebar collapsed, an open button and the logo. Then the view: while
* hiring, its title; on an employee's page, who they are (avatar, name,
- * role and apps, their status) and New conversation. At the end the
- * Workspace pill, the Normal/Dev switch (on an employee's page, Dev opens
- * their workflow) and the theme button. The bottom border appears only once
- * the content has scrolled, so the hero reads as one surface.
+ * role and apps, their status) and New conversation. The owner renames them
+ * with the pencil beside their name, and gives them a photo (or takes it
+ * away) from their avatar's menu; an employee built in the editor keeps its
+ * initial. At the end the Workspace pill, the Normal/Dev switch (on an
+ * employee's page, Dev opens their workflow) and the theme button. The
+ * bottom border appears only once the content has scrolled, so the hero
+ * reads as one surface.
*/
-import { PanelLeft } from 'lucide-react';
+import { useRef, useState } from 'react';
+import { ImagePlus, PanelLeft, Pencil, Trash2 } from 'lucide-react';
import { OcLogo } from '@/components/brand/Logo';
import { ModeToggle } from '@/components/shell/ModeToggle';
import { Button } from '@/components/ui/button';
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
+import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import { useWorkflowControlPending } from '@/stores/workflowControlStore';
+import { PHOTO_TYPES, useRenameEmployee, useSetEmployeePhoto } from '../data/identity';
import { presentEmployee } from '../data/presentation';
import type { EmployeeSummary } from '../data/schemas';
+import { HIRE_LIMITS } from '../genui';
import { useHomeStore } from '../state/homeStore';
import { Avatar, StatusPill } from '../ui/primitives';
+import { pillToast } from '../ui/pillToast';
import { WorkspaceButton } from '../workspace/WorkspaceButton';
import { NewConversationButton } from './NewConversationButton';
import { ThemeButton } from './ThemeButton';
@@ -28,15 +37,122 @@ function subtitleOf(employee: EmployeeSummary): string {
return [employee.role, apps].filter(Boolean).join(' · ');
}
+function PhotoButton({ employee }: { employee: EmployeeSummary }) {
+ const setPhoto = useSetEmployeePhoto();
+ const input = useRef<HTMLInputElement>(null);
+ const avatar = <Avatar name={employee.name} colorRole={employee.color_role} photo={employee.photo_url} size="sm" />;
+ if (employee.derived) return avatar;
+ const change = (file: File | null) =>
+ setPhoto.mutate(
+ { workflowId: employee.workflow_id, file },
+ { onError: (error) => pillToast(error.message || 'That photo couldn’t be used. Try another.', { tone: 'error' }) },
+ );
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="quiet"
+ size="icon"
+ aria-label={`Change ${employee.name}’s photo`}
+ title="Change photo"
+ className="size-auto rounded-full p-0"
+ >
+ {avatar}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ <DropdownMenuItem onSelect={() => input.current?.click()}>
+ <ImagePlus />
+ Upload photo…
+ </DropdownMenuItem>
+ {employee.photo_url && (
+ <DropdownMenuItem onSelect={() => change(null)}>
+ <Trash2 />
+ Remove photo
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <input
+ ref={input}
+ type="file"
+ accept={PHOTO_TYPES.join(',')}
+ hidden
+ data-testid="employee-photo-input"
+ onChange={(event) => {
+ const file = event.target.files?.[0] ?? null;
+ event.target.value = '';
+ if (file) change(file);
+ }}
+ />
+ </>
+ );
+}
+
+function Name({ employee }: { employee: EmployeeSummary }) {
+ const rename = useRenameEmployee();
+ const [draft, setDraft] = useState<string | null>(null);
+ // The new name shows while it saves; the refreshed summary takes over.
+ const shown = rename.isPending && rename.variables ? rename.variables.name : employee.name;
+ const save = () => {
+ if (draft === null) return;
+ const name = draft.replace(/\s+/g, ' ').trim();
+ setDraft(null);
+ if (!name || name === employee.name) return;
+ rename.mutate(
+ { workflowId: employee.workflow_id, name },
+ { onError: () => pillToast(`${employee.name} wasn’t renamed. Try again.`, { tone: 'error' }) },
+ );
+ };
+ if (draft !== null) {
+ return (
+ <Input
+ autoFocus
+ aria-label="Name"
+ value={draft}
+ maxLength={HIRE_LIMITS.name}
+ onChange={(event) => setDraft(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ save();
+ } else if (event.key === 'Escape') {
+ event.preventDefault();
+ setDraft(null);
+ }
+ }}
+ onBlur={save}
+ className="h-7 w-48 px-2 text-base font-semibold"
+ />
+ );
+ }
+ return (
+ <div className="flex min-w-0 items-center gap-0.5">
+ <h2 className="m-0 truncate text-base font-semibold text-fg-default">{shown}</h2>
+ <Button
+ variant="quiet"
+ size="icon"
+ aria-label={`Rename ${shown}`}
+ title="Rename"
+ onClick={() => setDraft(shown)}
+ className="size-6 shrink-0 rounded-md text-fg-faint"
+ >
+ <Pencil className="size-3.5" strokeWidth={1.75} />
+ </Button>
+ </div>
+ );
+}
+
function Identity({ employee }: { employee: EmployeeSummary }) {
const pending = useWorkflowControlPending(employee.workflow_id);
const { pill, pulse } = presentEmployee(employee, pending);
const subtitle = subtitleOf(employee);
return (
<div className="flex min-w-0 items-center gap-2.5 px-1">
- <Avatar name={employee.name} colorRole={employee.color_role} size="sm" />
+ <PhotoButton employee={employee} />
<div className="flex min-w-0 flex-col">
- <h2 className="m-0 truncate text-base font-semibold text-fg-default">{employee.name}</h2>
+ <Name employee={employee} />
{subtitle && <span className="truncate text-xs text-fg-muted">{subtitle}</span>}
</div>
<StatusPill tone={pill.tone} label={pill.label} pulse={pulse} size="compact" />
diff --git a/client/src/features/home/sidebar/HomeSidebar.tsx b/client/src/features/home/sidebar/HomeSidebar.tsx
index 70cce5fc..eb7bd8d4 100644
--- a/client/src/features/home/sidebar/HomeSidebar.tsx
+++ b/client/src/features/home/sidebar/HomeSidebar.tsx
@@ -96,7 +96,7 @@ function EmployeeRow({ employee, selected }: { employee: EmployeeSummary; select
onClick={() => showEmployee(employee.workflow_id)}
className="flex min-h-12.5 min-w-0 flex-1 items-center gap-2.5 rounded-row px-2.5 py-1.5 text-left"
>
- <Avatar name={employee.name} colorRole={employee.color_role} status={view.pill.tone} pulse={view.pulse} />
+ <Avatar name={employee.name} colorRole={employee.color_role} photo={employee.photo_url} status={view.pill.tone} pulse={view.pulse} />
<span className="flex min-w-0 flex-1 flex-col gap-px">
<span className="truncate text-row font-medium">{employee.name}</span>
<span className="truncate text-xs text-fg-muted">{employee.role}</span>
diff --git a/client/src/features/home/ui/primitives.tsx b/client/src/features/home/ui/primitives.tsx
index 11fbbcb3..9cc107fd 100644
--- a/client/src/features/home/ui/primitives.tsx
+++ b/client/src/features/home/ui/primitives.tsx
@@ -5,12 +5,12 @@
*/
import type { ReactNode } from 'react';
+import { AvatarFace } from '@/components/catalog/primitives';
import { cn } from '@/lib/utils';
import {
AVATAR_CLASS,
STATUS_DOT_CLASS,
STATUS_PILL_CLASS,
- initialOf,
type StatusTone,
} from '../data/presentation';
import type { ColorRole } from '../data/schemas';
@@ -24,6 +24,7 @@ const AVATAR_SIZE = {
export function Avatar({
name,
colorRole,
+ photo,
size = 'md',
status,
pulse = false,
@@ -31,6 +32,8 @@ export function Avatar({
}: {
name: string;
colorRole: ColorRole;
+ /** Their photo; without one (or while it fails to load), their initial. */
+ photo?: string | null;
size?: keyof typeof AVATAR_SIZE;
/** Draws the status pip bottom-right (sidebar rows). */
status?: StatusTone;
@@ -47,7 +50,7 @@ export function Avatar({
className,
)}
>
- {initialOf(name)}
+ <AvatarFace name={name} photo={photo} />
{status && (
<StatusDot
tone={status}
diff --git a/client/src/features/home/workspace/WorkspaceDock.tsx b/client/src/features/home/workspace/WorkspaceDock.tsx
index 164c2e1b..ae5ff679 100644
--- a/client/src/features/home/workspace/WorkspaceDock.tsx
+++ b/client/src/features/home/workspace/WorkspaceDock.tsx
@@ -81,7 +81,7 @@ function Identity({ employee }: { employee: EmployeeSummary }) {
employee.status === 'working' && !employee.browser_request ? { tone: 'live' as const, label: 'Live' } : presentEmployee(employee).pill;
return (
<>
- <Avatar name={employee.name} colorRole={employee.color_role} size="sm" />
+ <Avatar name={employee.name} colorRole={employee.color_role} photo={employee.photo_url} size="sm" />
<div className="flex min-w-0 flex-1 flex-col gap-px">
<span className="truncate text-base font-semibold text-fg-default">{employee.name}’s workspace</span>
{task && <span className="truncate font-mono text-2xs text-fg-muted">{task.text}</span>}
diff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.md
index 4a50e47a..69261836 100644
--- a/docs-internal/normal_mode.md
+++ b/docs-internal/normal_mode.md
@@ -434,7 +434,12 @@ will finish. The wire contract is [chat_protocol.md](./chat_protocol.md).
is the page: the shared chat ([features/chat](../client/src/features/chat/),
the same `ChatPane` the editor's console Chat pane uses) with Home around it.
The header names the employee instead of the page (`HomeHeader`: avatar,
-name, role and apps, the status pill, and New conversation), and `HomeShell`
+name, role and apps, the status pill, and New conversation). The pencil beside
+the name renames them, and the avatar's menu uploads a photo for a hired
+employee or takes it away ([data/identity.ts](../client/src/features/home/data/identity.ts));
+the photo then stands in for their initial in the sidebar, the header, the
+Workspace and beside each reply, and the initial comes back when it will not
+load. `HomeShell`
gives the page a column that does not scroll: the conversation scrolls on its
own above the message box, and tells the shell when it has left the top so the
header draws its border. Turn on Talk and Apply are in
@@ -787,7 +792,7 @@ WebSocket requests (snake_case; failures come back as `success: false` with an
| Type | Payload | Response |
|---|---|---|
-| `list_employees` | `{}` | `{employees}`; each summary's `canvas_node_id` is its Canvas board: the one it was hired with, else the graph's first Canvas node, else null. `browser_request` is a browser waiting for the owner (`{node_id, reason, since}`), else null. `talk` is `{state: "on" \| "off" \| "unsupported", agent_node_id}` (the agent that answers the owner; not in `watch_node_ids`). `task` is `{label, text}`, or null when the page already says it (a running employee with Talk on whose only work is the owner's messages). `asks_first` is the hire's "ask me first" rule (built in Dev mode: whether it has an approval gate). `pending_changes` is true when the saved graph's structure differs from the live generation's snapshot |
+| `list_employees` | `{}` | `{employees}`; each summary's `canvas_node_id` is its Canvas board: the one it was hired with, else the graph's first Canvas node, else null. `browser_request` is a browser waiting for the owner (`{node_id, reason, since}`), else null. `talk` is `{state: "on" \| "off" \| "unsupported", agent_node_id}` (the agent that answers the owner; not in `watch_node_ids`). `task` is `{label, text}`, or null when the page already says it (a running employee with Talk on whose only work is the owner's messages). `asks_first` is the hire's "ask me first" rule (built in Dev mode: whether it has an approval gate). `pending_changes` is true when the saved graph's structure differs from the live generation's snapshot. `photo_url` is the photo the owner gave them (the workspace file route, versioned), else null |
| `get_employee` | `{workflow_id}` | the summary plus `description`, `job`, `plan`, `rules`, `choices`, `trigger_text`, `last_run`, `latest_report` |
| `get_employee_usage` | `{}` | `{tasks_this_month}` (successful runs since the 1st, owner's timezone, whole team) |
| `generate_employee_setup` | `{job, refine?, history?, draft_token}` | `{draft_token, reply, provider, model, usage, retried, finish_reason, apps}`; `apps` maps each app the reply mentions to its AppRef plus `can_trigger` |
@@ -796,6 +801,8 @@ WebSocket requests (snake_case; failures come back as `success: false` with an
| `start_employee` | `{workflow_id, expected_revision, idempotency_key}` | as `start_workflow` |
| `enable_employee_talk` | `{workflow_id, idempotency_key}` | `{employee}`. Errors: `invalid_request`, `not_found`, `unsupported`, `conflict` (a start, pause, resume or reset is under way, or the graph changed meanwhile), `restart_failed`; the last three carry `employee` too |
| `apply_employee_changes` | `{workflow_id, idempotency_key}` | `{employee}`: running ends running, paused or failed ends ready, ready is left alone. Errors: `invalid_request`, `not_found`, `conflict`, `restart_failed` (the last two with `employee`) |
+| `rename_employee` | `{workflow_id, name}` (spaces collapsed, at most 40 characters) | `{employee}`: renames the workflow (a new slug, the workspace folder moved, `workflow.renamed` sent), and each agent's instructions a hire wrote take the new name in their opening ("You are <name>, ..."); instructions the owner rewrote keep their words. Agents read them on every run, so nothing restarts. Errors: `invalid_request`, `not_found`, `save_failed` |
+| `set_employee_photo` | `{workflow_id, path \| null}` | `{employee}`: `path` is a PNG, JPEG, WebP or GIF the owner uploaded under `uploads/` (`POST /api/workspace/{workflow_id}/uploads`), at most 5 MB (`EMPLOYEE_PHOTO_MAX_BYTES`); `null` takes the photo away. Errors: `invalid_request`, `not_found`, `invalid_photo` (with `detail`), `unsupported` (a workflow built in the editor has no employee row to keep it on) |
| `send_chat_message` | `{message, role: "user", session_id: <workflow_id>, timestamp, client_message_id?}` | `{timestamp, delivery, message_id, run_id}`: `"now"` while running, starting or resuming; `"queued"` while paused or pausing (it runs on Resume). In any other state `not_running`, and nothing is saved or sent; `run_in_progress` (with the live `run_id`) while a run is live. `run_id` is null when no deployed chat trigger answers the session. Session `"default"` works as before, with no `delivery` |
| `get_chat_messages` | `{session_id, limit?, all_generations?}` | `{messages, thread, active_runs}`, messages oldest first, each `{id, role, message, timestamp, run_key, ...}` (the full shape is in [chat_protocol.md](./chat_protocol.md#messages)). Timestamps carry their UTC offset; `run_key` is the generation the row was written in. Without `all_generations`, only the latest generation's rows (none after a Reset; every row when the workflow was never started). A failed read answers `read_failed`, never an empty thread |
| `list_approvals` | `{workflow_id?, status?, limit <= 100}` | `{approvals, counts, server_time}` |
diff --git a/server/core/database.py b/server/core/database.py
index 09796534..fce71b34 100644
--- a/server/core/database.py
+++ b/server/core/database.py
@@ -149,6 +149,7 @@ class Database:
await self._migrate_chat_messages()
await self._migrate_chat_runs()
await self._migrate_approvals()
+ await self._migrate_employees()
logger.info("Database initialized successfully")
@@ -555,6 +556,21 @@ class Database:
except Exception as exc:
logger.warning(f"Chat run migration check failed: {exc}")
+ async def _migrate_employees(self):
+ """Give an older ``employees`` table the columns added since."""
+ columns_added = {"photo_path": "VARCHAR(500)"}
+ try:
+ async with self.engine.begin() as conn:
+ result = await conn.execute(text("PRAGMA table_info(employees)"))
+ columns = {row[1] for row in result.fetchall()}
+ if not columns:
+ return
+ for column, definition in columns_added.items():
+ if column not in columns:
+ await conn.execute(text(f"ALTER TABLE employees ADD COLUMN {column} {definition}"))
+ except Exception as exc:
+ logger.warning(f"Employee migration check failed: {exc}")
+
async def _migrate_approvals(self):
"""Give an older ``approval_requests`` table the columns approvals v2
added (held tool calls, Undo and Restore, outcomes). A draft approved
diff --git a/server/models/employees.py b/server/models/employees.py
index e21717c1..0d75293f 100644
--- a/server/models/employees.py
+++ b/server/models/employees.py
@@ -72,6 +72,10 @@ class Employee(SQLModel, table=True):
#: The model the employee runs on: {provider, model}.
llm: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON, nullable=False))
builder_version: int = Field(default=1)
+ #: A photo the owner uploaded for the employee: a path under the
+ #: workflow workspace's ``uploads/`` (``set_employee_photo``). None
+ #: shows their initial.
+ photo_path: Optional[str] = Field(default=None, max_length=500)
hired_at: Optional[datetime] = Field(default=None, sa_column=Column(DateTime(timezone=True), nullable=True))
created_at: datetime = Field(default_factory=_utcnow, sa_column=Column(DateTime(timezone=True), nullable=False))
diff --git a/server/services/employees/handlers.py b/server/services/employees/handlers.py
index 394b07de..d05845f7 100644
--- a/server/services/employees/handlers.py
+++ b/server/services/employees/handlers.py
@@ -24,6 +24,20 @@ talk to), ``conflict`` (a start, pause, resume or reset is under way, or
the graph changed meanwhile), ``restart_failed``. A retry with the same
key adds nothing twice and restarts once. Changes to one employee run one
at a time.
+
+Two change who the employee is, for the owner of the workflow only, and
+answer the same way:
+
+- ``rename_employee {workflow_id, name}``: renames their workflow (a new
+ slug, the workspace folder moved, ``workflow.renamed`` sent), and each
+ agent's instructions a hire wrote take the new name in their opening.
+ ``save_failed`` when the rename was not saved.
+- ``set_employee_photo {workflow_id, path | null}``: the photo they show,
+ a PNG, JPEG, WebP or GIF the owner uploaded to the workspace's
+ ``uploads/`` (at most ``EMPLOYEE_PHOTO_MAX_BYTES``); ``null`` takes it
+ away. ``invalid_photo`` (with ``detail``) for any other file,
+ ``unsupported`` for a workflow built in the editor (it has no employee
+ row to keep it on).
"""
from __future__ import annotations
@@ -40,14 +54,24 @@ from services.employees import store
from services.employees.apps import get_app
from services.employees.builder import CHAT_UI_TYPE, talk_tools
from services.employees.context import SETTINGS_USER_ID
+from services.employees.events import employee_changed_now
from services.employees.graph_index import CANVAS_NODE_TYPE, MEMORY_NODE_TYPE, TODO_NODE_TYPE, index_graph
-from services.employees.prompt import OwnerProfile, PromptInputs, build_system_message, request_from_employee, talk_addendum
+from services.employees.hire_request import NAME_MAX
+from services.employees.prompt import (
+ OwnerProfile,
+ PromptInputs,
+ build_system_message,
+ renamed_instructions,
+ request_from_employee,
+ talk_addendum,
+)
from services.employees.summaries import employee_usage, get_employee_detail, get_employee_summary, list_employee_summaries
from services.employees.talk import TalkAgent, TalkState, TalkTool, plan_talk_line, sources, talk_agent_label, talk_state
from services.employees.upgrade import upgrade_employee
from services.graph_build import TOOLS_INPUT
from services.plugin.base import NodeUserError
from services.plugin.ws import ws_response
+from services.media.limits import EMPLOYEE_PHOTO_MAX_BYTES
from services.workflow_storage.mutate import apply_graph_additions
#: Control states a change must not interrupt.
@@ -244,6 +268,96 @@ async def handle_apply_employee_changes(data: Dict[str, Any], websocket: WebSock
)
+# ----- Name and photo -----
+
+#: What a photo may be: images the workspace file route shows inline.
+PHOTO_TYPES = frozenset({"image/png", "image/jpeg", "image/webp", "image/gif"})
+
+
+async def _owns(database: Any, websocket: Any, workflow_id: str) -> bool:
+ from services.chat.access import ChatAccessDenied, authorize_session
+
+ try:
+ await authorize_session(database, websocket, workflow_id)
+ except ChatAccessDenied:
+ return False
+ return True
+
+
+async def _rename_in_instructions(database: Any, workflow: Any, old: str, new: str) -> None:
+ """Each agent's instructions a hire wrote take the new name; ones the
+ owner rewrote are left alone. Read on every run, so no restart."""
+ from services.status_broadcaster import get_status_broadcaster
+
+ for node_id in index_graph(getattr(workflow, "data", None)).agent_ids:
+ params = await database.get_node_parameters(node_id) or {}
+ renamed = renamed_instructions(str(params.get("system_message") or ""), old, new)
+ if renamed is None:
+ continue
+ params = {**params, "system_message": renamed}
+ await database.save_node_parameters(node_id, params)
+ await get_status_broadcaster().broadcast_node_parameters_updated(
+ node_id, parameters=params, workflow_id=workflow.id, source_hint="employee"
+ )
+
+
+@ws_response
+async def handle_rename_employee(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ workflow_id = str(data.get("workflow_id") or "").strip()
+ name = " ".join(str(data.get("name") or "").split())[:NAME_MAX]
+ if not workflow_id or not name:
+ return {"success": False, "error": "invalid_request"}
+ from core.container import container
+ from services.workflow_storage.handlers import rename_saved_workflow
+
+ database, auth_service = container.database(), container.auth_service()
+ if not await _owns(database, websocket, workflow_id):
+ return {"success": False, "error": "not_found", "workflow_id": workflow_id}
+ async with _lock(workflow_id):
+ workflow = await database.get_workflow(workflow_id)
+ if workflow is None:
+ return {"success": False, "error": "not_found", "workflow_id": workflow_id}
+ old = str(workflow.name or "")
+ if name != old:
+ if await rename_saved_workflow(database, workflow_id, name) is None:
+ return await _answer(database, auth_service, workflow_id, "save_failed")
+ await _rename_in_instructions(database, workflow, old, name)
+ return await _answer(database, auth_service, workflow_id)
+
+
+@ws_response
+async def handle_set_employee_photo(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ workflow_id = str(data.get("workflow_id") or "").strip()
+ path = data.get("path")
+ if not workflow_id or (path is not None and not isinstance(path, str)):
+ return {"success": False, "error": "invalid_request"}
+ from core.container import container
+
+ database, auth_service = container.database(), container.auth_service()
+ if not await _owns(database, websocket, workflow_id):
+ return {"success": False, "error": "not_found", "workflow_id": workflow_id}
+ if path is not None:
+ from services.chat.attachments import AttachmentRefused, check_attachments
+
+ try:
+ [ref] = await check_attachments(database, workflow_id, [path])
+ except AttachmentRefused as exc:
+ return {"success": False, "error": "invalid_photo", "detail": str(exc)}
+ if ref["mime_type"] not in PHOTO_TYPES:
+ return {"success": False, "error": "invalid_photo", "detail": "A photo is a PNG, JPEG, WebP or GIF image."}
+ if ref["size_bytes"] > EMPLOYEE_PHOTO_MAX_BYTES:
+ return {
+ "success": False,
+ "error": "invalid_photo",
+ "detail": f"A photo is at most {EMPLOYEE_PHOTO_MAX_BYTES // (1024 * 1024)} MB.",
+ }
+ path = ref["path"]
+ if await store.set_photo(database, workflow_id, path) is None:
+ return {"success": False, "error": "unsupported", "workflow_id": workflow_id}
+ employee_changed_now(workflow_id)
+ return await _answer(database, auth_service, workflow_id)
+
+
from services.employees.hire import handle_hire_employee # noqa: E402
from services.employees.start import handle_start_employee # noqa: E402
@@ -255,6 +369,8 @@ WS_HANDLERS: Dict[str, Any] = {
"start_employee": handle_start_employee,
"enable_employee_talk": handle_enable_employee_talk,
"apply_employee_changes": handle_apply_employee_changes,
+ "rename_employee": handle_rename_employee,
+ "set_employee_photo": handle_set_employee_photo,
}
@@ -265,4 +381,6 @@ __all__ = [
"handle_get_employee",
"handle_get_employee_usage",
"handle_list_employees",
+ "handle_rename_employee",
+ "handle_set_employee_photo",
]
diff --git a/server/services/employees/prompt.py b/server/services/employees/prompt.py
index 2c46a51e..2f530f25 100644
--- a/server/services/employees/prompt.py
+++ b/server/services/employees/prompt.py
@@ -113,6 +113,16 @@ def _block(text: str) -> str:
return neutralize_templates(str(text).strip())
+def renamed_instructions(system_message: str, old_name: str, new_name: str) -> Optional[str]:
+ """Instructions a hire wrote, with the employee's new name in their
+ opening ("You are <name>, ..."). None when they no longer open that way
+ (the owner rewrote them in Dev mode): those are left as they are."""
+ opening = f"You are {_clean(old_name)}, "
+ if not old_name.strip() or not system_message.startswith(opening):
+ return None
+ return f"You are {_clean(new_name)}, " + system_message[len(opening):]
+
+
def _owner_words(inputs: PromptInputs, owner: str) -> List[str]:
"""Who they are, the job, the routine, the owner's settings and profile."""
request = inputs.request
diff --git a/server/services/employees/store.py b/server/services/employees/store.py
index 82f7b1dd..60d696b0 100644
--- a/server/services/employees/store.py
+++ b/server/services/employees/store.py
@@ -165,6 +165,20 @@ async def update_employee(database: Any, workflow_id: str, fields: Dict[str, Any
return row
+async def set_photo(database: Any, workflow_id: str, path: Optional[str]) -> Optional[Employee]:
+ """Set or clear the photo an employee shows (a workspace path). None when
+ the workflow has no employee row (one built in the editor)."""
+ async with database.get_session() as session:
+ result = await session.execute(select(Employee).where(Employee.workflow_id == workflow_id))
+ row = result.scalar_one_or_none()
+ if row is None:
+ return None
+ row.photo_path = path
+ row.updated_at = _utcnow()
+ await session.commit()
+ return row
+
+
async def delete_for_workflow(database: Any, workflow_id: str) -> int:
"""Remove the employee row of a deleted workflow. Returns rows removed."""
async with database.get_session() as session:
@@ -183,5 +197,6 @@ __all__ = [
"mark_ready",
"merge_node_roles",
"reserve",
+ "set_photo",
"update_employee",
]
diff --git a/server/services/employees/summaries.py b/server/services/employees/summaries.py
index c6bc9f45..e528d84d 100644
--- a/server/services/employees/summaries.py
+++ b/server/services/employees/summaries.py
@@ -55,6 +55,18 @@ PAUSED_STATES = frozenset({"pausing", "paused"})
_WEEKDAYS = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
+def _photo_url(workflow_id: str, employee: Any) -> Optional[str]:
+ """Where the employee's photo is served (the workspace file route),
+ versioned so a new photo replaces the old one in every cache."""
+ path = getattr(employee, "photo_path", None)
+ if not path:
+ return None
+ from services.media.workspace import workspace_file_url
+
+ url = workspace_file_url(workflow_id, path)
+ return f"{url}?v={_millis(getattr(employee, 'updated_at', None))}" if url else None
+
+
def _millis(*moments: Optional[datetime]) -> int:
latest = 0
for moment in moments:
@@ -276,6 +288,8 @@ async def _summary(
return {
"workflow_id": workflow.id,
"name": workflow.name,
+ #: The photo the owner gave them; null shows their initial.
+ "photo_url": _photo_url(workflow.id, employee),
"role": (getattr(employee, "role", "") or _derived_role(graph)),
"color_role": getattr(employee, "color_role", None) or "agent",
"derived": employee is None,
diff --git a/server/services/media/limits.py b/server/services/media/limits.py
index 4dfdc130..d6d0599b 100644
--- a/server/services/media/limits.py
+++ b/server/services/media/limits.py
@@ -30,6 +30,10 @@ TEMPORAL_PAYLOAD_ERROR_BYTES = 2_097_152
# reference ever enters a payload.
MEDIA_MAX_UPLOAD_BYTES = 25 * 1024 * 1024
+# Largest photo an employee may show. Every avatar of theirs (the team
+# list, the chat header, beside each reply) loads this one file.
+EMPLOYEE_PHOTO_MAX_BYTES = 5 * 1024 * 1024
+
# Largest file a node will pull back off disk into memory to hand to a
# provider. Bounds one activity's peak RSS; the bytes are discarded as
# soon as the HTTP call returns.
diff --git a/server/services/workflow_storage/handlers.py b/server/services/workflow_storage/handlers.py
index ca20a8fa..b9da02aa 100644
--- a/server/services/workflow_storage/handlers.py
+++ b/server/services/workflow_storage/handlers.py
@@ -9,7 +9,7 @@ auto-save chain IS the rename path — no separate rename endpoint.
from __future__ import annotations
from pathlib import Path
-from typing import Any, Dict
+from typing import Any, Dict, Optional
from fastapi import WebSocket
@@ -169,6 +169,27 @@ async def _broadcast_renamed(workflow_id: str, name: str, slug: str, old_slug: s
await _broadcast_lifecycle("renamed", workflow_id, name=name, slug=slug, old_slug=old_slug)
+async def rename_saved_workflow(database: Any, workflow_id: str, name: str) -> Optional[Dict[str, Any]]:
+ """Rename a saved workflow without touching its graph, the way a save
+ with a new name does: a new slug, the workspace folder moved to match,
+ and ``workflow.renamed`` to every client. None when it does not exist or
+ the rename was not saved."""
+ from services.workflow_naming import next_available_slug
+
+ existing = await database.get_workflow(workflow_id)
+ if existing is None:
+ return None
+ if existing.name == name:
+ return {"workflow_id": workflow_id, "name": name, "slug": existing.slug}
+ slug = await next_available_slug(name, database, exclude_id=workflow_id)
+ if not await database.rename_workflow(workflow_id, name, slug):
+ return None
+ if existing.slug and existing.slug != slug:
+ _move_workspace(existing.slug, slug)
+ await _broadcast_renamed(workflow_id, name, slug, existing.slug or slug)
+ return {"workflow_id": workflow_id, "name": name, "slug": slug}
+
+
async def _failed_workflow_save(database: Any, workflow_id: str, *, require_existing: bool) -> Dict[str, Any]:
"""Report a vanished workflow separately from a storage failure."""
missing = require_existing and await database.get_workflow(workflow_id) is None
diff --git a/server/tests/services/employees/test_handlers.py b/server/tests/services/employees/test_handlers.py
index f5b72981..5691f082 100644
--- a/server/tests/services/employees/test_handlers.py
+++ b/server/tests/services/employees/test_handlers.py
@@ -36,7 +36,7 @@ def container(monkeypatch, real_database):
def test_handlers_are_registered_and_not_internal():
registered = get_ws_handlers()
- for name in ("list_employees", "get_employee", "get_employee_usage"):
+ for name in ("list_employees", "get_employee", "get_employee_usage", "rename_employee", "set_employee_photo"):
assert name in registered
assert name not in INTERNAL_SOCKET_HANDLERS
diff --git a/server/tests/services/employees/test_identity.py b/server/tests/services/employees/test_identity.py
new file mode 100644
index 00000000..8dce66fc
--- /dev/null
+++ b/server/tests/services/employees/test_identity.py
@@ -0,0 +1,167 @@
+"""Who an employee is (services/employees/handlers.py): renaming renames
+their workflow and the opening of the instructions a hire wrote, and their
+photo is an image the owner uploaded, served by the workspace file route."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from models.employees import Employee
+from services.employees import handlers
+
+HIRED = "You are Maya, front desk for Sam. You are an AI employee inside OpenCompany: you do real work with the owner's apps."
+AGENT = "1:aiAgent:1"
+
+
+def setup(monkeypatch, real_database, tmp_path):
+ class Auth:
+ async def has_valid_key(self, key):
+ return False
+
+ async def get_oauth_tokens(self, provider):
+ return None
+
+ async def list_api_key_providers(self):
+ return []
+
+ import core.container as container_module
+ import services.plugin.deps as deps
+
+ monkeypatch.setattr(container_module, "container", SimpleNamespace(database=lambda: real_database, auth_service=lambda: Auth()))
+ monkeypatch.setattr(deps, "get_auth_service", lambda: Auth())
+
+ frames = []
+
+ class Broadcaster:
+ async def broadcast(self, message):
+ frames.append(message)
+
+ async def broadcast_node_parameters_updated(self, node_id, **kwargs):
+ frames.append({"type": "node_parameters_updated", "node_id": node_id, **kwargs})
+
+ async def broadcast_workflow_lifecycle(self, stage, **data):
+ frames.append({"type": "workflow_lifecycle", "stage": stage, **data})
+
+ monkeypatch.setattr("services.status_broadcaster.get_status_broadcaster", lambda: Broadcaster())
+ moves = []
+ monkeypatch.setattr("services.workflow_storage.handlers._move_workspace", lambda old, new: moves.append((old, new)))
+ changed = []
+ monkeypatch.setattr(handlers, "employee_changed_now", changed.append)
+
+ root = tmp_path / "workspace"
+ (root / "uploads").mkdir(parents=True)
+
+ async def workspace_root(workflow_id, database, *, allow_default=True):
+ return root
+
+ monkeypatch.setattr("services.workspace_locator.resolve_workspace_root", workspace_root)
+ return SimpleNamespace(database=real_database, frames=frames, moves=moves, changed=changed, root=root)
+
+
+async def hire(database, *, system_message=HIRED, employee=True):
+ graph = {"nodes": [{"id": AGENT, "type": "aiAgent", "data": {"label": "Maya"}}], "edges": []}
+ assert await database.save_workflow(workflow_id="1", name="Maya", slug="Maya_1", data=graph)
+ if employee:
+ async with database.get_session() as session:
+ session.add(Employee(id="e1", workflow_id="1", owner_id="owner", hire_state="ready"))
+ await session.commit()
+ await database.save_node_parameters(AGENT, {"provider": "openai", "system_message": system_message})
+
+
+def types(frames):
+ return [frame["type"] for frame in frames]
+
+
+# ----- the name -----
+
+
+async def test_renaming_renames_the_workflow_and_the_instructions(setup):
+ await hire(setup.database)
+ answer = await handlers.handle_rename_employee({"workflow_id": "1", "name": " Ana Lopez "}, None)
+ assert answer["success"] is True and answer["employee"]["name"] == "Ana Lopez"
+ workflow = await setup.database.get_workflow("1")
+ assert workflow.name == "Ana Lopez" and workflow.slug != "Maya_1"
+ assert setup.moves == [("Maya_1", workflow.slug)]
+ params = await setup.database.get_node_parameters(AGENT)
+ assert params["system_message"].startswith("You are Ana Lopez, front desk for Sam. You are an AI employee")
+ assert params["provider"] == "openai"
+ assert types(setup.frames) == ["workflow_lifecycle", "node_parameters_updated"]
+ renamed = setup.frames[0]
+ assert (renamed["stage"], renamed["name"], renamed["old_slug"]) == ("renamed", "Ana Lopez", "Maya_1")
+
+
+async def test_instructions_the_owner_rewrote_keep_their_words(setup):
+ await hire(setup.database, system_message="Be brief and kind.")
+ assert (await handlers.handle_rename_employee({"workflow_id": "1", "name": "Ana"}, None))["success"] is True
+ assert (await setup.database.get_node_parameters(AGENT))["system_message"] == "Be brief and kind."
+ assert types(setup.frames) == ["workflow_lifecycle"]
+
+
+async def test_the_same_name_changes_nothing(setup):
+ await hire(setup.database)
+ assert (await handlers.handle_rename_employee({"workflow_id": "1", "name": "Maya"}, None))["success"] is True
+ assert setup.frames == [] and setup.moves == []
+
+
+async def test_a_rename_that_cannot_be_made(setup):
+ await hire(setup.database)
+ assert await handlers.handle_rename_employee({"workflow_id": "1", "name": " "}, None) == {"success": False, "error": "invalid_request"}
+ assert await handlers.handle_rename_employee({"name": "Ana"}, None) == {"success": False, "error": "invalid_request"}
+ missing = await handlers.handle_rename_employee({"workflow_id": "9", "name": "Ana"}, None)
+ assert (missing["success"], missing["error"]) == (False, "not_found")
+ # Cut to the hire's own limit.
+ long = await handlers.handle_rename_employee({"workflow_id": "1", "name": "A" * 60}, None)
+ assert long["employee"]["name"] == "A" * 40
+
+
+# ----- the photo -----
+
+
+def upload(root, name, data=b"\x89PNG" + b"0" * 60):
+ (root / "uploads" / name).write_bytes(data)
+ return f"uploads/{name}"
+
+
+async def test_the_photo_is_an_image_the_owner_uploaded(setup):
+ await hire(setup.database)
+ path = upload(setup.root, "me.png")
+ answer = await handlers.handle_set_employee_photo({"workflow_id": "1", "path": path}, None)
+ assert answer["success"] is True
+ assert answer["employee"]["photo_url"].startswith("/api/workspace/1/files/uploads/me.png?v=")
+ assert setup.changed == ["1"]
+ cleared = await handlers.handle_set_employee_photo({"workflow_id": "1", "path": None}, None)
+ assert cleared["success"] is True and cleared["employee"]["photo_url"] is None
+
+
+ "name, data",
+ [
+ ("drawing.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>"),
+ ("notes.txt", b"hello"),
+ ],
+)
+async def test_only_a_raster_image_can_be_a_photo(setup, name, data):
+ await hire(setup.database)
+ answer = await handlers.handle_set_employee_photo({"workflow_id": "1", "path": upload(setup.root, name, data)}, None)
+ assert (answer["success"], answer["error"]) == (False, "invalid_photo")
+
+
+async def test_what_else_cannot_be_a_photo(setup, monkeypatch):
+ await hire(setup.database)
+ for path in ("uploads/missing.png", "elsewhere/me.png", "../me.png"):
+ answer = await handlers.handle_set_employee_photo({"workflow_id": "1", "path": path}, None)
+ assert (answer["success"], answer["error"]) == (False, "invalid_photo"), path
+ monkeypatch.setattr(handlers, "EMPLOYEE_PHOTO_MAX_BYTES", 10)
+ big = await handlers.handle_set_employee_photo({"workflow_id": "1", "path": upload(setup.root, "big.png")}, None)
+ assert (big["error"], big["detail"]) == ("invalid_photo", "A photo is at most 0 MB.")
+ assert (await handlers.handle_set_employee_photo({"workflow_id": "1", "path": 5}, None))["error"] == "invalid_request"
+ assert setup.changed == []
+
+
+async def test_a_workflow_built_in_the_editor_keeps_its_initial(setup):
+ await hire(setup.database, employee=False)
+ answer = await handlers.handle_set_employee_photo({"workflow_id": "1", "path": upload(setup.root, "me.png")}, None)
+ assert (answer["success"], answer["error"]) == (False, "unsupported")