源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s
This commit is contained in:
commit
2ed3415fb7
8018 files changed
+1936476
No files matched your search
+188
@@ -0,0 +1,188 @@
|
||||
import { type PointerEvent, useRef, useState } from "react";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
Input,
|
||||
Spinner,
|
||||
Textarea
|
||||
} from "@tutti-os/ui-system";
|
||||
import type { AgentHostQuickPrompt } from "../../../../host/agentHostApi";
|
||||
import type {
|
||||
AgentQuickPromptDraft,
|
||||
AgentQuickPromptLibraryController
|
||||
} from "./useAgentQuickPromptLibrary";
|
||||
|
||||
const MAX_TITLE_CODE_POINTS = 80;
|
||||
const MAX_CONTENT_BYTES = 32 * 1024;
|
||||
|
||||
export function AgentQuickPromptEditorDialog({
|
||||
controller
|
||||
}: {
|
||||
controller: AgentQuickPromptLibraryController;
|
||||
}): React.JSX.Element {
|
||||
const { labels } = controller;
|
||||
const source = controller.mode === "edit" ? controller.selectedPrompt : null;
|
||||
const [draft, setDraft] = useState<AgentQuickPromptDraft>(
|
||||
() => controller.initialDraft ?? promptDraft(source)
|
||||
);
|
||||
const [validationError, setValidationError] = useState<string | null>(null);
|
||||
const cancelRequestedOnPointerDownRef = useRef(false);
|
||||
|
||||
const submit = async (): Promise<void> => {
|
||||
const error = validateDraft(draft, labels);
|
||||
if (error) {
|
||||
setValidationError(error);
|
||||
return;
|
||||
}
|
||||
setValidationError(null);
|
||||
await controller.saveDraft({
|
||||
title: draft.title.trim(),
|
||||
content: draft.content
|
||||
});
|
||||
};
|
||||
const mutationError =
|
||||
controller.mutationError === "conflict"
|
||||
? labels.conflict
|
||||
: controller.mutationError === "generic"
|
||||
? labels.mutationError
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={controller.isEditorOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !controller.isSaving) {
|
||||
controller.closeDialog();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
className="sm:max-w-[560px]"
|
||||
showCloseButton={false}
|
||||
onKeyDownCapture={(event) => {
|
||||
// The dialog is portalled but still participates in the Composer's
|
||||
// React event tree. Keep Enter inside the form so a keyboard save
|
||||
// cannot reach the Composer submit shortcut after the dialog closes.
|
||||
if (event.key === "Enter") event.stopPropagation();
|
||||
}}
|
||||
onEscapeKeyDown={(event) => {
|
||||
if (controller.isSaving) event.preventDefault();
|
||||
}}
|
||||
onInteractOutside={(event) => {
|
||||
if (controller.isSaving) event.preventDefault();
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{source ? labels.editTitle : labels.createTitle}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="sr-only">
|
||||
{labels.contentPlaceholder}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form
|
||||
className="flex min-h-0 flex-col gap-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void submit();
|
||||
}}
|
||||
>
|
||||
<label className="flex flex-col gap-1.5 text-[13px] text-[var(--text-secondary)]">
|
||||
<span>{labels.titleLabel}</span>
|
||||
<Input
|
||||
autoFocus
|
||||
aria-invalid={Boolean(validationError)}
|
||||
disabled={controller.isSaving}
|
||||
maxLength={MAX_TITLE_CODE_POINTS * 2}
|
||||
placeholder={labels.titlePlaceholder}
|
||||
value={draft.title}
|
||||
onChange={(event) =>
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
title: event.target.value
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex min-h-0 flex-col gap-1.5 text-[13px] text-[var(--text-secondary)]">
|
||||
<span>{labels.contentLabel}</span>
|
||||
<Textarea
|
||||
aria-invalid={Boolean(validationError)}
|
||||
className="min-h-[128px] resize-y"
|
||||
disabled={controller.isSaving}
|
||||
placeholder={labels.contentPlaceholder}
|
||||
value={draft.content}
|
||||
onChange={(event) =>
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
content: event.target.value
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{validationError || mutationError ? (
|
||||
<p className="text-[12px] text-[var(--state-danger)]" role="alert">
|
||||
{validationError ?? mutationError}
|
||||
</p>
|
||||
) : null}
|
||||
<DialogFooter>
|
||||
<Button
|
||||
disabled={controller.isSaving}
|
||||
size="dialog"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onPointerDown={(event: PointerEvent<HTMLButtonElement>) => {
|
||||
if (event.button !== 0) return;
|
||||
cancelRequestedOnPointerDownRef.current = true;
|
||||
event.preventDefault();
|
||||
controller.closeDialog();
|
||||
}}
|
||||
onClick={() => {
|
||||
if (cancelRequestedOnPointerDownRef.current) {
|
||||
cancelRequestedOnPointerDownRef.current = false;
|
||||
return;
|
||||
}
|
||||
controller.closeDialog();
|
||||
}}
|
||||
>
|
||||
{labels.cancel}
|
||||
</Button>
|
||||
<Button disabled={controller.isSaving} size="dialog" type="submit">
|
||||
{controller.isSaving ? <Spinner size={14} /> : null}
|
||||
{controller.isSaving ? labels.saving : labels.save}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function promptDraft(
|
||||
source: AgentHostQuickPrompt | null
|
||||
): AgentQuickPromptDraft {
|
||||
return source
|
||||
? { title: source.title, content: source.content }
|
||||
: { title: "", content: "" };
|
||||
}
|
||||
|
||||
function validateDraft(
|
||||
draft: AgentQuickPromptDraft,
|
||||
labels: AgentQuickPromptLibraryController["labels"]
|
||||
): string | null {
|
||||
if (!draft.title.trim() || !draft.content.trim()) {
|
||||
return labels.required;
|
||||
}
|
||||
if (Array.from(draft.title.trim()).length > MAX_TITLE_CODE_POINTS) {
|
||||
return labels.titleTooLong;
|
||||
}
|
||||
if (new TextEncoder().encode(draft.content).byteLength > MAX_CONTENT_BYTES) {
|
||||
return labels.contentTooLarge;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { TooltipProvider } from "@tutti-os/ui-system";
|
||||
import type { AgentQuickPromptLabels } from "./agentQuickPromptLabels";
|
||||
import { AgentQuickPromptList } from "./AgentQuickPromptList";
|
||||
import type { AgentQuickPromptLibraryController } from "./useAgentQuickPromptLibrary";
|
||||
|
||||
vi.mock("@tutti-os/ui-system", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@tutti-os/ui-system")>();
|
||||
return {
|
||||
...actual,
|
||||
Sortable: ({
|
||||
children,
|
||||
onMove
|
||||
}: {
|
||||
children: ReactNode;
|
||||
onMove?: (event: { activeIndex: number; overIndex: number }) => void;
|
||||
}) => (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onMove?.({ activeIndex: 1, overIndex: 0 })}
|
||||
>
|
||||
Move second before first
|
||||
</button>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
SortableContent: ({ children }: { children: ReactNode }) => (
|
||||
<div>{children}</div>
|
||||
),
|
||||
SortableItem: ({ children }: { children: ReactNode }) => (
|
||||
<div>{children}</div>
|
||||
),
|
||||
SortableItemHandle: ({ children }: { children: ReactNode }) => children
|
||||
};
|
||||
});
|
||||
|
||||
const prompts = [
|
||||
{
|
||||
id: "prompt-1",
|
||||
title: "Review",
|
||||
content: "Review the change",
|
||||
version: 1,
|
||||
createdAtUnixMs: 1,
|
||||
updatedAtUnixMs: 1
|
||||
},
|
||||
{
|
||||
id: "prompt-2",
|
||||
title: "Plan",
|
||||
content: "Plan the change",
|
||||
version: 1,
|
||||
createdAtUnixMs: 2,
|
||||
updatedAtUnixMs: 2
|
||||
}
|
||||
];
|
||||
|
||||
const labels = new Proxy(
|
||||
{
|
||||
delete: "Delete",
|
||||
dragCancel: (title: string) => `Canceled ${title}`,
|
||||
dragDrop: (title: string) => `Dropped ${title}`,
|
||||
dragHandle: (title: string) => `Reorder ${title}`,
|
||||
dragInstructions: "Use the keyboard to move",
|
||||
dragMove: (title: string) => `Moving ${title}`,
|
||||
dragStart: (title: string) => `Picked up ${title}`,
|
||||
edit: "Edit"
|
||||
},
|
||||
{
|
||||
get: (target, property) => Reflect.get(target, property) ?? String(property)
|
||||
}
|
||||
) as unknown as AgentQuickPromptLabels;
|
||||
|
||||
describe("AgentQuickPromptList", () => {
|
||||
it("restores the moved handle focus after a failed reorder", async () => {
|
||||
vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
|
||||
callback(0);
|
||||
return 1;
|
||||
});
|
||||
const reorderPrompts = vi.fn(async () => false);
|
||||
const controller = {
|
||||
canReorder: true,
|
||||
filteredPrompts: prompts,
|
||||
isInteractionLocked: false,
|
||||
labels,
|
||||
reorderPrompts,
|
||||
showReorderHandles: true,
|
||||
snapshot: {
|
||||
enabled: true,
|
||||
error: null,
|
||||
pendingMutationIds: [],
|
||||
prompts,
|
||||
revision: 1,
|
||||
status: "ready"
|
||||
}
|
||||
} as unknown as AgentQuickPromptLibraryController;
|
||||
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptList
|
||||
controller={controller}
|
||||
isSorting
|
||||
rowRefs={{ current: new Map() }}
|
||||
onDelete={vi.fn()}
|
||||
onEdit={vi.fn()}
|
||||
onFocusRow={vi.fn()}
|
||||
onSelect={vi.fn()}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
fireEvent.click(
|
||||
screen.getByRole("button", { name: "Move second before first" })
|
||||
);
|
||||
|
||||
expect(reorderPrompts).toHaveBeenCalledWith("prompt-2", "prompt-1");
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "Reorder Plan" })).toHaveFocus()
|
||||
);
|
||||
});
|
||||
});
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
import { useMemo, useRef } from "react";
|
||||
import { Sortable, SortableContent, SortableItem } from "@tutti-os/ui-system";
|
||||
import type { AgentHostQuickPrompt } from "../../../../host/agentHostApi";
|
||||
import { AgentQuickPromptRow } from "./AgentQuickPromptRow";
|
||||
import type { AgentQuickPromptLibraryController } from "./useAgentQuickPromptLibrary";
|
||||
|
||||
export function AgentQuickPromptList({
|
||||
controller,
|
||||
isSorting,
|
||||
onDelete,
|
||||
onEdit,
|
||||
onFocusRow,
|
||||
onSelect,
|
||||
rowRefs
|
||||
}: {
|
||||
controller: AgentQuickPromptLibraryController;
|
||||
isSorting: boolean;
|
||||
onDelete: (prompt: AgentHostQuickPrompt) => void;
|
||||
onEdit: (prompt: AgentHostQuickPrompt) => void;
|
||||
onFocusRow: (index: number) => void;
|
||||
onSelect: (prompt: AgentHostQuickPrompt) => void;
|
||||
rowRefs: React.MutableRefObject<Map<string, HTMLButtonElement>>;
|
||||
}): React.JSX.Element {
|
||||
const handleRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
const { filteredPrompts, labels, snapshot } = controller;
|
||||
const promptsById = useMemo(
|
||||
() => new Map(filteredPrompts.map((prompt) => [prompt.id, prompt])),
|
||||
[filteredPrompts]
|
||||
);
|
||||
const accessibility = useMemo(
|
||||
() => ({
|
||||
announcements: {
|
||||
onDragStart({ active }: { active: { id: string | number } }) {
|
||||
const index = filteredPrompts.findIndex(
|
||||
(prompt) => prompt.id === active.id
|
||||
);
|
||||
return labels.dragStart(
|
||||
promptsById.get(String(active.id))?.title ?? String(active.id),
|
||||
index + 1,
|
||||
filteredPrompts.length
|
||||
);
|
||||
},
|
||||
onDragMove({ active, over }: DragAnnouncementInput) {
|
||||
const index = over
|
||||
? filteredPrompts.findIndex((prompt) => prompt.id === over.id)
|
||||
: filteredPrompts.findIndex((prompt) => prompt.id === active.id);
|
||||
return labels.dragMove(
|
||||
promptsById.get(String(active.id))?.title ?? String(active.id),
|
||||
index + 1,
|
||||
filteredPrompts.length
|
||||
);
|
||||
},
|
||||
onDragOver({ active, over }: DragAnnouncementInput) {
|
||||
const index = over
|
||||
? filteredPrompts.findIndex((prompt) => prompt.id === over.id)
|
||||
: filteredPrompts.findIndex((prompt) => prompt.id === active.id);
|
||||
return labels.dragMove(
|
||||
promptsById.get(String(active.id))?.title ?? String(active.id),
|
||||
index + 1,
|
||||
filteredPrompts.length
|
||||
);
|
||||
},
|
||||
onDragEnd({ active, over }: DragAnnouncementInput) {
|
||||
if (!over) {
|
||||
return labels.dragCancel(
|
||||
promptsById.get(String(active.id))?.title ?? String(active.id),
|
||||
filteredPrompts.findIndex((prompt) => prompt.id === active.id) +
|
||||
1,
|
||||
filteredPrompts.length
|
||||
);
|
||||
}
|
||||
const index = filteredPrompts.findIndex(
|
||||
(prompt) => prompt.id === over.id
|
||||
);
|
||||
return labels.dragDrop(
|
||||
promptsById.get(String(active.id))?.title ?? String(active.id),
|
||||
index + 1,
|
||||
filteredPrompts.length
|
||||
);
|
||||
},
|
||||
onDragCancel({ active }: DragAnnouncementInput) {
|
||||
const index = filteredPrompts.findIndex(
|
||||
(prompt) => prompt.id === active.id
|
||||
);
|
||||
return labels.dragCancel(
|
||||
promptsById.get(String(active.id))?.title ?? String(active.id),
|
||||
index + 1,
|
||||
filteredPrompts.length
|
||||
);
|
||||
}
|
||||
},
|
||||
screenReaderInstructions: { draggable: labels.dragInstructions }
|
||||
}),
|
||||
[filteredPrompts, labels, promptsById]
|
||||
);
|
||||
|
||||
return (
|
||||
<Sortable
|
||||
accessibility={accessibility}
|
||||
value={[...filteredPrompts]}
|
||||
getItemValue={(prompt) => prompt.id}
|
||||
onMove={({ activeIndex, overIndex }) => {
|
||||
const next = [...filteredPrompts];
|
||||
const [moving] = next.splice(activeIndex, 1);
|
||||
if (!moving) return;
|
||||
next.splice(overIndex, 0, moving);
|
||||
const beforePromptId = next[overIndex + 1]?.id ?? null;
|
||||
void controller.reorderPrompts(moving.id, beforePromptId).then(() => {
|
||||
window.requestAnimationFrame(() =>
|
||||
handleRefs.current.get(moving.id)?.focus()
|
||||
);
|
||||
});
|
||||
}}
|
||||
>
|
||||
<SortableContent className="flex flex-col gap-0.5">
|
||||
{filteredPrompts.map((prompt, index) => (
|
||||
<SortableItem key={prompt.id} value={prompt.id}>
|
||||
<AgentQuickPromptRow
|
||||
handleRef={(node) => {
|
||||
if (node) handleRefs.current.set(prompt.id, node);
|
||||
else handleRefs.current.delete(prompt.id);
|
||||
}}
|
||||
labels={labels}
|
||||
isSorting={isSorting}
|
||||
pending={
|
||||
controller.isInteractionLocked ||
|
||||
snapshot.pendingMutationIds.includes(prompt.id)
|
||||
}
|
||||
prompt={prompt}
|
||||
reorderDisabled={!controller.canReorder}
|
||||
selectionRef={(node) => {
|
||||
if (node) rowRefs.current.set(prompt.id, node);
|
||||
else rowRefs.current.delete(prompt.id);
|
||||
}}
|
||||
showReorderHandle={isSorting && controller.showReorderHandles}
|
||||
onDelete={() => onDelete(prompt)}
|
||||
onEdit={() => onEdit(prompt)}
|
||||
onFocusNext={(offset) =>
|
||||
onFocusRow(
|
||||
(index + offset + filteredPrompts.length) %
|
||||
filteredPrompts.length
|
||||
)
|
||||
}
|
||||
onSelect={() => onSelect(prompt)}
|
||||
/>
|
||||
</SortableItem>
|
||||
))}
|
||||
</SortableContent>
|
||||
</Sortable>
|
||||
);
|
||||
}
|
||||
|
||||
type DragAnnouncementInput = {
|
||||
active: { id: string | number };
|
||||
over: { id: string | number } | null;
|
||||
};
|
||||
+762
@@ -0,0 +1,762 @@
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { TooltipProvider } from "@tutti-os/ui-system";
|
||||
import type { AgentQuickPromptLabels } from "./agentQuickPromptLabels";
|
||||
import { AgentQuickPromptPopover } from "./AgentQuickPromptPopover";
|
||||
import type { AgentQuickPromptLibraryController } from "./useAgentQuickPromptLibrary";
|
||||
|
||||
const labels = new Proxy(
|
||||
{
|
||||
deleteDescription: (title: string) => `Delete ${title}`,
|
||||
dragCancel: (title: string) => `Canceled ${title}`,
|
||||
dragDrop: (title: string) => `Dropped ${title}`,
|
||||
dragHandle: (title: string) => `Reorder ${title}`,
|
||||
dragMove: (title: string) => `Moving ${title}`,
|
||||
dragStart: (title: string) => `Picked up ${title}`,
|
||||
title: "Quick prompts",
|
||||
trigger: "Prompts",
|
||||
triggerTooltip: "Choose a quick prompt",
|
||||
searchPlaceholder: "Search quick prompts",
|
||||
startSorting: "Reorder",
|
||||
finishSorting: "Done",
|
||||
insertionError:
|
||||
"Could not insert into the Composer. Try again from the quick prompt list.",
|
||||
reorderDisabledMinimum:
|
||||
"At least two quick prompts are required to adjust their order",
|
||||
reorderDisabledPending:
|
||||
"Wait for the current quick prompt change to finish",
|
||||
reorderDisabledSearch: "Clear the search to adjust prompt order",
|
||||
reorderDisabledUnsupported: "This host does not support prompt reordering",
|
||||
add: "New prompt",
|
||||
createFromTemplate: "Recommended templates",
|
||||
moreActions: "More prompt actions",
|
||||
edit: "Edit",
|
||||
delete: "Delete",
|
||||
empty: "No quick prompts yet",
|
||||
loadError: "Quick prompts could not be loaded",
|
||||
loading: "Loading quick prompts…",
|
||||
noResults: "No matching quick prompts",
|
||||
recommendedTemplatesTitle: "Recommended templates",
|
||||
recommendedTemplatesDescription:
|
||||
"Choose one to prefill the editor. Saving adds it as a quick prompt and inserts it into the Composer.",
|
||||
returnToPrompts: "My prompts",
|
||||
useTemplate: "Use template",
|
||||
recommendedTemplates: [
|
||||
{
|
||||
id: "summary-common-prompts",
|
||||
title: "Summarize common prompts",
|
||||
description: "Find insights and repeated work patterns",
|
||||
content: "Summarize my common prompts"
|
||||
},
|
||||
{
|
||||
id: "understand-context",
|
||||
title: "Understand the situation",
|
||||
description: "Summarize context, constraints, risks, and next steps",
|
||||
content: "Summarize the situation"
|
||||
},
|
||||
{
|
||||
id: "create-action-plan",
|
||||
title: "Create an action plan",
|
||||
description: "Break a goal into prioritized, verifiable steps",
|
||||
content: "Create an action plan"
|
||||
},
|
||||
{
|
||||
id: "review-and-improve",
|
||||
title: "Review and improve",
|
||||
description: "Find gaps, risks, and practical improvements",
|
||||
content: "Review and improve"
|
||||
},
|
||||
{
|
||||
id: "draft-clear-update",
|
||||
title: "Draft a clear update",
|
||||
description: "Write a concise explanation for the intended audience",
|
||||
content: "Draft an update"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
get: (target, property) => Reflect.get(target, property) ?? String(property)
|
||||
}
|
||||
) as unknown as AgentQuickPromptLabels;
|
||||
|
||||
function controller(
|
||||
patch: Partial<AgentQuickPromptLibraryController> = {}
|
||||
): AgentQuickPromptLibraryController {
|
||||
const prompt = {
|
||||
id: "prompt-1",
|
||||
title: "Review",
|
||||
content: "Review the current change",
|
||||
version: 1,
|
||||
createdAtUnixMs: 1,
|
||||
updatedAtUnixMs: 2
|
||||
};
|
||||
return {
|
||||
capabilityAvailable: true,
|
||||
canReorder: false,
|
||||
close: vi.fn(),
|
||||
closeDialog: vi.fn(),
|
||||
deletePrompt: vi.fn(),
|
||||
filteredPrompts: [prompt],
|
||||
isDeleting: false,
|
||||
isEditorOpen: false,
|
||||
isPopoverOpen: true,
|
||||
isSaving: false,
|
||||
isInteractionLocked: false,
|
||||
isReordering: false,
|
||||
initialDraft: null,
|
||||
insertionError: false,
|
||||
labels,
|
||||
mode: "popover",
|
||||
mutationError: null,
|
||||
openCreate: vi.fn(),
|
||||
openEdit: vi.fn(),
|
||||
openPopover: vi.fn(),
|
||||
promptToDelete: null,
|
||||
retry: vi.fn(),
|
||||
reorderCapabilityAvailable: true,
|
||||
reorderError: null,
|
||||
reorderPrompts: vi.fn(async () => true),
|
||||
saveDraft: vi.fn(async () => true),
|
||||
searchQuery: "",
|
||||
showReorderHandles: false,
|
||||
selectPrompt: vi.fn(),
|
||||
selectedPrompt: null,
|
||||
setPopoverOpen: vi.fn(),
|
||||
setSearchQuery: vi.fn(),
|
||||
snapshot: {
|
||||
enabled: true,
|
||||
status: "ready",
|
||||
prompts: [prompt],
|
||||
error: null,
|
||||
revision: 1,
|
||||
pendingMutationIds: []
|
||||
},
|
||||
submitDelete: vi.fn(async () => true),
|
||||
...patch
|
||||
};
|
||||
}
|
||||
|
||||
describe("AgentQuickPromptPopover", () => {
|
||||
it("uses the shared composer trigger color and icon sizing", () => {
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={controller()} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
const trigger = screen.getByRole("button", {
|
||||
name: "Choose a quick prompt"
|
||||
});
|
||||
expect(trigger).toHaveClass("agent-gui-node__composer-menu-trigger");
|
||||
expect(trigger).toHaveClass("focus-visible:!outline-2");
|
||||
expect(trigger.querySelector("svg")).toHaveClass("size-4");
|
||||
});
|
||||
|
||||
it("keeps selection and direct icon management controls as sibling buttons", () => {
|
||||
const subject = controller();
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={subject} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
const selection = screen.getByRole("button", { name: /^Review/u });
|
||||
expect(selection.querySelector("button")).toBeNull();
|
||||
const edit = screen.getByRole("button", { name: "Edit" });
|
||||
const remove = screen.getByRole("button", { name: "Delete" });
|
||||
expect(edit).toBeInTheDocument();
|
||||
expect(remove).toBeInTheDocument();
|
||||
fireEvent.pointerDown(edit, { button: 0 });
|
||||
expect(subject.openEdit).toHaveBeenCalledOnce();
|
||||
fireEvent.pointerDown(remove, { button: 0 });
|
||||
expect(subject.deletePrompt).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("shows reorder handles only in explicit sorting mode", () => {
|
||||
const first = controller().filteredPrompts[0]!;
|
||||
const second = {
|
||||
...first,
|
||||
id: "prompt-2",
|
||||
title: "Plan",
|
||||
content: "Plan the current change"
|
||||
};
|
||||
const subject = controller({
|
||||
canReorder: true,
|
||||
filteredPrompts: [first, second],
|
||||
showReorderHandles: true,
|
||||
snapshot: {
|
||||
enabled: true,
|
||||
status: "ready",
|
||||
prompts: [first, second],
|
||||
error: null,
|
||||
revision: 1,
|
||||
pendingMutationIds: []
|
||||
}
|
||||
});
|
||||
const rendered = render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={subject} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
expect(screen.queryByRole("button", { name: "Reorder Review" })).toBeNull();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reorder" }));
|
||||
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Reorder Review" })
|
||||
).toBeEnabled();
|
||||
expect(screen.queryByPlaceholderText("Search quick prompts")).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: "Edit" })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: "Delete" })).toBeNull();
|
||||
expect(
|
||||
screen.queryByRole("button", {
|
||||
name: /Summarize common prompts.*Use template/u
|
||||
})
|
||||
).toBeNull();
|
||||
expect(
|
||||
screen.queryByRole("button", {
|
||||
name: "Recommended templates"
|
||||
})
|
||||
).toBeNull();
|
||||
|
||||
rendered.rerender(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover
|
||||
controller={controller({
|
||||
canReorder: false,
|
||||
filteredPrompts: [first, second],
|
||||
isInteractionLocked: true,
|
||||
showReorderHandles: true,
|
||||
snapshot: {
|
||||
enabled: true,
|
||||
status: "ready",
|
||||
prompts: [first, second],
|
||||
error: null,
|
||||
revision: 2,
|
||||
orderMutationPending: true,
|
||||
pendingMutationIds: [first.id]
|
||||
}
|
||||
})}
|
||||
disabled={false}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Reorder Review" })
|
||||
).toBeDisabled();
|
||||
expect(screen.queryByRole("button", { name: /^Review/u })).toBeNull();
|
||||
expect(screen.getByText("Review")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Done" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("enters and finishes sorting on primary pointer down and keyboard click", () => {
|
||||
const first = controller().filteredPrompts[0]!;
|
||||
const second = { ...first, id: "prompt-2", title: "Plan" };
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover
|
||||
controller={controller({
|
||||
canReorder: true,
|
||||
filteredPrompts: [first, second],
|
||||
showReorderHandles: true,
|
||||
snapshot: {
|
||||
enabled: true,
|
||||
status: "ready",
|
||||
prompts: [first, second],
|
||||
error: null,
|
||||
revision: 1,
|
||||
pendingMutationIds: []
|
||||
}
|
||||
})}
|
||||
disabled={false}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
const sort = screen.getByRole("button", { name: "Reorder" });
|
||||
fireEvent.pointerDown(sort, { button: 0 });
|
||||
expect(screen.getByRole("button", { name: "Done" })).toBeInTheDocument();
|
||||
|
||||
const done = screen.getByRole("button", { name: "Done" });
|
||||
fireEvent.pointerDown(done, { button: 0 });
|
||||
expect(screen.getByRole("button", { name: "Reorder" })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByPlaceholderText("Search quick prompts")
|
||||
).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reorder" }));
|
||||
expect(screen.getByRole("button", { name: "Done" })).toBeInTheDocument();
|
||||
expect(screen.queryByPlaceholderText("Search quick prompts")).toBeNull();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Done" }));
|
||||
expect(screen.getByRole("button", { name: "Reorder" })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByPlaceholderText("Search quick prompts")
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("reports a Composer insertion failure without reporting a save failure", () => {
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover
|
||||
controller={controller({ insertionError: true })}
|
||||
disabled={false}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(
|
||||
"Could not insert into the Composer. Try again from the quick prompt list."
|
||||
);
|
||||
});
|
||||
|
||||
it("returns to the prompt list when insertion fails from the template view", () => {
|
||||
const rendered = render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={controller()} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
fireEvent.click(
|
||||
screen.getByRole("button", { name: "Recommended templates" })
|
||||
);
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Recommended templates", level: 2 })
|
||||
).toBeInTheDocument();
|
||||
|
||||
rendered.rerender(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover
|
||||
controller={controller({ insertionError: true })}
|
||||
disabled={false}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Quick prompts", level: 2 })
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(
|
||||
"Could not insert into the Composer. Try again from the quick prompt list."
|
||||
);
|
||||
expect(
|
||||
screen.getByRole("button", { name: /^Review/u })
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("explains why reordering is unavailable with stable reason priority", () => {
|
||||
const first = controller().filteredPrompts[0]!;
|
||||
const second = { ...first, id: "prompt-2", title: "Plan" };
|
||||
const rendered = render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={controller()} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getByLabelText(
|
||||
"At least two quick prompts are required to adjust their order"
|
||||
)
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Reorder" })).toBeDisabled();
|
||||
|
||||
rendered.rerender(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover
|
||||
controller={controller({
|
||||
filteredPrompts: [first, second],
|
||||
reorderCapabilityAvailable: false,
|
||||
showReorderHandles: false,
|
||||
snapshot: {
|
||||
enabled: true,
|
||||
status: "ready",
|
||||
prompts: [first, second],
|
||||
error: null,
|
||||
revision: 1,
|
||||
pendingMutationIds: []
|
||||
}
|
||||
})}
|
||||
disabled={false}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
expect(
|
||||
screen.getByLabelText("This host does not support prompt reordering")
|
||||
).toBeInTheDocument();
|
||||
|
||||
rendered.rerender(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover
|
||||
controller={controller({
|
||||
filteredPrompts: [],
|
||||
snapshot: {
|
||||
enabled: true,
|
||||
status: "loading",
|
||||
prompts: [],
|
||||
error: null,
|
||||
revision: 1,
|
||||
pendingMutationIds: []
|
||||
}
|
||||
})}
|
||||
disabled={false}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
expect(screen.getByLabelText(labels.loading)).toBeInTheDocument();
|
||||
|
||||
rendered.rerender(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover
|
||||
controller={controller({
|
||||
filteredPrompts: [],
|
||||
snapshot: {
|
||||
enabled: true,
|
||||
status: "error",
|
||||
prompts: [],
|
||||
error: "offline",
|
||||
revision: 1,
|
||||
pendingMutationIds: []
|
||||
}
|
||||
})}
|
||||
disabled={false}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
expect(screen.getByLabelText(labels.loadError)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("resets sorting mode when the controlled Popover closes externally", () => {
|
||||
const first = controller().filteredPrompts[0]!;
|
||||
const second = { ...first, id: "prompt-2", title: "Plan" };
|
||||
const openController = controller({
|
||||
canReorder: true,
|
||||
filteredPrompts: [first, second],
|
||||
showReorderHandles: true,
|
||||
snapshot: {
|
||||
enabled: true,
|
||||
status: "ready",
|
||||
prompts: [first, second],
|
||||
error: null,
|
||||
revision: 1,
|
||||
pendingMutationIds: []
|
||||
}
|
||||
});
|
||||
const rendered = render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={openController} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reorder" }));
|
||||
expect(screen.getByRole("button", { name: "Done" })).toBeInTheDocument();
|
||||
|
||||
rendered.rerender(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover
|
||||
controller={{ ...openController, isPopoverOpen: false }}
|
||||
disabled={false}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
rendered.rerender(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={openController} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
expect(screen.getByRole("button", { name: "Reorder" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Done" })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: "Reorder Review" })).toBeNull();
|
||||
});
|
||||
|
||||
it("disables recommended-template actions while a shared mutation is pending", () => {
|
||||
const subject = controller({
|
||||
filteredPrompts: [],
|
||||
isInteractionLocked: true,
|
||||
snapshot: {
|
||||
enabled: true,
|
||||
status: "ready",
|
||||
prompts: [],
|
||||
error: null,
|
||||
revision: 1,
|
||||
pendingMutationIds: ["prompt-1"]
|
||||
}
|
||||
});
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={subject} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
const summaryTemplate = screen.getByRole("button", {
|
||||
name: /Summarize common prompts.*Use template/u
|
||||
});
|
||||
const createTemplate = screen.getByRole("button", {
|
||||
name: /Understand the situation.*Use template/u
|
||||
});
|
||||
expect(summaryTemplate).toBeDisabled();
|
||||
expect(createTemplate).toBeDisabled();
|
||||
fireEvent.pointerDown(summaryTemplate, { button: 0 });
|
||||
fireEvent.click(summaryTemplate, { detail: 1 });
|
||||
expect(subject.openCreate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("selects on primary pointer down and still accepts a later keyboard click", () => {
|
||||
const subject = controller();
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={subject} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
const prompt = screen.getByRole("button", { name: /^Review/u });
|
||||
fireEvent.pointerDown(prompt, { button: 0 });
|
||||
expect(subject.selectPrompt).toHaveBeenCalledOnce();
|
||||
fireEvent.click(prompt);
|
||||
expect(subject.selectPrompt).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("keeps touch and pen actions cancellable until click", () => {
|
||||
const subject = controller();
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={subject} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
const prompt = screen.getByRole("button", { name: /^Review/u });
|
||||
fireEvent.pointerDown(prompt, { button: 0, pointerType: "touch" });
|
||||
fireEvent.pointerCancel(prompt, { pointerType: "touch" });
|
||||
expect(subject.selectPrompt).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.pointerDown(prompt, { button: 0, pointerType: "pen" });
|
||||
expect(subject.selectPrompt).not.toHaveBeenCalled();
|
||||
fireEvent.click(prompt, { detail: 1 });
|
||||
expect(subject.selectPrompt).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("keeps the common-prompts recommendation inside the template view", () => {
|
||||
const subject = controller();
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={subject} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.queryByRole("button", {
|
||||
name: /Summarize common prompts.*Use template/u
|
||||
})
|
||||
).toBeNull();
|
||||
fireEvent.pointerDown(
|
||||
screen.getByRole("button", { name: "Recommended templates" }),
|
||||
{ button: 0 }
|
||||
);
|
||||
const summaryTemplate = screen.getByRole("button", {
|
||||
name: /Summarize common prompts.*Use template/u
|
||||
});
|
||||
fireEvent.pointerDown(summaryTemplate, { button: 0 });
|
||||
fireEvent.click(summaryTemplate, { detail: 1 });
|
||||
expect(subject.openCreate).toHaveBeenCalledWith(
|
||||
{
|
||||
title: "Summarize common prompts",
|
||||
content: "Summarize my common prompts"
|
||||
},
|
||||
{
|
||||
insertIntoComposerAfterSave: true,
|
||||
usagePromptType: "recommended_template"
|
||||
}
|
||||
);
|
||||
expect(subject.openCreate).toHaveBeenCalledOnce();
|
||||
expect(subject.saveDraft).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("starts creation on primary pointer down so the Dialog survives Popover dismissal", () => {
|
||||
const subject = controller();
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={subject} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
fireEvent.pointerDown(screen.getByRole("button", { name: "New prompt" }), {
|
||||
button: 0
|
||||
});
|
||||
expect(subject.openCreate).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("prefills the create editor for every recommended template", () => {
|
||||
const subject = controller({
|
||||
filteredPrompts: [],
|
||||
snapshot: {
|
||||
enabled: true,
|
||||
status: "ready",
|
||||
prompts: [],
|
||||
error: null,
|
||||
revision: 1,
|
||||
pendingMutationIds: []
|
||||
}
|
||||
});
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={subject} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
const summaryTemplate = screen.getByRole("button", {
|
||||
name: /Summarize common prompts.*Use template/u
|
||||
});
|
||||
fireEvent.click(summaryTemplate);
|
||||
expect(subject.openCreate).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
{
|
||||
title: "Summarize common prompts",
|
||||
content: "Summarize my common prompts"
|
||||
},
|
||||
{
|
||||
insertIntoComposerAfterSave: true,
|
||||
usagePromptType: "recommended_template"
|
||||
}
|
||||
);
|
||||
|
||||
const createTemplate = screen.getByRole("button", {
|
||||
name: /Understand the situation.*Use template/u
|
||||
});
|
||||
fireEvent.click(createTemplate);
|
||||
expect(subject.openCreate).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
{
|
||||
title: "Understand the situation",
|
||||
content: "Summarize the situation"
|
||||
},
|
||||
{
|
||||
insertIntoComposerAfterSave: true,
|
||||
usagePromptType: "recommended_template"
|
||||
}
|
||||
);
|
||||
expect(subject.openCreate).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("lets a non-empty library reopen recommended templates in the same Popover", () => {
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={controller()} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
fireEvent.pointerDown(
|
||||
screen.getByRole("button", {
|
||||
name: "Recommended templates"
|
||||
}),
|
||||
{ button: 0 }
|
||||
);
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Recommended templates", level: 2 })
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByPlaceholderText("Search quick prompts")).toBeNull();
|
||||
expect(
|
||||
screen.getByRole("button", { name: "My prompts" })
|
||||
).toBeInTheDocument();
|
||||
|
||||
fireEvent.pointerDown(screen.getByRole("button", { name: "My prompts" }), {
|
||||
button: 0
|
||||
});
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Quick prompts", level: 2 })
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByPlaceholderText("Search quick prompts")
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("runs dialog cancellation and deletion on primary pointer down", () => {
|
||||
const createSubject = controller({
|
||||
isEditorOpen: true,
|
||||
isPopoverOpen: false,
|
||||
mode: "create"
|
||||
});
|
||||
const createRender = render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={createSubject} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
fireEvent.pointerDown(screen.getByRole("button", { name: labels.cancel }), {
|
||||
button: 0
|
||||
});
|
||||
expect(createSubject.closeDialog).toHaveBeenCalledOnce();
|
||||
createRender.unmount();
|
||||
|
||||
const deleteSubject = controller({
|
||||
isPopoverOpen: false,
|
||||
mode: "delete",
|
||||
promptToDelete: controller().filteredPrompts[0]!
|
||||
});
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover controller={deleteSubject} disabled={false} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
fireEvent.pointerDown(
|
||||
screen.getByRole("button", { name: labels.deleteConfirm }),
|
||||
{ button: 0 }
|
||||
);
|
||||
expect(deleteSubject.submitDelete).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("preserves an edited draft when a conflict refreshes the same prompt", () => {
|
||||
const prompt = controller().filteredPrompts[0]!;
|
||||
const rendered = render(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover
|
||||
controller={controller({
|
||||
isEditorOpen: true,
|
||||
isPopoverOpen: false,
|
||||
mode: "edit",
|
||||
selectedPrompt: prompt
|
||||
})}
|
||||
disabled={false}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
const content = screen.getByLabelText(labels.contentLabel);
|
||||
fireEvent.change(content, { target: { value: "My unsaved draft" } });
|
||||
|
||||
rendered.rerender(
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover
|
||||
controller={controller({
|
||||
isEditorOpen: true,
|
||||
isPopoverOpen: false,
|
||||
mode: "edit",
|
||||
selectedPrompt: { ...prompt, version: 2, updatedAtUnixMs: 5 }
|
||||
})}
|
||||
disabled={false}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
expect(screen.getByLabelText(labels.contentLabel)).toHaveValue(
|
||||
"My unsaved draft"
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps Enter in the editor Dialog out of the Composer shortcut", () => {
|
||||
const onComposerKeyDown = vi.fn();
|
||||
render(
|
||||
<div onKeyDown={onComposerKeyDown}>
|
||||
<TooltipProvider>
|
||||
<AgentQuickPromptPopover
|
||||
controller={controller({
|
||||
isEditorOpen: true,
|
||||
isPopoverOpen: false,
|
||||
mode: "create"
|
||||
})}
|
||||
disabled={false}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
);
|
||||
|
||||
fireEvent.keyDown(screen.getByLabelText(labels.titleLabel), {
|
||||
key: "Enter"
|
||||
});
|
||||
expect(onComposerKeyDown).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+609
@@ -0,0 +1,609 @@
|
||||
import { useId, useRef, useState } from "react";
|
||||
import {
|
||||
Button,
|
||||
ConfirmationDialog,
|
||||
DialogFooter,
|
||||
Input,
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
ScrollArea,
|
||||
Spinner,
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger
|
||||
} from "@tutti-os/ui-system";
|
||||
import {
|
||||
AddIcon,
|
||||
ArrowLeftIcon,
|
||||
ArrowRightIcon,
|
||||
CheckIcon,
|
||||
GripVerticalIcon,
|
||||
MessageSquareTextIcon,
|
||||
SearchIcon
|
||||
} from "@tutti-os/ui-system/icons";
|
||||
import { cn } from "../../../../app/renderer/lib/utils";
|
||||
import styles from "../../AgentGUINode.styles";
|
||||
import { AgentQuickPromptEditorDialog } from "./AgentQuickPromptEditorDialog";
|
||||
import { AgentQuickPromptList } from "./AgentQuickPromptList";
|
||||
import type { AgentQuickPromptTemplate } from "./agentQuickPromptLabels";
|
||||
import type { AgentQuickPromptLibraryController } from "./useAgentQuickPromptLibrary";
|
||||
import {
|
||||
type PrimaryPointerAction,
|
||||
usePrimaryPointerAction
|
||||
} from "./usePrimaryPointerAction";
|
||||
|
||||
export function AgentQuickPromptPopover({
|
||||
controller,
|
||||
disabled
|
||||
}: {
|
||||
controller: AgentQuickPromptLibraryController;
|
||||
disabled: boolean;
|
||||
}): React.JSX.Element | null {
|
||||
const searchRef = useRef<HTMLInputElement | null>(null);
|
||||
const rowRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
const firstTemplateRef = useRef<HTMLButtonElement | null>(null);
|
||||
const preserveExternalFocusRef = useRef(false);
|
||||
const [view, setView] = useState<"prompts" | "templates">("prompts");
|
||||
let activeView = view;
|
||||
if (controller.insertionError && activeView !== "prompts") {
|
||||
activeView = "prompts";
|
||||
setView("prompts");
|
||||
}
|
||||
const [sortingState, setSortingState] = useState({
|
||||
isPopoverOpen: controller.isPopoverOpen,
|
||||
isSorting: false
|
||||
});
|
||||
let isSorting = sortingState.isSorting;
|
||||
if (sortingState.isPopoverOpen !== controller.isPopoverOpen) {
|
||||
isSorting = false;
|
||||
setSortingState({
|
||||
isPopoverOpen: controller.isPopoverOpen,
|
||||
isSorting: false
|
||||
});
|
||||
}
|
||||
const setIsSorting = (next: boolean): void => {
|
||||
setSortingState({
|
||||
isPopoverOpen: controller.isPopoverOpen,
|
||||
isSorting: next
|
||||
});
|
||||
};
|
||||
const titleId = useId();
|
||||
const { labels, snapshot } = controller;
|
||||
const templateEntryAction = usePrimaryPointerAction(() =>
|
||||
setView("templates")
|
||||
);
|
||||
const returnToPromptsAction = usePrimaryPointerAction(() =>
|
||||
setView("prompts")
|
||||
);
|
||||
const createAction = usePrimaryPointerAction(() => {
|
||||
if (controller.isInteractionLocked) return;
|
||||
preserveExternalFocusRef.current = true;
|
||||
controller.openCreate();
|
||||
});
|
||||
const deleteCancelAction = usePrimaryPointerAction(controller.closeDialog);
|
||||
const deleteConfirmAction = usePrimaryPointerAction(() => {
|
||||
void controller.submitDelete();
|
||||
});
|
||||
const startSortingAction = usePrimaryPointerAction(() => setIsSorting(true));
|
||||
const finishSortingAction = usePrimaryPointerAction(() =>
|
||||
setIsSorting(false)
|
||||
);
|
||||
|
||||
if (!controller.capabilityAvailable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const focusRow = (index: number): void => {
|
||||
const prompt = controller.filteredPrompts[index];
|
||||
if (prompt) rowRefs.current.get(prompt.id)?.focus();
|
||||
};
|
||||
const errorLabel =
|
||||
controller.mutationError === "conflict"
|
||||
? labels.conflict
|
||||
: controller.mutationError === "generic"
|
||||
? labels.mutationError
|
||||
: null;
|
||||
const requestTemplate = (template: AgentQuickPromptTemplate): void => {
|
||||
preserveExternalFocusRef.current = true;
|
||||
controller.openCreate(
|
||||
{ title: template.title, content: template.content },
|
||||
{
|
||||
insertIntoComposerAfterSave: true,
|
||||
usagePromptType: "recommended_template"
|
||||
}
|
||||
);
|
||||
};
|
||||
const isTemplateView = activeView === "templates";
|
||||
const reorderDisabledMessage = resolveReorderDisabledMessage(controller);
|
||||
const startSortingButton = (
|
||||
<Button
|
||||
disabled={reorderDisabledMessage !== null}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
{...startSortingAction}
|
||||
>
|
||||
<GripVerticalIcon data-icon="inline-start" />
|
||||
{labels.startSorting}
|
||||
</Button>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Popover
|
||||
modal={false}
|
||||
open={controller.isPopoverOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setView("prompts");
|
||||
setIsSorting(false);
|
||||
}
|
||||
controller.setPopoverOpen(open);
|
||||
}}
|
||||
>
|
||||
<TooltipProvider delayDuration={120}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span className="inline-flex shrink-0">
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
aria-label={labels.triggerTooltip}
|
||||
className={cn(
|
||||
styles.composerMenuTrigger,
|
||||
"w-auto max-w-[180px] !gap-1.5 focus-visible:!outline-2 focus-visible:!outline-offset-2 focus-visible:!outline-[var(--border-focus)]"
|
||||
)}
|
||||
disabled={disabled}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="chrome"
|
||||
>
|
||||
<MessageSquareTextIcon
|
||||
className="size-4"
|
||||
data-icon="inline-start"
|
||||
/>
|
||||
<span className="hidden min-[900px]:inline">
|
||||
{labels.trigger}
|
||||
</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">{labels.triggerTooltip}</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
<PopoverContent
|
||||
aria-labelledby={titleId}
|
||||
align="start"
|
||||
className="h-[420px] max-h-[var(--radix-popover-content-available-height)] w-[400px] gap-0 overflow-hidden p-0"
|
||||
side="top"
|
||||
sideOffset={8}
|
||||
onOpenAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
window.requestAnimationFrame(() => {
|
||||
if (isTemplateView) {
|
||||
firstTemplateRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
const selectedId = controller.selectedPrompt?.id;
|
||||
const selectedRow = selectedId
|
||||
? rowRefs.current.get(selectedId)
|
||||
: null;
|
||||
(selectedRow ?? searchRef.current)?.focus();
|
||||
});
|
||||
}}
|
||||
onCloseAutoFocus={(event) => {
|
||||
if (preserveExternalFocusRef.current) event.preventDefault();
|
||||
preserveExternalFocusRef.current = false;
|
||||
}}
|
||||
>
|
||||
<div className="flex shrink-0 items-center justify-between gap-2 border-b border-[var(--border-1)] px-3 py-2.5">
|
||||
<h2
|
||||
id={titleId}
|
||||
className="text-[14px] font-medium text-[var(--text-primary)]"
|
||||
>
|
||||
{isTemplateView ? labels.recommendedTemplatesTitle : labels.title}
|
||||
</h2>
|
||||
{isTemplateView ? (
|
||||
<Button
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
{...returnToPromptsAction}
|
||||
>
|
||||
<ArrowLeftIcon data-icon="inline-start" />
|
||||
{labels.returnToPrompts}
|
||||
</Button>
|
||||
) : (
|
||||
<div className="flex items-center gap-1">
|
||||
{isSorting ? (
|
||||
<Button
|
||||
disabled={controller.isInteractionLocked}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
{...finishSortingAction}
|
||||
>
|
||||
<CheckIcon data-icon="inline-start" />
|
||||
{labels.finishSorting}
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
{reorderDisabledMessage ? (
|
||||
<TooltipProvider delayDuration={120}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span
|
||||
aria-label={reorderDisabledMessage}
|
||||
className="inline-flex"
|
||||
tabIndex={0}
|
||||
>
|
||||
{startSortingButton}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">
|
||||
{reorderDisabledMessage}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
) : (
|
||||
startSortingButton
|
||||
)}
|
||||
<Button
|
||||
{...createAction}
|
||||
disabled={controller.isInteractionLocked}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
<AddIcon data-icon="inline-start" />
|
||||
{labels.add}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!isTemplateView && !isSorting ? (
|
||||
<div className="relative shrink-0 px-3 py-2.5">
|
||||
<SearchIcon
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute top-1/2 left-5 size-3.5 -translate-y-1/2 text-[var(--text-tertiary)]"
|
||||
/>
|
||||
<Input
|
||||
ref={searchRef}
|
||||
aria-label={labels.searchPlaceholder}
|
||||
className="pl-8"
|
||||
disabled={controller.isInteractionLocked}
|
||||
placeholder={labels.searchPlaceholder}
|
||||
value={controller.searchQuery}
|
||||
onChange={(event) =>
|
||||
controller.setSearchQuery(event.target.value)
|
||||
}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "ArrowDown") {
|
||||
event.preventDefault();
|
||||
focusRow(0);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{!isTemplateView &&
|
||||
snapshot.status === "error" &&
|
||||
snapshot.prompts.length > 0 ? (
|
||||
<div
|
||||
className="flex shrink-0 items-center justify-between gap-2 px-3 pb-2 text-[12px] text-[var(--state-danger)]"
|
||||
role="alert"
|
||||
>
|
||||
<span>{labels.loadError}</span>
|
||||
<Button
|
||||
size="xs"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={controller.retry}
|
||||
>
|
||||
{labels.retry}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
{!isTemplateView && controller.reorderError ? (
|
||||
<div
|
||||
className="flex shrink-0 items-center justify-between gap-2 px-3 pb-2 text-[12px] text-[var(--state-danger)]"
|
||||
role="alert"
|
||||
>
|
||||
<span>
|
||||
{controller.reorderError === "conflict"
|
||||
? labels.reorderConflict
|
||||
: labels.reorderError}
|
||||
</span>
|
||||
<Button
|
||||
size="xs"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={controller.retry}
|
||||
>
|
||||
{labels.retry}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
{!isTemplateView && controller.insertionError ? (
|
||||
<div
|
||||
className="shrink-0 px-3 pb-2 text-[12px] text-[var(--state-danger)]"
|
||||
role="alert"
|
||||
>
|
||||
{labels.insertionError}
|
||||
</div>
|
||||
) : null}
|
||||
<ScrollArea
|
||||
className="min-h-0 flex-1"
|
||||
viewportClassName={cn("px-2 pb-2", isSorting && "pt-2")}
|
||||
viewportTestId="agent-quick-prompt-scroll-viewport"
|
||||
>
|
||||
{isTemplateView ? (
|
||||
<RecommendedTemplateList
|
||||
disabled={controller.isInteractionLocked}
|
||||
firstTemplateRef={firstTemplateRef}
|
||||
labels={labels}
|
||||
onSelect={requestTemplate}
|
||||
/>
|
||||
) : snapshot.status === "loading" &&
|
||||
snapshot.prompts.length === 0 ? (
|
||||
<PromptState
|
||||
icon={<Spinner size={16} />}
|
||||
label={labels.loading}
|
||||
/>
|
||||
) : snapshot.status === "error" && snapshot.prompts.length === 0 ? (
|
||||
<PromptState
|
||||
label={labels.loadError}
|
||||
action={
|
||||
<Button
|
||||
disabled={controller.isInteractionLocked}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={controller.retry}
|
||||
>
|
||||
{labels.retry}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : snapshot.prompts.length === 0 &&
|
||||
!controller.searchQuery.trim() ? (
|
||||
<RecommendedTemplateList
|
||||
disabled={controller.isInteractionLocked}
|
||||
firstTemplateRef={firstTemplateRef}
|
||||
labels={labels}
|
||||
onSelect={requestTemplate}
|
||||
/>
|
||||
) : controller.filteredPrompts.length === 0 ? (
|
||||
<PromptState label={labels.noResults} />
|
||||
) : (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<AgentQuickPromptList
|
||||
controller={controller}
|
||||
isSorting={isSorting}
|
||||
rowRefs={rowRefs}
|
||||
onFocusRow={focusRow}
|
||||
onDelete={(prompt) => {
|
||||
preserveExternalFocusRef.current = true;
|
||||
controller.deletePrompt(prompt);
|
||||
}}
|
||||
onEdit={(prompt) => {
|
||||
preserveExternalFocusRef.current = true;
|
||||
controller.openEdit(prompt);
|
||||
}}
|
||||
onSelect={(prompt) => {
|
||||
if (isSorting) return;
|
||||
preserveExternalFocusRef.current = true;
|
||||
controller.selectPrompt(prompt);
|
||||
}}
|
||||
/>
|
||||
{!isSorting ? (
|
||||
<TemplateEntry
|
||||
label={labels.createFromTemplate}
|
||||
action={templateEntryAction}
|
||||
disabled={controller.isInteractionLocked}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{controller.isEditorOpen ? (
|
||||
<AgentQuickPromptEditorDialog controller={controller} />
|
||||
) : null}
|
||||
<ConfirmationDialog
|
||||
cancelLabel={labels.cancel}
|
||||
confirmBusy={controller.isDeleting}
|
||||
confirmLabel={
|
||||
controller.isDeleting ? labels.deleting : labels.deleteConfirm
|
||||
}
|
||||
description={
|
||||
controller.promptToDelete
|
||||
? labels.deleteDescription(controller.promptToDelete.title)
|
||||
: undefined
|
||||
}
|
||||
footer={
|
||||
<DialogFooter>
|
||||
<Button
|
||||
{...deleteCancelAction}
|
||||
disabled={controller.isDeleting}
|
||||
size="dialog"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
{labels.cancel}
|
||||
</Button>
|
||||
<Button
|
||||
{...deleteConfirmAction}
|
||||
disabled={controller.isDeleting}
|
||||
size="dialog"
|
||||
type="button"
|
||||
variant="destructive"
|
||||
>
|
||||
{controller.isDeleting ? labels.deleting : labels.deleteConfirm}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !controller.isDeleting) controller.closeDialog();
|
||||
}}
|
||||
open={controller.mode === "delete"}
|
||||
title={labels.deleteTitle}
|
||||
tone="destructive"
|
||||
>
|
||||
{errorLabel ? (
|
||||
<p className="text-[12px] text-[var(--state-danger)]" role="alert">
|
||||
{errorLabel}
|
||||
</p>
|
||||
) : null}
|
||||
</ConfirmationDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function resolveReorderDisabledMessage(
|
||||
controller: AgentQuickPromptLibraryController
|
||||
): string | null {
|
||||
const { labels, snapshot } = controller;
|
||||
if (!controller.reorderCapabilityAvailable) {
|
||||
return labels.reorderDisabledUnsupported;
|
||||
}
|
||||
if (snapshot.status === "idle" || snapshot.status === "loading") {
|
||||
return labels.loading;
|
||||
}
|
||||
if (snapshot.status === "error" && snapshot.prompts.length === 0) {
|
||||
return labels.loadError;
|
||||
}
|
||||
if (controller.isInteractionLocked) {
|
||||
return labels.reorderDisabledPending;
|
||||
}
|
||||
if (controller.searchQuery.trim()) {
|
||||
return labels.reorderDisabledSearch;
|
||||
}
|
||||
if (controller.filteredPrompts.length < 2) {
|
||||
return labels.reorderDisabledMinimum;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function RecommendedTemplateList({
|
||||
disabled,
|
||||
firstTemplateRef,
|
||||
labels,
|
||||
onSelect
|
||||
}: {
|
||||
disabled: boolean;
|
||||
firstTemplateRef: React.RefObject<HTMLButtonElement | null>;
|
||||
labels: AgentQuickPromptLibraryController["labels"];
|
||||
onSelect: (template: AgentQuickPromptTemplate) => void;
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<section className="flex flex-col gap-1 px-1 pt-2">
|
||||
<div className="px-2 pb-1">
|
||||
<h3 className="text-[13px] font-medium text-[var(--text-primary)]">
|
||||
{labels.recommendedTemplatesTitle}
|
||||
</h3>
|
||||
<p className="pt-0.5 text-[12px] leading-[1.35] text-[var(--text-secondary)]">
|
||||
{labels.recommendedTemplatesDescription}
|
||||
</p>
|
||||
</div>
|
||||
{labels.recommendedTemplates.map((template, index) => (
|
||||
<RecommendedTemplateButton
|
||||
key={template.id}
|
||||
disabled={disabled}
|
||||
labels={labels}
|
||||
selectionRef={index === 0 ? firstTemplateRef : undefined}
|
||||
template={template}
|
||||
onSelect={onSelect}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function RecommendedTemplateButton({
|
||||
disabled,
|
||||
labels,
|
||||
onSelect,
|
||||
selectionRef,
|
||||
template
|
||||
}: {
|
||||
disabled: boolean;
|
||||
labels: AgentQuickPromptLibraryController["labels"];
|
||||
onSelect: (template: AgentQuickPromptTemplate) => void;
|
||||
selectionRef?: React.RefObject<HTMLButtonElement | null>;
|
||||
template: AgentQuickPromptTemplate;
|
||||
}): React.JSX.Element {
|
||||
const selectionAction = usePrimaryPointerAction(() => {
|
||||
if (!disabled) onSelect(template);
|
||||
});
|
||||
|
||||
return (
|
||||
<Button
|
||||
{...selectionAction}
|
||||
ref={selectionRef}
|
||||
className="h-auto w-full justify-between px-2 py-2 text-left whitespace-normal"
|
||||
disabled={disabled}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
<span className="flex min-w-0 flex-col items-start gap-0.5">
|
||||
<span className="w-full truncate font-medium text-[var(--text-primary)]">
|
||||
{template.title}
|
||||
</span>
|
||||
<span className="line-clamp-2 w-full text-[12px] leading-[1.35] text-[var(--text-secondary)]">
|
||||
{template.description}
|
||||
</span>
|
||||
</span>
|
||||
<span className="flex shrink-0 items-center gap-1 text-[12px] text-[var(--text-secondary)]">
|
||||
{labels.useTemplate}
|
||||
<ArrowRightIcon data-icon="inline-end" />
|
||||
</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function TemplateEntry({
|
||||
action,
|
||||
disabled,
|
||||
label
|
||||
}: {
|
||||
action: PrimaryPointerAction;
|
||||
disabled: boolean;
|
||||
label: string;
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<Button
|
||||
{...action}
|
||||
className="mt-1 h-auto w-full justify-between px-2 py-2 text-left whitespace-normal"
|
||||
disabled={disabled}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
<span className="font-medium">{label}</span>
|
||||
<ArrowRightIcon data-icon="inline-end" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function PromptState({
|
||||
action,
|
||||
icon,
|
||||
label
|
||||
}: {
|
||||
action?: React.ReactNode;
|
||||
icon?: React.ReactNode;
|
||||
label: string;
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<div className="flex min-h-[180px] flex-col items-center justify-center gap-2 px-4 text-center text-[13px] text-[var(--text-secondary)]">
|
||||
{icon}
|
||||
<span>{label}</span>
|
||||
{action}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
import {
|
||||
BareIconButton,
|
||||
Button,
|
||||
SortableItemHandle,
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger
|
||||
} from "@tutti-os/ui-system";
|
||||
import {
|
||||
DeleteIcon,
|
||||
EditIcon,
|
||||
GripVerticalIcon
|
||||
} from "@tutti-os/ui-system/icons";
|
||||
import type { AgentHostQuickPrompt } from "../../../../host/agentHostApi";
|
||||
import type { AgentQuickPromptLibraryController } from "./useAgentQuickPromptLibrary";
|
||||
import { usePrimaryPointerAction } from "./usePrimaryPointerAction";
|
||||
|
||||
export function AgentQuickPromptRow({
|
||||
handleRef,
|
||||
isSorting,
|
||||
labels,
|
||||
onDelete,
|
||||
onEdit,
|
||||
onFocusNext,
|
||||
onSelect,
|
||||
pending,
|
||||
prompt,
|
||||
reorderDisabled,
|
||||
selectionRef,
|
||||
showReorderHandle
|
||||
}: {
|
||||
handleRef: (node: HTMLButtonElement | null) => void;
|
||||
isSorting: boolean;
|
||||
labels: AgentQuickPromptLibraryController["labels"];
|
||||
onDelete: () => void;
|
||||
onEdit: () => void;
|
||||
onFocusNext: (offset: number) => void;
|
||||
onSelect: () => void;
|
||||
pending: boolean;
|
||||
prompt: AgentHostQuickPrompt;
|
||||
reorderDisabled: boolean;
|
||||
selectionRef: (node: HTMLButtonElement | null) => void;
|
||||
showReorderHandle: boolean;
|
||||
}): React.JSX.Element {
|
||||
const selectionAction = usePrimaryPointerAction(onSelect);
|
||||
const editAction = usePrimaryPointerAction(onEdit);
|
||||
const deleteAction = usePrimaryPointerAction(onDelete);
|
||||
const actionRevealClass =
|
||||
"opacity-100 transition-opacity [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-hover/quick-prompt-row:opacity-100 group-has-[:focus-visible]/quick-prompt-row:opacity-100 focus-visible:opacity-100";
|
||||
const promptContent = (
|
||||
<span className="flex min-w-0 flex-col items-start gap-0.5">
|
||||
<span className="w-full truncate font-medium text-[var(--text-primary)]">
|
||||
{prompt.title}
|
||||
</span>
|
||||
<span className="line-clamp-2 w-full text-[12px] leading-[1.35] text-[var(--text-secondary)]">
|
||||
{prompt.content}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="group/quick-prompt-row flex min-w-0 items-start gap-1 rounded-md hover:bg-[var(--transparency-hover)]">
|
||||
{showReorderHandle ? (
|
||||
<div
|
||||
className={`mt-1.5 flex size-6 shrink-0 items-center justify-center ${reorderDisabled ? "cursor-not-allowed" : ""}`}
|
||||
>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<SortableItemHandle asChild disabled={reorderDisabled}>
|
||||
<BareIconButton
|
||||
ref={handleRef}
|
||||
aria-label={labels.dragHandle(prompt.title)}
|
||||
className="cursor-grab text-[var(--text-tertiary)] hover:text-[var(--text-primary)] focus-visible:text-[var(--text-primary)] disabled:cursor-not-allowed disabled:text-[var(--text-disabled)] disabled:opacity-100"
|
||||
size="md"
|
||||
title=""
|
||||
>
|
||||
<GripVerticalIcon />
|
||||
</BareIconButton>
|
||||
</SortableItemHandle>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">
|
||||
{labels.dragHandle(prompt.title)}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : null}
|
||||
{isSorting ? (
|
||||
<div className="h-auto min-w-0 flex-1 px-1 py-2 text-left whitespace-normal">
|
||||
{promptContent}
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
{...selectionAction}
|
||||
ref={selectionRef}
|
||||
className="h-auto min-w-0 flex-1 justify-start px-1 py-2 text-left whitespace-normal hover:bg-transparent"
|
||||
disabled={pending}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
onFocusNext(event.key === "ArrowDown" ? 1 : -1);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{promptContent}
|
||||
</Button>
|
||||
)}
|
||||
{!isSorting ? (
|
||||
<>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<BareIconButton
|
||||
{...editAction}
|
||||
aria-label={labels.edit}
|
||||
className={`mt-1.5 ${actionRevealClass}`}
|
||||
disabled={pending}
|
||||
size="md"
|
||||
title=""
|
||||
>
|
||||
<EditIcon />
|
||||
</BareIconButton>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">{labels.edit}</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<BareIconButton
|
||||
{...deleteAction}
|
||||
aria-label={labels.delete}
|
||||
className={`mt-1.5 ${actionRevealClass}`}
|
||||
disabled={pending}
|
||||
size="md"
|
||||
title=""
|
||||
>
|
||||
<DeleteIcon />
|
||||
</BareIconButton>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">{labels.delete}</TooltipContent>
|
||||
</Tooltip>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
import type { TranslateFn } from "../../../../i18n";
|
||||
|
||||
export interface AgentQuickPromptTemplate {
|
||||
content: string;
|
||||
description: string;
|
||||
id:
|
||||
| "summary-common-prompts"
|
||||
| "understand-context"
|
||||
| "create-action-plan"
|
||||
| "review-and-improve"
|
||||
| "draft-clear-update";
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface AgentQuickPromptLabels {
|
||||
add: string;
|
||||
cancel: string;
|
||||
conflict: string;
|
||||
contentLabel: string;
|
||||
contentPlaceholder: string;
|
||||
createTitle: string;
|
||||
createFromTemplate: string;
|
||||
delete: string;
|
||||
deleteConfirm: string;
|
||||
deleteDescription: (title: string) => string;
|
||||
deleteTitle: string;
|
||||
deleting: string;
|
||||
dragCancel: (title: string, position: number, total: number) => string;
|
||||
dragDrop: (title: string, position: number, total: number) => string;
|
||||
dragHandle: (title: string) => string;
|
||||
dragInstructions: string;
|
||||
dragMove: (title: string, position: number, total: number) => string;
|
||||
dragStart: (title: string, position: number, total: number) => string;
|
||||
edit: string;
|
||||
editTitle: string;
|
||||
empty: string;
|
||||
finishSorting: string;
|
||||
insertionError: string;
|
||||
loadError: string;
|
||||
loading: string;
|
||||
moreActions: string;
|
||||
mutationError: string;
|
||||
noResults: string;
|
||||
required: string;
|
||||
reorderConflict: string;
|
||||
reorderDisabledMinimum: string;
|
||||
reorderDisabledPending: string;
|
||||
reorderDisabledSearch: string;
|
||||
reorderDisabledUnsupported: string;
|
||||
reorderError: string;
|
||||
retry: string;
|
||||
save: string;
|
||||
saving: string;
|
||||
searchPlaceholder: string;
|
||||
startSorting: string;
|
||||
recommendedTemplates: readonly AgentQuickPromptTemplate[];
|
||||
recommendedTemplatesDescription: string;
|
||||
recommendedTemplatesTitle: string;
|
||||
returnToPrompts: string;
|
||||
title: string;
|
||||
titleLabel: string;
|
||||
titlePlaceholder: string;
|
||||
titleTooLong: string;
|
||||
contentTooLarge: string;
|
||||
trigger: string;
|
||||
triggerTooltip: string;
|
||||
useTemplate: string;
|
||||
}
|
||||
|
||||
export function agentQuickPromptLabels(t: TranslateFn): AgentQuickPromptLabels {
|
||||
return {
|
||||
add: t("agentHost.agentGui.quickPrompts.add"),
|
||||
cancel: t("common.cancel"),
|
||||
conflict: t("agentHost.agentGui.quickPrompts.conflict"),
|
||||
contentLabel: t("agentHost.agentGui.quickPrompts.contentLabel"),
|
||||
contentPlaceholder: t("agentHost.agentGui.quickPrompts.contentPlaceholder"),
|
||||
contentTooLarge: t("agentHost.agentGui.quickPrompts.contentTooLarge"),
|
||||
createTitle: t("agentHost.agentGui.quickPrompts.createTitle"),
|
||||
createFromTemplate: t("agentHost.agentGui.quickPrompts.createFromTemplate"),
|
||||
delete: t("agentHost.agentGui.quickPrompts.delete"),
|
||||
deleteConfirm: t("agentHost.agentGui.quickPrompts.deleteConfirm"),
|
||||
deleteDescription: (title) =>
|
||||
t("agentHost.agentGui.quickPrompts.deleteDescription", { title }),
|
||||
deleteTitle: t("agentHost.agentGui.quickPrompts.deleteTitle"),
|
||||
deleting: t("agentHost.agentGui.quickPrompts.deleting"),
|
||||
dragCancel: (title, position, total) =>
|
||||
t("agentHost.agentGui.quickPrompts.dragCancel", {
|
||||
title,
|
||||
position,
|
||||
total
|
||||
}),
|
||||
dragDrop: (title, position, total) =>
|
||||
t("agentHost.agentGui.quickPrompts.dragDrop", {
|
||||
title,
|
||||
position,
|
||||
total
|
||||
}),
|
||||
dragHandle: (title) =>
|
||||
t("agentHost.agentGui.quickPrompts.dragHandle", { title }),
|
||||
dragInstructions: t("agentHost.agentGui.quickPrompts.dragInstructions"),
|
||||
dragMove: (title, position, total) =>
|
||||
t("agentHost.agentGui.quickPrompts.dragMove", {
|
||||
title,
|
||||
position,
|
||||
total
|
||||
}),
|
||||
dragStart: (title, position, total) =>
|
||||
t("agentHost.agentGui.quickPrompts.dragStart", {
|
||||
title,
|
||||
position,
|
||||
total
|
||||
}),
|
||||
edit: t("agentHost.agentGui.quickPrompts.edit"),
|
||||
editTitle: t("agentHost.agentGui.quickPrompts.editTitle"),
|
||||
empty: t("agentHost.agentGui.quickPrompts.empty"),
|
||||
finishSorting: t("agentHost.agentGui.quickPrompts.finishSorting"),
|
||||
insertionError: t("agentHost.agentGui.quickPrompts.insertionError"),
|
||||
loadError: t("agentHost.agentGui.quickPrompts.loadError"),
|
||||
loading: t("agentHost.agentGui.quickPrompts.loading"),
|
||||
moreActions: t("agentHost.agentGui.quickPrompts.moreActions"),
|
||||
mutationError: t("agentHost.agentGui.quickPrompts.mutationError"),
|
||||
noResults: t("agentHost.agentGui.quickPrompts.noResults"),
|
||||
required: t("agentHost.agentGui.quickPrompts.required"),
|
||||
reorderConflict: t("agentHost.agentGui.quickPrompts.reorderConflict"),
|
||||
reorderDisabledMinimum: t(
|
||||
"agentHost.agentGui.quickPrompts.reorderDisabledMinimum"
|
||||
),
|
||||
reorderDisabledPending: t(
|
||||
"agentHost.agentGui.quickPrompts.reorderDisabledPending"
|
||||
),
|
||||
reorderDisabledSearch: t(
|
||||
"agentHost.agentGui.quickPrompts.reorderDisabledSearch"
|
||||
),
|
||||
reorderDisabledUnsupported: t(
|
||||
"agentHost.agentGui.quickPrompts.reorderDisabledUnsupported"
|
||||
),
|
||||
reorderError: t("agentHost.agentGui.quickPrompts.reorderError"),
|
||||
retry: t("agentHost.agentGui.quickPrompts.retry"),
|
||||
save: t("agentHost.agentGui.quickPrompts.save"),
|
||||
saving: t("agentHost.agentGui.quickPrompts.saving"),
|
||||
searchPlaceholder: t("agentHost.agentGui.quickPrompts.searchPlaceholder"),
|
||||
startSorting: t("agentHost.agentGui.quickPrompts.startSorting"),
|
||||
recommendedTemplates: [
|
||||
{
|
||||
id: "summary-common-prompts",
|
||||
title: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.summaryCommonPrompts.title"
|
||||
),
|
||||
description: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.summaryCommonPrompts.description"
|
||||
),
|
||||
content: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.summaryCommonPrompts.content"
|
||||
)
|
||||
},
|
||||
{
|
||||
id: "understand-context",
|
||||
title: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.understandContext.title"
|
||||
),
|
||||
description: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.understandContext.description"
|
||||
),
|
||||
content: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.understandContext.content"
|
||||
)
|
||||
},
|
||||
{
|
||||
id: "create-action-plan",
|
||||
title: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.createActionPlan.title"
|
||||
),
|
||||
description: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.createActionPlan.description"
|
||||
),
|
||||
content: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.createActionPlan.content"
|
||||
)
|
||||
},
|
||||
{
|
||||
id: "review-and-improve",
|
||||
title: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.reviewAndImprove.title"
|
||||
),
|
||||
description: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.reviewAndImprove.description"
|
||||
),
|
||||
content: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.reviewAndImprove.content"
|
||||
)
|
||||
},
|
||||
{
|
||||
id: "draft-clear-update",
|
||||
title: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.draftClearUpdate.title"
|
||||
),
|
||||
description: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.draftClearUpdate.description"
|
||||
),
|
||||
content: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplates.draftClearUpdate.content"
|
||||
)
|
||||
}
|
||||
],
|
||||
recommendedTemplatesDescription: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplatesDescription"
|
||||
),
|
||||
recommendedTemplatesTitle: t(
|
||||
"agentHost.agentGui.quickPrompts.recommendedTemplatesTitle"
|
||||
),
|
||||
returnToPrompts: t("agentHost.agentGui.quickPrompts.returnToPrompts"),
|
||||
title: t("agentHost.agentGui.quickPrompts.title"),
|
||||
titleLabel: t("agentHost.agentGui.quickPrompts.titleLabel"),
|
||||
titlePlaceholder: t("agentHost.agentGui.quickPrompts.titlePlaceholder"),
|
||||
titleTooLong: t("agentHost.agentGui.quickPrompts.titleTooLong"),
|
||||
trigger: t("agentHost.agentGui.quickPrompts.trigger"),
|
||||
triggerTooltip: t("agentHost.agentGui.quickPrompts.triggerTooltip"),
|
||||
useTemplate: t("agentHost.agentGui.quickPrompts.useTemplate")
|
||||
};
|
||||
}
|
||||
+610
@@ -0,0 +1,610 @@
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type {
|
||||
AgentHostQuickPromptSnapshot,
|
||||
AgentHostQuickPromptsApi,
|
||||
AgentHostRuntimeApi
|
||||
} from "../../../../host/agentHostApi";
|
||||
import type { AgentQuickPromptLabels } from "./agentQuickPromptLabels";
|
||||
import { useAgentQuickPromptLibrary } from "./useAgentQuickPromptLibrary";
|
||||
|
||||
let hostApi: AgentHostRuntimeApi | null = null;
|
||||
|
||||
vi.mock("../../../../agentActivityHost", () => ({
|
||||
useOptionalAgentHostApi: () => hostApi
|
||||
}));
|
||||
|
||||
const labels = new Proxy(
|
||||
{ deleteDescription: (title: string) => title },
|
||||
{
|
||||
get: (target, property) => Reflect.get(target, property) ?? String(property)
|
||||
}
|
||||
) as AgentQuickPromptLabels;
|
||||
|
||||
function createQuickPrompts() {
|
||||
let snapshot: AgentHostQuickPromptSnapshot = {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
prompts: [
|
||||
{
|
||||
id: "prompt-1",
|
||||
title: "Review",
|
||||
content: "Review this change",
|
||||
version: 1,
|
||||
createdAtUnixMs: 1,
|
||||
updatedAtUnixMs: 2
|
||||
}
|
||||
],
|
||||
error: null,
|
||||
revision: 0,
|
||||
pendingMutationIds: []
|
||||
};
|
||||
const listeners = new Set<(snapshot: AgentHostQuickPromptSnapshot) => void>();
|
||||
const api: AgentHostQuickPromptsApi = {
|
||||
ensureLoaded: vi.fn(async () => {}),
|
||||
getSnapshot: () => snapshot,
|
||||
subscribe: (listener) => {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
create: vi.fn(async (input) => ({
|
||||
id: "created",
|
||||
...input,
|
||||
version: 1,
|
||||
createdAtUnixMs: 3,
|
||||
updatedAtUnixMs: 3
|
||||
})),
|
||||
update: vi.fn(async (input) => ({
|
||||
id: input.id,
|
||||
title: input.title,
|
||||
content: input.content,
|
||||
version: input.expectedVersion + 1,
|
||||
createdAtUnixMs: 1,
|
||||
updatedAtUnixMs: 4
|
||||
})),
|
||||
remove: vi.fn(async () => {}),
|
||||
move: vi.fn(async () => snapshot.prompts)
|
||||
};
|
||||
return {
|
||||
api,
|
||||
publish(next: AgentHostQuickPromptSnapshot) {
|
||||
snapshot = next;
|
||||
for (const listener of listeners) listener(snapshot);
|
||||
},
|
||||
snapshot: () => snapshot
|
||||
};
|
||||
}
|
||||
|
||||
describe("useAgentQuickPromptLibrary", () => {
|
||||
beforeEach(() => {
|
||||
hostApi = null;
|
||||
});
|
||||
|
||||
it("preserves canonical host order and sends an anchor move", async () => {
|
||||
const quickPrompts = createQuickPrompts();
|
||||
const older = {
|
||||
...quickPrompts.snapshot().prompts[0]!,
|
||||
id: "older",
|
||||
title: "Older",
|
||||
updatedAtUnixMs: 1
|
||||
};
|
||||
const newer = {
|
||||
...older,
|
||||
id: "newer",
|
||||
title: "Newer",
|
||||
updatedAtUnixMs: 99
|
||||
};
|
||||
quickPrompts.publish({
|
||||
...quickPrompts.snapshot(),
|
||||
status: "ready",
|
||||
prompts: [older, newer],
|
||||
revision: 1
|
||||
});
|
||||
hostApi = { quickPrompts: quickPrompts.api } as AgentHostRuntimeApi;
|
||||
const rendered = renderHook(() =>
|
||||
useAgentQuickPromptLibrary({
|
||||
disabled: false,
|
||||
labels,
|
||||
onBeforeOpen: vi.fn(),
|
||||
onInsertPrompt: vi.fn()
|
||||
})
|
||||
);
|
||||
expect(
|
||||
rendered.result.current.filteredPrompts.map((prompt) => prompt.id)
|
||||
).toEqual(["older", "newer"]);
|
||||
let moved = false;
|
||||
await act(async () => {
|
||||
moved = await rendered.result.current.reorderPrompts("older", null);
|
||||
});
|
||||
expect(moved).toBe(true);
|
||||
expect(quickPrompts.api.move).toHaveBeenCalledWith({
|
||||
promptId: "older",
|
||||
beforePromptId: null,
|
||||
expectedVersion: older.version
|
||||
});
|
||||
});
|
||||
|
||||
it("locks reorder and all mutating entry points while the shared host snapshot is pending", () => {
|
||||
const quickPrompts = createQuickPrompts();
|
||||
const second = {
|
||||
...quickPrompts.snapshot().prompts[0]!,
|
||||
id: "prompt-2",
|
||||
title: "Plan"
|
||||
};
|
||||
quickPrompts.publish({
|
||||
...quickPrompts.snapshot(),
|
||||
status: "ready",
|
||||
prompts: [...quickPrompts.snapshot().prompts, second],
|
||||
pendingMutationIds: ["other-window-update"],
|
||||
revision: 1
|
||||
});
|
||||
hostApi = { quickPrompts: quickPrompts.api } as AgentHostRuntimeApi;
|
||||
const onInsertPrompt = vi.fn(() => true);
|
||||
const rendered = renderHook(() =>
|
||||
useAgentQuickPromptLibrary({
|
||||
disabled: false,
|
||||
labels,
|
||||
onBeforeOpen: vi.fn(),
|
||||
onInsertPrompt
|
||||
})
|
||||
);
|
||||
|
||||
expect(rendered.result.current.isInteractionLocked).toBe(true);
|
||||
expect(rendered.result.current.canReorder).toBe(false);
|
||||
expect(rendered.result.current.reorderCapabilityAvailable).toBe(true);
|
||||
act(() => {
|
||||
rendered.result.current.openCreate();
|
||||
rendered.result.current.openEdit(second);
|
||||
rendered.result.current.deletePrompt(second);
|
||||
rendered.result.current.selectPrompt(second);
|
||||
rendered.result.current.setSearchQuery("plan");
|
||||
});
|
||||
expect(rendered.result.current.mode).toBe("closed");
|
||||
expect(rendered.result.current.searchQuery).toBe("");
|
||||
expect(onInsertPrompt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lazy-loads when opened and inserts a selection without a submit path", () => {
|
||||
const quickPrompts = createQuickPrompts();
|
||||
hostApi = { quickPrompts: quickPrompts.api } as AgentHostRuntimeApi;
|
||||
const onBeforeOpen = vi.fn();
|
||||
const onInsertPrompt = vi.fn(() => true);
|
||||
const rendered = renderHook(() =>
|
||||
useAgentQuickPromptLibrary({
|
||||
disabled: false,
|
||||
labels,
|
||||
onBeforeOpen,
|
||||
onInsertPrompt
|
||||
})
|
||||
);
|
||||
|
||||
act(() => rendered.result.current.openPopover());
|
||||
expect(onBeforeOpen).toHaveBeenCalledOnce();
|
||||
expect(quickPrompts.api.ensureLoaded).toHaveBeenCalledWith();
|
||||
expect(rendered.result.current.isPopoverOpen).toBe(true);
|
||||
|
||||
act(() =>
|
||||
rendered.result.current.selectPrompt(
|
||||
rendered.result.current.filteredPrompts[0]!
|
||||
)
|
||||
);
|
||||
expect(onInsertPrompt).toHaveBeenCalledWith("Review this change");
|
||||
expect(rendered.result.current.mode).toBe("closed");
|
||||
});
|
||||
|
||||
it("closes all disclosure when the feature gate turns off", () => {
|
||||
const quickPrompts = createQuickPrompts();
|
||||
hostApi = { quickPrompts: quickPrompts.api } as AgentHostRuntimeApi;
|
||||
const rendered = renderHook(() =>
|
||||
useAgentQuickPromptLibrary({
|
||||
disabled: false,
|
||||
labels,
|
||||
onBeforeOpen: vi.fn(),
|
||||
onInsertPrompt: vi.fn()
|
||||
})
|
||||
);
|
||||
|
||||
act(() => rendered.result.current.openPopover());
|
||||
act(() => rendered.result.current.openCreate());
|
||||
expect(rendered.result.current.isEditorOpen).toBe(true);
|
||||
|
||||
act(() => {
|
||||
quickPrompts.publish({
|
||||
...quickPrompts.snapshot(),
|
||||
enabled: false,
|
||||
revision: 1
|
||||
});
|
||||
});
|
||||
expect(rendered.result.current.capabilityAvailable).toBe(false);
|
||||
expect(rendered.result.current.mode).toBe("closed");
|
||||
});
|
||||
|
||||
it("does not let a stale popover close callback dismiss the create dialog", () => {
|
||||
const quickPrompts = createQuickPrompts();
|
||||
hostApi = { quickPrompts: quickPrompts.api } as AgentHostRuntimeApi;
|
||||
const rendered = renderHook(() =>
|
||||
useAgentQuickPromptLibrary({
|
||||
disabled: false,
|
||||
labels,
|
||||
onBeforeOpen: vi.fn(),
|
||||
onInsertPrompt: vi.fn()
|
||||
})
|
||||
);
|
||||
|
||||
act(() => rendered.result.current.openPopover());
|
||||
const stalePopoverOpenChange = rendered.result.current.setPopoverOpen;
|
||||
act(() => rendered.result.current.openCreate());
|
||||
expect(rendered.result.current.mode).toBe("create");
|
||||
|
||||
act(() => stalePopoverOpenChange(false));
|
||||
expect(rendered.result.current.mode).toBe("create");
|
||||
expect(rendered.result.current.isEditorOpen).toBe(true);
|
||||
});
|
||||
|
||||
it("does not open or load while composer controls are disabled", () => {
|
||||
const quickPrompts = createQuickPrompts();
|
||||
hostApi = { quickPrompts: quickPrompts.api } as AgentHostRuntimeApi;
|
||||
const rendered = renderHook(() =>
|
||||
useAgentQuickPromptLibrary({
|
||||
disabled: true,
|
||||
labels,
|
||||
onBeforeOpen: vi.fn(),
|
||||
onInsertPrompt: vi.fn()
|
||||
})
|
||||
);
|
||||
|
||||
act(() => rendered.result.current.openPopover());
|
||||
expect(rendered.result.current.mode).toBe("closed");
|
||||
expect(quickPrompts.api.ensureLoaded).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a recommended template local until the user saves it", () => {
|
||||
const quickPrompts = createQuickPrompts();
|
||||
hostApi = { quickPrompts: quickPrompts.api } as AgentHostRuntimeApi;
|
||||
const rendered = renderHook(() =>
|
||||
useAgentQuickPromptLibrary({
|
||||
disabled: false,
|
||||
labels,
|
||||
onBeforeOpen: vi.fn(),
|
||||
onInsertPrompt: vi.fn()
|
||||
})
|
||||
);
|
||||
const template = {
|
||||
title: "Understand the situation",
|
||||
content: "Summarize the situation"
|
||||
};
|
||||
|
||||
act(() => rendered.result.current.openCreate(template));
|
||||
expect(rendered.result.current.initialDraft).toEqual(template);
|
||||
expect(rendered.result.current.mode).toBe("create");
|
||||
expect(quickPrompts.api.create).not.toHaveBeenCalled();
|
||||
|
||||
act(() => rendered.result.current.closeDialog());
|
||||
expect(rendered.result.current.initialDraft).toBeNull();
|
||||
expect(quickPrompts.api.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("runs create and preserves edit disclosure on a version conflict", async () => {
|
||||
const quickPrompts = createQuickPrompts();
|
||||
hostApi = { quickPrompts: quickPrompts.api } as AgentHostRuntimeApi;
|
||||
const onInsertPrompt = vi.fn(() => true);
|
||||
const rendered = renderHook(() =>
|
||||
useAgentQuickPromptLibrary({
|
||||
disabled: false,
|
||||
labels,
|
||||
onBeforeOpen: vi.fn(),
|
||||
onInsertPrompt
|
||||
})
|
||||
);
|
||||
|
||||
act(() => rendered.result.current.openPopover());
|
||||
act(() => rendered.result.current.openCreate());
|
||||
await act(async () => {
|
||||
expect(
|
||||
await rendered.result.current.saveDraft({
|
||||
title: "Explain",
|
||||
content: "Explain this code"
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
expect(quickPrompts.api.create).toHaveBeenCalledWith({
|
||||
title: "Explain",
|
||||
content: "Explain this code"
|
||||
});
|
||||
expect(rendered.result.current.mode).toBe("popover");
|
||||
expect(onInsertPrompt).not.toHaveBeenCalled();
|
||||
|
||||
act(() =>
|
||||
rendered.result.current.openEdit(
|
||||
rendered.result.current.filteredPrompts[0]!
|
||||
)
|
||||
);
|
||||
vi.mocked(quickPrompts.api.update).mockRejectedValueOnce({
|
||||
code: "agent_quick_prompt_conflict",
|
||||
reason: "agent_quick_prompt_version_conflict",
|
||||
statusCode: 409
|
||||
});
|
||||
vi.mocked(quickPrompts.api.ensureLoaded).mockImplementationOnce(
|
||||
async () => {
|
||||
quickPrompts.publish({
|
||||
...quickPrompts.snapshot(),
|
||||
prompts: quickPrompts.snapshot().prompts.map((prompt) => ({
|
||||
...prompt,
|
||||
version: 2,
|
||||
updatedAtUnixMs: 5
|
||||
})),
|
||||
revision: 2
|
||||
});
|
||||
}
|
||||
);
|
||||
await act(async () => {
|
||||
expect(
|
||||
await rendered.result.current.saveDraft({
|
||||
title: "Review",
|
||||
content: "Keep my changed draft"
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
expect(rendered.result.current.mode).toBe("edit");
|
||||
expect(rendered.result.current.mutationError).toBe("conflict");
|
||||
expect(quickPrompts.api.ensureLoaded).toHaveBeenLastCalledWith({
|
||||
force: true
|
||||
});
|
||||
expect(rendered.result.current.selectedPrompt?.version).toBe(2);
|
||||
|
||||
await act(async () => {
|
||||
expect(
|
||||
await rendered.result.current.saveDraft({
|
||||
title: "Review",
|
||||
content: "Keep my changed draft"
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
expect(quickPrompts.api.update).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ expectedVersion: 2 })
|
||||
);
|
||||
expect(onInsertPrompt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("inserts a template-backed prompt into the Composer after creation", async () => {
|
||||
const quickPrompts = createQuickPrompts();
|
||||
hostApi = { quickPrompts: quickPrompts.api } as AgentHostRuntimeApi;
|
||||
const onInsertPrompt = vi.fn(() => true);
|
||||
const onQuickPromptUsed = vi.fn();
|
||||
const rendered = renderHook(() =>
|
||||
useAgentQuickPromptLibrary({
|
||||
disabled: false,
|
||||
labels,
|
||||
onBeforeOpen: vi.fn(),
|
||||
onInsertPrompt,
|
||||
onQuickPromptUsed
|
||||
})
|
||||
);
|
||||
|
||||
act(() => rendered.result.current.openPopover());
|
||||
act(() =>
|
||||
rendered.result.current.openCreate(
|
||||
{
|
||||
title: "Template title",
|
||||
content: "Template content"
|
||||
},
|
||||
{
|
||||
insertIntoComposerAfterSave: true,
|
||||
usagePromptType: "recommended_template"
|
||||
}
|
||||
)
|
||||
);
|
||||
await act(async () => {
|
||||
expect(
|
||||
await rendered.result.current.saveDraft({
|
||||
title: "Edited title",
|
||||
content: "Edited template content"
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
expect(quickPrompts.api.create).toHaveBeenCalledWith({
|
||||
title: "Edited title",
|
||||
content: "Edited template content"
|
||||
});
|
||||
expect(onInsertPrompt).toHaveBeenCalledOnce();
|
||||
expect(onInsertPrompt).toHaveBeenCalledWith("Edited template content");
|
||||
expect(onQuickPromptUsed).toHaveBeenCalledOnce();
|
||||
expect(onQuickPromptUsed).toHaveBeenCalledWith("recommended_template");
|
||||
expect(rendered.result.current.mode).toBe("closed");
|
||||
});
|
||||
|
||||
it("keeps a saved template in the library when Composer insertion throws", async () => {
|
||||
const quickPrompts = createQuickPrompts();
|
||||
hostApi = { quickPrompts: quickPrompts.api } as AgentHostRuntimeApi;
|
||||
const onInsertPrompt = vi.fn(() => {
|
||||
throw new Error("editor unavailable");
|
||||
});
|
||||
const onQuickPromptUsed = vi.fn();
|
||||
const rendered = renderHook(() =>
|
||||
useAgentQuickPromptLibrary({
|
||||
disabled: false,
|
||||
labels,
|
||||
onBeforeOpen: vi.fn(),
|
||||
onInsertPrompt,
|
||||
onQuickPromptUsed
|
||||
})
|
||||
);
|
||||
|
||||
act(() => rendered.result.current.openPopover());
|
||||
act(() =>
|
||||
rendered.result.current.openCreate(
|
||||
{ title: "Template", content: "Template content" },
|
||||
{
|
||||
insertIntoComposerAfterSave: true,
|
||||
usagePromptType: "recommended_template"
|
||||
}
|
||||
)
|
||||
);
|
||||
await act(async () => {
|
||||
expect(
|
||||
await rendered.result.current.saveDraft({
|
||||
title: "Template",
|
||||
content: "Edited content"
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
expect(quickPrompts.api.create).toHaveBeenCalledOnce();
|
||||
expect(onInsertPrompt).toHaveBeenCalledWith("Edited content");
|
||||
expect(rendered.result.current.mutationError).toBeNull();
|
||||
expect(rendered.result.current.insertionError).toBe(true);
|
||||
expect(onQuickPromptUsed).not.toHaveBeenCalled();
|
||||
expect(rendered.result.current.mode).toBe("popover");
|
||||
});
|
||||
|
||||
it("retains template insertion intent when creation succeeds on retry", async () => {
|
||||
const quickPrompts = createQuickPrompts();
|
||||
vi.mocked(quickPrompts.api.create).mockRejectedValueOnce(
|
||||
new Error("temporary create failure")
|
||||
);
|
||||
hostApi = { quickPrompts: quickPrompts.api } as AgentHostRuntimeApi;
|
||||
const onInsertPrompt = vi.fn(() => true);
|
||||
const onQuickPromptUsed = vi.fn();
|
||||
const rendered = renderHook(() =>
|
||||
useAgentQuickPromptLibrary({
|
||||
disabled: false,
|
||||
labels,
|
||||
onBeforeOpen: vi.fn(),
|
||||
onInsertPrompt,
|
||||
onQuickPromptUsed
|
||||
})
|
||||
);
|
||||
|
||||
act(() => rendered.result.current.openPopover());
|
||||
act(() =>
|
||||
rendered.result.current.openCreate(
|
||||
{ title: "Template", content: "Template content" },
|
||||
{
|
||||
insertIntoComposerAfterSave: true,
|
||||
usagePromptType: "recommended_template"
|
||||
}
|
||||
)
|
||||
);
|
||||
await act(async () => {
|
||||
expect(
|
||||
await rendered.result.current.saveDraft({
|
||||
title: "Template",
|
||||
content: "Edited content"
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
expect(onInsertPrompt).not.toHaveBeenCalled();
|
||||
expect(onQuickPromptUsed).not.toHaveBeenCalled();
|
||||
expect(rendered.result.current.mode).toBe("create");
|
||||
|
||||
await act(async () => {
|
||||
expect(
|
||||
await rendered.result.current.saveDraft({
|
||||
title: "Template",
|
||||
content: "Edited again"
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
expect(onInsertPrompt).toHaveBeenCalledOnce();
|
||||
expect(onQuickPromptUsed).toHaveBeenCalledOnce();
|
||||
expect(onQuickPromptUsed).toHaveBeenCalledWith("recommended_template");
|
||||
expect(onInsertPrompt).toHaveBeenCalledWith("Edited again");
|
||||
expect(rendered.result.current.mode).toBe("closed");
|
||||
});
|
||||
|
||||
it("does not insert after the template creation disclosure becomes unavailable", async () => {
|
||||
const quickPrompts = createQuickPrompts();
|
||||
let releaseCreate: (() => void) | undefined;
|
||||
vi.mocked(quickPrompts.api.create).mockImplementationOnce(async (input) => {
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseCreate = resolve;
|
||||
});
|
||||
return {
|
||||
id: "created-after-disable",
|
||||
...input,
|
||||
version: 1,
|
||||
createdAtUnixMs: 5,
|
||||
updatedAtUnixMs: 5
|
||||
};
|
||||
});
|
||||
hostApi = { quickPrompts: quickPrompts.api } as AgentHostRuntimeApi;
|
||||
const onInsertPrompt = vi.fn(() => true);
|
||||
const rendered = renderHook(
|
||||
({ disabled }) =>
|
||||
useAgentQuickPromptLibrary({
|
||||
disabled,
|
||||
labels,
|
||||
onBeforeOpen: vi.fn(),
|
||||
onInsertPrompt
|
||||
}),
|
||||
{ initialProps: { disabled: false } }
|
||||
);
|
||||
|
||||
act(() => rendered.result.current.openPopover());
|
||||
act(() =>
|
||||
rendered.result.current.openCreate(
|
||||
{ title: "Template", content: "Template content" },
|
||||
{ insertIntoComposerAfterSave: true }
|
||||
)
|
||||
);
|
||||
let saveResult: Promise<boolean> | undefined;
|
||||
act(() => {
|
||||
saveResult = rendered.result.current.saveDraft({
|
||||
title: "Template",
|
||||
content: "Edited content"
|
||||
});
|
||||
});
|
||||
expect(releaseCreate).toBeTypeOf("function");
|
||||
|
||||
rendered.rerender({ disabled: true });
|
||||
await act(async () => {
|
||||
releaseCreate?.();
|
||||
expect(await saveResult).toBe(true);
|
||||
});
|
||||
|
||||
expect(onInsertPrompt).not.toHaveBeenCalled();
|
||||
expect(rendered.result.current.mode).toBe("closed");
|
||||
});
|
||||
|
||||
it("does not treat the prompt limit as a version conflict", async () => {
|
||||
const quickPrompts = createQuickPrompts();
|
||||
hostApi = { quickPrompts: quickPrompts.api } as AgentHostRuntimeApi;
|
||||
vi.mocked(quickPrompts.api.create).mockRejectedValueOnce({
|
||||
code: "agent_quick_prompt_conflict",
|
||||
reason: "agent_quick_prompt_limit_exceeded",
|
||||
statusCode: 409
|
||||
});
|
||||
const onInsertPrompt = vi.fn(() => true);
|
||||
const rendered = renderHook(() =>
|
||||
useAgentQuickPromptLibrary({
|
||||
disabled: false,
|
||||
labels,
|
||||
onBeforeOpen: vi.fn(),
|
||||
onInsertPrompt
|
||||
})
|
||||
);
|
||||
|
||||
act(() => rendered.result.current.openPopover());
|
||||
act(() =>
|
||||
rendered.result.current.openCreate(
|
||||
{ title: "Template", content: "Template content" },
|
||||
{ insertIntoComposerAfterSave: true }
|
||||
)
|
||||
);
|
||||
await act(async () => {
|
||||
expect(
|
||||
await rendered.result.current.saveDraft({
|
||||
title: "One more prompt",
|
||||
content: "This exceeds the device limit"
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
expect(rendered.result.current.mutationError).toBe("generic");
|
||||
expect(rendered.result.current.insertionError).toBe(false);
|
||||
expect(rendered.result.current.mode).toBe("create");
|
||||
expect(onInsertPrompt).not.toHaveBeenCalled();
|
||||
expect(quickPrompts.api.ensureLoaded).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
+544
@@ -0,0 +1,544 @@
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { useOptionalAgentHostApi } from "../../../../agentActivityHost";
|
||||
import type {
|
||||
AgentHostQuickPrompt,
|
||||
AgentHostQuickPromptSnapshot
|
||||
} from "../../../../host/agentHostApi";
|
||||
import { useEngineSelector } from "../../../../shared/engine/useEngineSelector";
|
||||
import type { AgentQuickPromptLabels } from "./agentQuickPromptLabels";
|
||||
import type { AgentGUIQuickPromptType } from "../../engagement/agentGUIEngagement.types";
|
||||
|
||||
const unavailableSnapshot: AgentHostQuickPromptSnapshot = {
|
||||
enabled: false,
|
||||
status: "idle",
|
||||
prompts: [],
|
||||
error: null,
|
||||
revision: 0,
|
||||
pendingMutationIds: []
|
||||
};
|
||||
const unavailableQuickPromptStore = {
|
||||
getSnapshot: (): AgentHostQuickPromptSnapshot => unavailableSnapshot,
|
||||
subscribe:
|
||||
(
|
||||
_listener: (snapshot: AgentHostQuickPromptSnapshot) => void
|
||||
): (() => void) =>
|
||||
() => {}
|
||||
};
|
||||
|
||||
type AgentQuickPromptMode = "closed" | "popover" | "create" | "edit" | "delete";
|
||||
type AgentQuickPromptMutationError = "conflict" | "generic" | null;
|
||||
|
||||
export interface AgentQuickPromptDraft {
|
||||
content: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface AgentQuickPromptCreateOptions {
|
||||
insertIntoComposerAfterSave?: boolean;
|
||||
usagePromptType?: AgentGUIQuickPromptType;
|
||||
}
|
||||
|
||||
export interface AgentQuickPromptLibraryController {
|
||||
capabilityAvailable: boolean;
|
||||
canReorder: boolean;
|
||||
close: () => void;
|
||||
closeDialog: () => void;
|
||||
deletePrompt: (prompt: AgentHostQuickPrompt) => void;
|
||||
filteredPrompts: readonly AgentHostQuickPrompt[];
|
||||
isDeleting: boolean;
|
||||
isEditorOpen: boolean;
|
||||
isPopoverOpen: boolean;
|
||||
isSaving: boolean;
|
||||
isInteractionLocked: boolean;
|
||||
isReordering: boolean;
|
||||
initialDraft: AgentQuickPromptDraft | null;
|
||||
insertionError: boolean;
|
||||
labels: AgentQuickPromptLabels;
|
||||
mode: AgentQuickPromptMode;
|
||||
mutationError: AgentQuickPromptMutationError;
|
||||
openCreate: (
|
||||
draft?: AgentQuickPromptDraft,
|
||||
options?: AgentQuickPromptCreateOptions
|
||||
) => void;
|
||||
openEdit: (prompt: AgentHostQuickPrompt) => void;
|
||||
openPopover: () => void;
|
||||
promptToDelete: AgentHostQuickPrompt | null;
|
||||
retry: () => void;
|
||||
reorderCapabilityAvailable: boolean;
|
||||
reorderError: AgentQuickPromptMutationError;
|
||||
reorderPrompts: (
|
||||
promptId: string,
|
||||
beforePromptId: string | null
|
||||
) => Promise<boolean>;
|
||||
saveDraft: (draft: AgentQuickPromptDraft) => Promise<boolean>;
|
||||
searchQuery: string;
|
||||
showReorderHandles: boolean;
|
||||
selectPrompt: (prompt: AgentHostQuickPrompt) => void;
|
||||
selectedPrompt: AgentHostQuickPrompt | null;
|
||||
setPopoverOpen: (open: boolean) => void;
|
||||
setSearchQuery: (query: string) => void;
|
||||
snapshot: AgentHostQuickPromptSnapshot;
|
||||
submitDelete: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
export function useAgentQuickPromptLibrary(input: {
|
||||
disabled: boolean;
|
||||
labels: AgentQuickPromptLabels;
|
||||
onBeforeOpen: () => void;
|
||||
onInsertPrompt: (content: string) => boolean;
|
||||
onQuickPromptPanelOpened?: () => void;
|
||||
onQuickPromptUsed?: (promptType: AgentGUIQuickPromptType) => void;
|
||||
}): AgentQuickPromptLibraryController {
|
||||
const {
|
||||
disabled,
|
||||
labels,
|
||||
onBeforeOpen,
|
||||
onInsertPrompt,
|
||||
onQuickPromptPanelOpened,
|
||||
onQuickPromptUsed
|
||||
} = input;
|
||||
const hostApi = useOptionalAgentHostApi();
|
||||
const quickPrompts = hostApi?.quickPrompts;
|
||||
const snapshot = useEngineSelector(
|
||||
quickPrompts ?? unavailableQuickPromptStore,
|
||||
selectQuickPromptSnapshot
|
||||
);
|
||||
const [mode, setMode] = useState<AgentQuickPromptMode>("closed");
|
||||
const modeRef = useRef(mode);
|
||||
modeRef.current = mode;
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedPrompt, setSelectedPrompt] =
|
||||
useState<AgentHostQuickPrompt | null>(null);
|
||||
const [initialDraft, setInitialDraft] =
|
||||
useState<AgentQuickPromptDraft | null>(null);
|
||||
const createOptionsRef = useRef<AgentQuickPromptCreateOptions | null>(null);
|
||||
const [promptToDelete, setPromptToDelete] =
|
||||
useState<AgentHostQuickPrompt | null>(null);
|
||||
const [mutationError, setMutationError] =
|
||||
useState<AgentQuickPromptMutationError>(null);
|
||||
const [insertionError, setInsertionError] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isReordering, setIsReordering] = useState(false);
|
||||
const [reorderError, setReorderError] =
|
||||
useState<AgentQuickPromptMutationError>(null);
|
||||
const capabilityAvailable = Boolean(quickPrompts && snapshot.enabled);
|
||||
const disclosureAvailable = capabilityAvailable && !disabled;
|
||||
const [previousDisclosureAvailable, setPreviousDisclosureAvailable] =
|
||||
useState(disclosureAvailable);
|
||||
const disclosureAvailableRef = useRef(disclosureAvailable);
|
||||
disclosureAvailableRef.current = disclosureAvailable;
|
||||
if (previousDisclosureAvailable !== disclosureAvailable) {
|
||||
setPreviousDisclosureAvailable(disclosureAvailable);
|
||||
modeRef.current = "closed";
|
||||
setMode("closed");
|
||||
setSelectedPrompt(null);
|
||||
setInitialDraft(null);
|
||||
createOptionsRef.current = null;
|
||||
setPromptToDelete(null);
|
||||
setMutationError(null);
|
||||
setInsertionError(false);
|
||||
setReorderError(null);
|
||||
}
|
||||
const effectiveMode =
|
||||
disclosureAvailable && previousDisclosureAvailable === disclosureAvailable
|
||||
? mode
|
||||
: "closed";
|
||||
|
||||
const filteredPrompts = useMemo(() => {
|
||||
const query = searchQuery.trim().toLocaleLowerCase();
|
||||
if (!query) {
|
||||
return snapshot.prompts;
|
||||
}
|
||||
return snapshot.prompts.filter(
|
||||
(prompt) =>
|
||||
prompt.title.toLocaleLowerCase().includes(query) ||
|
||||
prompt.content.toLocaleLowerCase().includes(query)
|
||||
);
|
||||
}, [searchQuery, snapshot.prompts]);
|
||||
const isInteractionLocked =
|
||||
isSaving ||
|
||||
isDeleting ||
|
||||
isReordering ||
|
||||
Boolean(snapshot.orderMutationPending) ||
|
||||
snapshot.pendingMutationIds.length > 0;
|
||||
const reorderCapabilityAvailable = Boolean(
|
||||
quickPrompts?.move && capabilityAvailable
|
||||
);
|
||||
const canReorder = Boolean(
|
||||
reorderCapabilityAvailable &&
|
||||
!disabled &&
|
||||
!searchQuery.trim() &&
|
||||
filteredPrompts.length > 1 &&
|
||||
!isInteractionLocked
|
||||
);
|
||||
const showReorderHandles = Boolean(
|
||||
reorderCapabilityAvailable &&
|
||||
!searchQuery.trim() &&
|
||||
filteredPrompts.length > 1
|
||||
);
|
||||
|
||||
const openPopover = useCallback(() => {
|
||||
if (!capabilityAvailable || disabled) {
|
||||
return;
|
||||
}
|
||||
onBeforeOpen();
|
||||
onQuickPromptPanelOpened?.();
|
||||
setMutationError(null);
|
||||
setInsertionError(false);
|
||||
setReorderError(null);
|
||||
modeRef.current = "popover";
|
||||
setMode("popover");
|
||||
if (snapshot.status === "idle") {
|
||||
void quickPrompts?.ensureLoaded().catch(() => undefined);
|
||||
}
|
||||
}, [
|
||||
capabilityAvailable,
|
||||
disabled,
|
||||
onBeforeOpen,
|
||||
onQuickPromptPanelOpened,
|
||||
quickPrompts,
|
||||
snapshot.status
|
||||
]);
|
||||
|
||||
const close = useCallback(() => {
|
||||
modeRef.current = "closed";
|
||||
setMode("closed");
|
||||
setSelectedPrompt(null);
|
||||
setInitialDraft(null);
|
||||
createOptionsRef.current = null;
|
||||
setPromptToDelete(null);
|
||||
setMutationError(null);
|
||||
setInsertionError(false);
|
||||
setReorderError(null);
|
||||
}, []);
|
||||
|
||||
const closeDialog = useCallback(() => {
|
||||
const nextMode = capabilityAvailable && !disabled ? "popover" : "closed";
|
||||
modeRef.current = nextMode;
|
||||
setMutationError(null);
|
||||
setReorderError(null);
|
||||
setSelectedPrompt(null);
|
||||
setInitialDraft(null);
|
||||
createOptionsRef.current = null;
|
||||
setPromptToDelete(null);
|
||||
setInsertionError(false);
|
||||
setMode(nextMode);
|
||||
}, [capabilityAvailable, disabled]);
|
||||
|
||||
const setPopoverOpen = useCallback(
|
||||
(open: boolean) => {
|
||||
if (open) {
|
||||
openPopover();
|
||||
} else if (modeRef.current === "popover") {
|
||||
close();
|
||||
}
|
||||
},
|
||||
[close, openPopover]
|
||||
);
|
||||
|
||||
const openCreate = useCallback(
|
||||
(
|
||||
draft?: AgentQuickPromptDraft,
|
||||
options?: AgentQuickPromptCreateOptions
|
||||
) => {
|
||||
if (isInteractionLocked) return;
|
||||
modeRef.current = "create";
|
||||
setSelectedPrompt(null);
|
||||
setInitialDraft(draft ?? null);
|
||||
createOptionsRef.current = options ?? null;
|
||||
setMutationError(null);
|
||||
setInsertionError(false);
|
||||
setMode("create");
|
||||
},
|
||||
[isInteractionLocked]
|
||||
);
|
||||
|
||||
const openEdit = useCallback(
|
||||
(prompt: AgentHostQuickPrompt) => {
|
||||
if (isInteractionLocked) return;
|
||||
modeRef.current = "edit";
|
||||
setSelectedPrompt(prompt);
|
||||
setInitialDraft(null);
|
||||
createOptionsRef.current = null;
|
||||
setMutationError(null);
|
||||
setInsertionError(false);
|
||||
setMode("edit");
|
||||
},
|
||||
[isInteractionLocked]
|
||||
);
|
||||
|
||||
const deletePrompt = useCallback(
|
||||
(prompt: AgentHostQuickPrompt) => {
|
||||
if (isInteractionLocked) return;
|
||||
modeRef.current = "delete";
|
||||
setPromptToDelete(prompt);
|
||||
setMutationError(null);
|
||||
setMode("delete");
|
||||
},
|
||||
[isInteractionLocked]
|
||||
);
|
||||
|
||||
const saveDraft = useCallback(
|
||||
async (draft: AgentQuickPromptDraft): Promise<boolean> => {
|
||||
if (!quickPrompts || !capabilityAvailable || isInteractionLocked) {
|
||||
return false;
|
||||
}
|
||||
setIsSaving(true);
|
||||
setMutationError(null);
|
||||
setInsertionError(false);
|
||||
const createOptions = selectedPrompt ? null : createOptionsRef.current;
|
||||
let saved: AgentHostQuickPrompt;
|
||||
try {
|
||||
saved = selectedPrompt
|
||||
? await quickPrompts.update({
|
||||
id: selectedPrompt.id,
|
||||
title: draft.title,
|
||||
content: draft.content,
|
||||
expectedVersion: selectedPrompt.version
|
||||
})
|
||||
: await quickPrompts.create(draft);
|
||||
} catch (error) {
|
||||
const conflict = isVersionConflict(error);
|
||||
setMutationError(conflict ? "conflict" : "generic");
|
||||
if (conflict && selectedPrompt) {
|
||||
try {
|
||||
await quickPrompts.ensureLoaded({ force: true });
|
||||
const refreshedPrompt = quickPrompts
|
||||
.getSnapshot()
|
||||
.prompts.find((prompt) => prompt.id === selectedPrompt.id);
|
||||
if (refreshedPrompt) setSelectedPrompt(refreshedPrompt);
|
||||
} catch {
|
||||
setMutationError("conflict");
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
|
||||
const insertIntoComposerAfterSave = Boolean(
|
||||
createOptions?.insertIntoComposerAfterSave &&
|
||||
createOptionsRef.current === createOptions &&
|
||||
disclosureAvailableRef.current
|
||||
);
|
||||
if (insertIntoComposerAfterSave) {
|
||||
let inserted = false;
|
||||
try {
|
||||
inserted = onInsertPrompt(saved.content);
|
||||
} catch {
|
||||
inserted = false;
|
||||
}
|
||||
if (inserted) {
|
||||
if (createOptions?.usagePromptType) {
|
||||
onQuickPromptUsed?.(createOptions.usagePromptType);
|
||||
}
|
||||
close();
|
||||
return true;
|
||||
}
|
||||
setInsertionError(true);
|
||||
}
|
||||
|
||||
setSelectedPrompt(saved);
|
||||
setInitialDraft(null);
|
||||
createOptionsRef.current = null;
|
||||
const nextMode = disclosureAvailableRef.current ? "popover" : "closed";
|
||||
modeRef.current = nextMode;
|
||||
setMode(nextMode);
|
||||
return true;
|
||||
},
|
||||
[
|
||||
capabilityAvailable,
|
||||
close,
|
||||
isInteractionLocked,
|
||||
onInsertPrompt,
|
||||
onQuickPromptUsed,
|
||||
quickPrompts,
|
||||
selectedPrompt
|
||||
]
|
||||
);
|
||||
|
||||
const submitDelete = useCallback(async (): Promise<boolean> => {
|
||||
if (
|
||||
!quickPrompts ||
|
||||
!capabilityAvailable ||
|
||||
!promptToDelete ||
|
||||
isInteractionLocked
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
setIsDeleting(true);
|
||||
setMutationError(null);
|
||||
try {
|
||||
await quickPrompts.remove({
|
||||
id: promptToDelete.id,
|
||||
expectedVersion: promptToDelete.version
|
||||
});
|
||||
setPromptToDelete(null);
|
||||
const nextMode = disclosureAvailableRef.current ? "popover" : "closed";
|
||||
modeRef.current = nextMode;
|
||||
setMode(nextMode);
|
||||
return true;
|
||||
} catch (error) {
|
||||
const conflict = isVersionConflict(error);
|
||||
setMutationError(conflict ? "conflict" : "generic");
|
||||
if (conflict) {
|
||||
try {
|
||||
await quickPrompts.ensureLoaded({ force: true });
|
||||
const refreshedPrompt = quickPrompts
|
||||
.getSnapshot()
|
||||
.prompts.find((prompt) => prompt.id === promptToDelete.id);
|
||||
if (refreshedPrompt) setPromptToDelete(refreshedPrompt);
|
||||
} catch {
|
||||
setMutationError("conflict");
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
}, [capabilityAvailable, isInteractionLocked, promptToDelete, quickPrompts]);
|
||||
|
||||
const retry = useCallback(() => {
|
||||
if (!quickPrompts || !capabilityAvailable || isInteractionLocked) {
|
||||
return;
|
||||
}
|
||||
setReorderError(null);
|
||||
void quickPrompts.ensureLoaded({ force: true }).catch(() => undefined);
|
||||
}, [capabilityAvailable, isInteractionLocked, quickPrompts]);
|
||||
|
||||
const reorderPrompts = useCallback(
|
||||
async (
|
||||
promptId: string,
|
||||
beforePromptId: string | null
|
||||
): Promise<boolean> => {
|
||||
if (!quickPrompts?.move || !canReorder) return false;
|
||||
const prompt = snapshot.prompts.find((item) => item.id === promptId);
|
||||
if (!prompt) return false;
|
||||
setIsReordering(true);
|
||||
setReorderError(null);
|
||||
try {
|
||||
await quickPrompts.move({
|
||||
promptId,
|
||||
beforePromptId,
|
||||
expectedVersion: prompt.version
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
setReorderError(isOrderConflict(error) ? "conflict" : "generic");
|
||||
return false;
|
||||
} finally {
|
||||
setIsReordering(false);
|
||||
}
|
||||
},
|
||||
[canReorder, quickPrompts, snapshot.prompts]
|
||||
);
|
||||
|
||||
const insertPromptContent = useCallback(
|
||||
(content: string) => {
|
||||
if (disabled || !capabilityAvailable || isInteractionLocked) {
|
||||
return;
|
||||
}
|
||||
let inserted = false;
|
||||
try {
|
||||
inserted = onInsertPrompt(content);
|
||||
} catch {
|
||||
inserted = false;
|
||||
}
|
||||
if (inserted) {
|
||||
onQuickPromptUsed?.("saved");
|
||||
close();
|
||||
} else {
|
||||
setInsertionError(true);
|
||||
}
|
||||
},
|
||||
[
|
||||
capabilityAvailable,
|
||||
close,
|
||||
disabled,
|
||||
isInteractionLocked,
|
||||
onInsertPrompt,
|
||||
onQuickPromptUsed
|
||||
]
|
||||
);
|
||||
|
||||
const updateSearchQuery = useCallback(
|
||||
(query: string) => {
|
||||
if (isInteractionLocked) return;
|
||||
setSearchQuery(query);
|
||||
},
|
||||
[isInteractionLocked]
|
||||
);
|
||||
const selectPrompt = useCallback(
|
||||
(prompt: AgentHostQuickPrompt) => {
|
||||
insertPromptContent(prompt.content);
|
||||
},
|
||||
[insertPromptContent]
|
||||
);
|
||||
|
||||
return {
|
||||
capabilityAvailable,
|
||||
canReorder,
|
||||
close,
|
||||
closeDialog,
|
||||
deletePrompt,
|
||||
filteredPrompts,
|
||||
isDeleting,
|
||||
isEditorOpen: effectiveMode === "create" || effectiveMode === "edit",
|
||||
isPopoverOpen: effectiveMode === "popover",
|
||||
isSaving,
|
||||
isInteractionLocked,
|
||||
isReordering,
|
||||
initialDraft,
|
||||
insertionError,
|
||||
labels,
|
||||
mode: effectiveMode,
|
||||
mutationError,
|
||||
openCreate,
|
||||
openEdit,
|
||||
openPopover,
|
||||
promptToDelete,
|
||||
retry,
|
||||
reorderCapabilityAvailable,
|
||||
reorderError,
|
||||
reorderPrompts,
|
||||
saveDraft,
|
||||
searchQuery,
|
||||
showReorderHandles,
|
||||
selectPrompt,
|
||||
selectedPrompt,
|
||||
setPopoverOpen,
|
||||
setSearchQuery: updateSearchQuery,
|
||||
snapshot,
|
||||
submitDelete
|
||||
};
|
||||
}
|
||||
|
||||
function isOrderConflict(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
error.code === "agent_quick_prompt_conflict" &&
|
||||
"reason" in error &&
|
||||
(error.reason === "agent_quick_prompt_order_conflict" ||
|
||||
error.reason === "agent_quick_prompt_version_conflict")
|
||||
);
|
||||
}
|
||||
|
||||
function selectQuickPromptSnapshot(
|
||||
snapshot: AgentHostQuickPromptSnapshot
|
||||
): AgentHostQuickPromptSnapshot {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
function isVersionConflict(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
error.code === "agent_quick_prompt_conflict" &&
|
||||
"reason" in error &&
|
||||
error.reason === "agent_quick_prompt_version_conflict"
|
||||
);
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { type MouseEvent, type PointerEvent, useRef } from "react";
|
||||
|
||||
export interface PrimaryPointerAction {
|
||||
onClick: (event: MouseEvent<HTMLButtonElement>) => void;
|
||||
onPointerDown: (event: PointerEvent<HTMLButtonElement>) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs mouse actions before a surrounding Popover can dismiss, while leaving
|
||||
* touch and pen activation cancellable until the browser emits a click.
|
||||
*/
|
||||
export function usePrimaryPointerAction(
|
||||
action: () => void
|
||||
): PrimaryPointerAction {
|
||||
const mouseActionRequestedRef = useRef(false);
|
||||
|
||||
return {
|
||||
onPointerDown: (event) => {
|
||||
if (event.button !== 0) return;
|
||||
if (event.pointerType && event.pointerType !== "mouse") {
|
||||
mouseActionRequestedRef.current = false;
|
||||
return;
|
||||
}
|
||||
mouseActionRequestedRef.current = true;
|
||||
event.preventDefault();
|
||||
action();
|
||||
},
|
||||
onClick: (event) => {
|
||||
if (event.detail === 0) {
|
||||
action();
|
||||
return;
|
||||
}
|
||||
if (mouseActionRequestedRef.current) {
|
||||
mouseActionRequestedRef.current = false;
|
||||
return;
|
||||
}
|
||||
action();
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user