diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index 48e19b2cd95..82bb69adc23 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -193,6 +193,10 @@ the latest agent that assigned it to them. If no assignment is available, it use the latest other commenter, or leaves the recipient empty. A manual recipient choice stays selected while task data refreshes. +The composer assignee picker shows up to five recent choices for the company, +most recent first. Remaining agents appear before the remaining people. Use +**No assignee** at the end of the list or find it with search. + Task reply and new-task composers submit with Enter by default; Shift+Enter adds a new line. Settings → Experimental → **Command/Ctrl+Enter to Submit** restores the previous behavior, where Enter adds a new line and Command/Ctrl+Enter diff --git a/tests/e2e/new-task-picker-touch.spec.ts b/tests/e2e/new-task-picker-touch.spec.ts index adc604a106c..a60fde358b9 100644 --- a/tests/e2e/new-task-picker-touch.spec.ts +++ b/tests/e2e/new-task-picker-touch.spec.ts @@ -124,9 +124,11 @@ test("new-task assignee, model, and project sheets scroll by touch and retain th const modelTrigger = page.getByRole("button", { name: "Select model and effort", exact: true }); await assigneeTrigger.tap(); const assigneePicker = page.getByRole("dialog", { name: "Select assignee", exact: true }); - const lastAssignee = await swipeToLastOption(page, assigneePicker); - await expect(lastAssignee).toContainText("Touch Agent 22"); - await lastAssignee.tap(); + const assigneeList = assigneePicker.getByRole("listbox", { name: "Assignees" }); + const targetAssignee = assigneeList.getByRole("option", { name: /Touch Agent 22/ }); + await expect(assigneeList.getByRole("option").last()).toHaveText("No assignee"); + await swipeToLastOption(page, assigneePicker, assigneeList, targetAssignee); + await targetAssignee.tap(); await expect(assigneePicker).toBeHidden(); await expect(assigneeTrigger).toBeFocused(); await modelTrigger.tap(); diff --git a/ui/src/components/NewIssueDialog.tsx b/ui/src/components/NewIssueDialog.tsx index 542f9ba5bbc..0009ce301ff 100644 --- a/ui/src/components/NewIssueDialog.tsx +++ b/ui/src/components/NewIssueDialog.tsx @@ -25,7 +25,7 @@ import { import { useProjectOrder } from "../hooks/useProjectOrder"; import { useStreamlinedUiEnabled } from "../hooks/useStreamlinedUiEnabled"; import { useCoordinatorWorkspaceEnabled } from "../hooks/useCoordinatorWorkspaceEnabled"; -import { getRecentAssigneeIds, getRecentAssigneeSelectionIds, sortAgentsByRecency, trackRecentAssignee, trackRecentAssigneeUser } from "../lib/recent-assignees"; +import { getCompanyRecentAssigneeSelectionIds, trackRecentAssignee, trackRecentAssigneeUser } from "../lib/recent-assignees"; import { getLastProjectId, getRecentProjectIds, trackRecentProject } from "../lib/recent-projects"; import { recordRecentTask } from "../lib/recent-tasks"; import { buildExecutionPolicy } from "../lib/issue-execution-policy"; @@ -1352,19 +1352,18 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) const selectedReusableWorktree = selectableReusableWorkspaces.find((workspace) => workspace.id === selectedExecutionWorkspaceId); const worktreeSelectionIncomplete = canChooseWorktrees && executionWorkspaceMode === "reuse_existing" && (worktreesLoading || worktreesError || !selectedReusableWorktree); - const recentAssigneeIds = useMemo(() => getRecentAssigneeIds(), [newIssueOpen]); const recentProjectIds = useMemo(() => getRecentProjectIds(), [newIssueOpen]); const assigneeOptions = useMemo( () => [ ...currentUserAssigneeOption(currentUserId), ...buildCompanyUserInlineOptions(companyMembers?.users, { excludeUserIds: [currentUserId] }), - ...sortAgentsByRecency((agents ?? []).filter(isAgentTaskTarget), recentAssigneeIds).map((agent) => ({ + ...(agents ?? []).filter(isAgentTaskTarget).sort((a, b) => a.name.localeCompare(b.name)).map((agent) => ({ id: assigneeValueFromSelection({ assigneeAgentId: agent.id }), label: agent.name, searchText: `${agent.name} ${agent.role} ${agent.title ?? ""}`, })), ], - [agents, companyMembers?.users, currentUserId, recentAssigneeIds], + [agents, companyMembers?.users, currentUserId], ); // Resolve once after the directory loads, without resetting text typed while // the queries were in flight or replacing an explicit/restored assignee. @@ -1373,12 +1372,7 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) || !agents || !sessionFetched || !membersFetched || primaryAgent?.loading) return; defaultAssigneePendingRef.current = false; const available = new Set(assigneeOptions.map((option) => option.id)); - const scopedRecents = getRecentAssigneeSelectionIds(effectiveCompanyId); - // Older history has no company key. Agent IDs identify their company; - // human IDs can belong to several companies and cannot be migrated safely. - const recents = scopedRecents.length ? scopedRecents - : getRecentAssigneeSelectionIds().filter((value) => value.startsWith("agent:")); - const recent = recents.find((value) => available.has(value)); + const recent = getCompanyRecentAssigneeSelectionIds(effectiveCompanyId).find((value) => available.has(value)); const targets = agents.filter(isAgentTaskTarget); const fallback = targets.find((agent) => agent.id === primaryAgent?.primaryAgentId) ?? targets.find((agent) => agent.role === "ceo") ?? targets[0]; @@ -1556,9 +1550,6 @@ function AccountNewIssueDialog({ ignoreDefaults }: { ignoreDefaults: boolean }) onPendingAssigneeChange={(value) => { if (value === null) return; defaultAssigneePendingRef.current = false; - const next = parseAssigneeValue(value); - if (next.assigneeAgentId) trackRecentAssignee(next.assigneeAgentId, effectiveCompanyId ?? undefined); - if (next.assigneeUserId) trackRecentAssigneeUser(next.assigneeUserId, effectiveCompanyId ?? undefined); setAssigneeValue(value); setComposerSettings(null); setAssigneeModelLane("primary"); diff --git a/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx b/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx index 2ffa0c54ad2..7a30b0a4ba7 100644 --- a/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx +++ b/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx @@ -1,4 +1,4 @@ -import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode, type Ref } from "react"; +import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode, type Ref } from "react"; import { useQuery } from "@tanstack/react-query"; import { ArrowLeft, Check, ChevronDown, Plus, RotateCcw, Search, X, Zap } from "lucide-react"; import { aiRuntimeConnectionBindingSchema, agentHarnessType, type Agent, type IssueAssigneeAdapterOverrides } from "@paperclipai/shared"; @@ -10,6 +10,8 @@ import { ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS, nativeTaskModelCatalogOpti import { cn } from "@/lib/utils"; import { useMobileEntityPickerViewportStyle } from "@/hooks/useMobileEntityPickerViewportStyle"; import { getLastComposerEffort, rememberComposerEffort } from "@/lib/recent-composer-effort"; +import { getCompanyRecentAssigneeSelectionIds, trackRecentAssigneeSelection } from "@/lib/recent-assignees"; +import { orderItemsBySelectedAndRecent } from "@/lib/recent-selections"; import type { InlineEntityOption } from "@/components/InlineEntitySelector"; import { Dialog, DialogClose, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; @@ -54,6 +56,9 @@ const HARNESS_LABELS: Record = { hermes_gateway: "Hermes Gateway", }; +const NO_ASSIGNEE_OPTION: InlineEntityOption = { id: "", label: "No assignee", searchText: "Unassigned" }; +const RECENT_ASSIGNEE_LIMIT = 5; + function harnessLabel(agent: Agent | undefined): string { if (!agent) return "Choose an agent"; const harness = HARNESS_LABELS[agentHarnessType(agent.adapterType, agent.adapterConfig)] ?? agent.adapterType; @@ -165,11 +170,29 @@ export function ComposerRunSettingsPicker({ } }, [companyId, agentId, model, modelSupported, settings, base.model, base.effort, base.fast, effortChoicesKey, onSettingsChange]); const changed = Boolean(selected.model || selected.effort || selected.fast); - const assigneeOptions = [{ id: "", label: "No assignee", searchText: "Unassigned" }, ...options.filter((item) => item.id !== "")]; - const filteredAgents = assigneeOptions.filter((item) => { + const assigneeOptions = useMemo(() => { + if (!open || view !== "agents") return []; + const agentOptions: InlineEntityOption[] = []; + const peopleOptions: InlineEntityOption[] = []; + const available = new Set(); + for (const item of options) { + const { id } = item; + if (!id) continue; + available.add(id); + if (id.startsWith("agent:")) agentOptions.push(item); + else peopleOptions.push(item); + } + const recentIds = [...new Set(getCompanyRecentAssigneeSelectionIds(companyId))] + .filter((id) => available.has(id)); + return orderItemsBySelectedAndRecent( + [...agentOptions, ...peopleOptions, NO_ASSIGNEE_OPTION], null, recentIds, RECENT_ASSIGNEE_LIMIT, + ); + }, [open, view, options, companyId]); + const assigneeQuery = assigneeSearch.trim().toLowerCase(); + const filteredAssignees = !assigneeQuery ? assigneeOptions : assigneeOptions.filter((item) => { const optionAgent = agents.get(item.id.startsWith("agent:") ? item.id.slice(6) : ""); return `${item.label} ${item.searchText ?? ""} ${optionAgent?.role ?? ""} ${harnessLabel(optionAgent)}` - .toLowerCase().includes(assigneeSearch.trim().toLowerCase()); + .toLowerCase().includes(assigneeQuery); }); const query = modelSearch.trim(); const filteredModels = models.filter((item) => @@ -190,6 +213,7 @@ export function ComposerRunSettingsPicker({ }, [agentId]); const chooseAssignee = (value: string) => { + if (value) trackRecentAssigneeSelection(value, companyId); if (value !== assigneeValue) { onAssigneeChange(value); onSettingsChange(null); @@ -223,7 +247,7 @@ export function ComposerRunSettingsPicker({ onClick={() => { setView("agents"); setHighlightedAssignee(0); }} className="flex h-8 min-w-0 max-w-full items-center gap-1.5 rounded-full px-2.5 hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"> {renderAssigneeIdentity?.(assigneeValue, agent?.name ?? "Unassigned", "trigger")} - {assigneeOptions.find((item) => item.id === assigneeValue)?.label ?? "Unassigned"} + {assigneeValue ? options.find((item) => item.id === assigneeValue)?.label ?? "Unassigned" : NO_ASSIGNEE_OPTION.label} {!modelSupported ? : null} : null} {modelSupported ? <> @@ -264,13 +288,13 @@ export function ComposerRunSettingsPicker({ : view === "agents" ?
Choose assignee{closeButton}
{ setAssigneeSearch(event.target.value); setHighlightedAssignee(0); }} onKeyDown={(event) => { - if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); setHighlightedAssignee((current) => filteredAgents.length ? (current + (event.key === "ArrowDown" ? 1 : -1) + filteredAgents.length) % filteredAgents.length : 0); } - if (event.key === "Enter" && filteredAgents.length) { event.preventDefault(); chooseAssignee(filteredAgents[Math.min(highlightedAssignee, filteredAgents.length - 1)]!.id); } + if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); setHighlightedAssignee((current) => filteredAssignees.length ? (current + (event.key === "ArrowDown" ? 1 : -1) + filteredAssignees.length) % filteredAssignees.length : 0); } + if (event.key === "Enter" && filteredAssignees.length) { event.preventDefault(); chooseAssignee(filteredAssignees[Math.min(highlightedAssignee, filteredAssignees.length - 1)]!.id); } }} className="h-9 w-full rounded-md border border-border bg-background pl-8 pr-2 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring" />
-
{filteredAgents.map((item, index) => { +
{filteredAssignees.map((item, index) => { const optionAgent = agents.get(item.id.startsWith("agent:") ? item.id.slice(6) : ""); return ; - })}{!filteredAgents.length ?

No matches.

: null}
+ })}{!filteredAssignees.length ?

No matches.

: null}
:
Choose model{harnessLabel(agent)}{closeButton}
setModelSearch(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter" && manualValid && !exactMatch) chooseModel(query); }} className="h-9 w-full rounded-md border border-border bg-background pl-8 pr-2 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring" />
diff --git a/ui/src/components/task-chat/TaskChatComposer.test.tsx b/ui/src/components/task-chat/TaskChatComposer.test.tsx index af2f5b2adc2..4655a6294c4 100644 --- a/ui/src/components/task-chat/TaskChatComposer.test.tsx +++ b/ui/src/components/task-chat/TaskChatComposer.test.tsx @@ -20,6 +20,7 @@ import { instanceSettingsApi } from "@/api/instanceSettings"; import { CoordinatorPresentation } from "@/components/coordinator/CoordinatorPresentation"; import { ThemeProvider } from "@/context/ThemeContext"; import { DRAFT_DEBOUNCE_MS } from "../../lib/composer-draft"; +import { getRecentAssigneeSelectionIds, trackRecentAssignee, trackRecentAssigneeUser } from "../../lib/recent-assignees"; import { loadDraftAttachments, loadDraftSubmission, @@ -2506,6 +2507,97 @@ describe("TaskChatComposer", () => { expect(trigger().textContent).toContain("Me"); }); + it.each(["reply", "creation"])("keeps recent assignees first on a large roster in %s mode", async (mode) => { + vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} }); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const companyId = "company-1"; + trackRecentAssigneeUser("older", companyId); + trackRecentAssignee("alpha", companyId); + trackRecentAssigneeUser("sam", companyId); + trackRecentAssignee("beta", companyId); + trackRecentAssignee("gamma", companyId); + trackRecentAssigneeUser("me", companyId); + trackRecentAssignee("removed", companyId); + trackRecentAssigneeUser("lee", "company-2"); + + const otherAgents = Array.from({ length: 200 }, (_, index) => ({ id: `agent:team-${index}`, label: `Team agent ${index}` })); + const otherPeople = Array.from({ length: 60 }, (_, index) => ({ id: `user:team-${index}`, label: `Team member ${index}` })); + const roster = [ + { id: "user:me", label: "Me" }, + { id: "user:lee", label: "Lee" }, + { id: "user:older", label: "Pat" }, + { id: "user:sam", label: "Sam" }, + { id: "agent:alpha", label: "Alpha" }, + { id: "agent:beta", label: "Beta" }, + { id: "agent:delta", label: "Delta" }, + { id: "agent:gamma", label: "Gamma" }, + ...otherPeople, + ...otherAgents, + ]; + const readBudget = 20 * roster.length; + let idReads = 0; + const options = roster.map(({ id, label }) => ({ + label, + get id() { + if (++idReads > readBudget) throw new Error("Assignee picker exceeded its linear roster read budget"); + return id; + }, + })); + const creation = mode === "creation" ? { + value: "", onChange: vi.fn(), onSubmit: vi.fn(), submitLabel: "Create task", + onSelectFiles: vi.fn(), runSettings: null, onRunSettingsChange: vi.fn(), + } : undefined; + const modelAgents = new Map(); + function Composer() { + const [assignee, setAssignee] = useState("agent:delta"); + return setAssignee(value ?? "") : undefined} />; + } + try { + render(); + const trigger = container.querySelector('[aria-label="Select assignee"]')!; + const rows = () => Array.from(document.querySelectorAll('[aria-label="Assignees"] [role="option"]')); + const order = () => rows().map((row) => row.querySelector("[data-assignee-identity]")?.dataset.assigneeIdentity ?? row.textContent); + + idReads = 0; + await act(async () => trigger.click()); + expect(order()).toEqual([ + "user:me", "agent:gamma", "agent:beta", "user:sam", "agent:alpha", "agent:delta", + ...otherAgents.map(({ id }) => id), "user:lee", "user:older", ...otherPeople.map(({ id }) => id), "No assignee", + ]); + + idReads = 0; + const current = rows().find((row) => row.getAttribute("aria-selected") === "true")!; + await act(async () => current.click()); + expect(getRecentAssigneeSelectionIds(companyId)[0]).toBe("agent:delta"); + if (creation) expect(creation.onRunSettingsChange).not.toHaveBeenCalled(); + + idReads = 0; + await act(async () => trigger.click()); + expect(order()[0]).toBe("agent:delta"); + + idReads = 0; + const search = document.querySelector('[aria-label="Search assignees"]')!; + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(search, "Lee"); + search.dispatchEvent(new Event("input", { bubbles: true })); + }); + expect(order()).toEqual(["user:lee"]); + + idReads = 0; + await act(async () => rows()[0]!.click()); + expect(getRecentAssigneeSelectionIds(companyId)[0]).toBe("user:lee"); + idReads = 0; + await act(async () => trigger.click()); + expect(order().slice(0, 6)).toEqual(["user:lee", "agent:delta", "user:me", "agent:gamma", "agent:beta", "agent:alpha"]); + } finally { + render(<>); + client.clear(); + vi.unstubAllGlobals(); + } + }); + it("shows human avatars in assignee options and after selection", async () => { renderComposer({ onAdd: vi.fn(), diff --git a/ui/src/components/task-chat/TaskChatComposer.tsx b/ui/src/components/task-chat/TaskChatComposer.tsx index da16718ccdf..f6a5ac69700 100644 --- a/ui/src/components/task-chat/TaskChatComposer.tsx +++ b/ui/src/components/task-chat/TaskChatComposer.tsx @@ -66,7 +66,7 @@ import { type MarkdownEditorRef, } from "@/components/MarkdownEditor"; import { nextWorkMode } from "@/lib/work-mode-meta"; -import { trackRecentAssignee, trackRecentAssigneeUser } from "@/lib/recent-assignees"; +import { trackRecentAssigneeSelection } from "@/lib/recent-assignees"; import { InlineEntitySelector, type InlineEntityOption, @@ -663,11 +663,6 @@ export function TaskChatComposer({ }; function updatePendingAssignee(value: string | null) { - if (!creation && value && companyId) { - const selection = parseAssigneeValue(value); - if (selection?.assigneeAgentId) trackRecentAssignee(selection.assigneeAgentId, companyId); - if (selection?.assigneeUserId) trackRecentAssigneeUser(selection.assigneeUserId, companyId); - } setPendingAssignee(value); onPendingAssigneeChange?.(value); } @@ -1666,7 +1661,10 @@ export function TaskChatComposer({ noneLabel="No assignee" searchPlaceholder="Search assignees…" emptyMessage="No matches." - onChange={updatePendingAssignee} + onChange={(value) => { + if (value && companyId) trackRecentAssigneeSelection(value, companyId); + updatePendingAssignee(value); + }} disabled={disabled} triggerTestId="task-chat-composer-assignee" className="h-8 gap-1.5 border-0 bg-transparent px-2.5 text-xs shadow-none hover:bg-accent focus-visible:bg-accent focus-visible:ring-0" diff --git a/ui/src/lib/recent-assignees.ts b/ui/src/lib/recent-assignees.ts index d8a57a07c62..9a476256216 100644 --- a/ui/src/lib/recent-assignees.ts +++ b/ui/src/lib/recent-assignees.ts @@ -1,3 +1,4 @@ +import { parseAssigneeValue } from "./assignees"; import { RECENT_SELECTION_DISPLAY_LIMIT, readRecentSelectionIds, @@ -33,6 +34,14 @@ export function getRecentAssigneeSelectionIds(companyId?: string): string[] { }); } +export function getCompanyRecentAssigneeSelectionIds(companyId: string): string[] { + const scopedRecents = getRecentAssigneeSelectionIds(companyId); + // Older history has no company key. Agent IDs identify their company; + // human IDs can belong to several companies and cannot be migrated safely. + return scopedRecents.length ? scopedRecents + : getRecentAssigneeSelectionIds().filter((value) => value.startsWith("agent:")); +} + export function trackRecentAssignee(agentId: string, companyId?: string): void { trackRecentSelectionId(STORAGE_KEY, agentSelectionId(agentId)); if (companyId) trackRecentSelectionId(`${STORAGE_KEY}:${companyId}`, agentSelectionId(agentId)); @@ -43,6 +52,12 @@ export function trackRecentAssigneeUser(userId: string, companyId?: string): voi if (companyId) trackRecentSelectionId(`${STORAGE_KEY}:${companyId}`, userSelectionId(userId)); } +export function trackRecentAssigneeSelection(value: string, companyId: string): void { + const { assigneeAgentId, assigneeUserId } = parseAssigneeValue(value); + if (assigneeAgentId) trackRecentAssignee(assigneeAgentId, companyId); + if (assigneeUserId) trackRecentAssigneeUser(assigneeUserId, companyId); +} + export function sortAgentsByRecency( agents: T[], recentIds: string[], diff --git a/ui/src/lib/recent-selections.ts b/ui/src/lib/recent-selections.ts index 3ca845ad65f..d28047f785a 100644 --- a/ui/src/lib/recent-selections.ts +++ b/ui/src/lib/recent-selections.ts @@ -14,10 +14,16 @@ export function readRecentSelectionIds(storageKey: string): string[] { export function trackRecentSelectionId(storageKey: string, id: string): void { if (!id) return; - const recent = readRecentSelectionIds(storageKey).filter((candidate) => candidate !== id); + const previous = readRecentSelectionIds(storageKey); + if (previous[0] === id) return; + const recent = previous.filter((candidate) => candidate !== id); recent.unshift(id); if (recent.length > MAX_STORED_RECENT_SELECTIONS) recent.length = MAX_STORED_RECENT_SELECTIONS; - localStorage.setItem(storageKey, JSON.stringify(recent)); + try { + localStorage.setItem(storageKey, JSON.stringify(recent)); + } catch { + return; + } } export function orderItemsBySelectedAndRecent(