A local-first multi-agent app development platform, built on PenguinHarness
feat(web): the shared "Create with AI" kit (#583)
Yaowei Zheng946513ef37ea
diff --git a/changelog/unreleased/2026-09-02-create-with-ai-kit.md b/changelog/unreleased/2026-09-02-create-with-ai-kit.mdnew file mode 100644index 00000000..c3642e64--- /dev/null+++ b/changelog/unreleased/2026-09-02-create-with-ai-kit.md@@ -0,0 +1,20 @@+# A shared "Create with AI" kit for the Web App++- **Date:** 2026-09-02+- **Type:** feature+- **Scope:** `web`, `docs`+- **PR:** [#583](https://github.com/Prism-Shadow/penguin-harness/pull/583)++[中文版](2026-09-02-create-with-ai-kit.zh.md)++Every object the Web App creates from a form is getting a second path: describe it to an agent. This change added the reusable kit behind that path — the pair of buttons that opens either path, the prompt panel with clickable examples and a folded full-prompt preview, and the dialog that hands the composed prompt to the Project's default agent as a prefilled draft in a new conversation. The creation surfaces wire it up in their own changes.++## Details++- `features/ai-create` exports the bridge hook (`useAiBridge`), the pure draft builder, the default-agent pick (`default_agent`, else the first agent), the prompt composer, `AiCreatePanel`, `AiCreateModal` and `CreateButtons`; the `MAGIC_WAND_ICON` and `HAND_ICON` glyphs joined `components/ui/icons.tsx`.+- `CreateButtons` renders two separate buttons rather than a split control or a mode switch: the accented **Create with AI** with the wand, then the plain **Create manually** with the hand. Both paths stay visible at once, and a surface that offers no manual path simply omits the second button.+- The dialog has one way out — **Edit in a new conversation** — and nothing is ever sent automatically: the composed prompt lands in the new conversation's composer, and pressing Send stays the user's own action.+- The Skills tab's import-via-chat and the Memory tab's add / edit-via-chat jumps go through the same bridge; the Memory tab's jump now also parks typed-but-unsent draft text instead of overwriting it.+- The prompt box is set in the smaller of the two control sizes, so a long draft stays readable in the dialog, and the **Full prompt** preview opens flush with the examples above it (`HelpFold` gained `flush` for a body that is a block rather than a run of prose).+- A composed prompt no longer outlives the draft it seeds. It goes into the draft cache marked as composed rather than typed: leaving the draft page without editing or sending it clears the slot (model carry-over only, as a send does), and a later jump drops it instead of parking it as a draft conversation. The first edit makes it the user's own text, cached and parked like any other draft.+- The Web App docs describe the pattern in both languages.diff --git a/changelog/unreleased/2026-09-02-create-with-ai-kit.zh.md b/changelog/unreleased/2026-09-02-create-with-ai-kit.zh.mdnew file mode 100644index 00000000..67d8ecb6--- /dev/null+++ b/changelog/unreleased/2026-09-02-create-with-ai-kit.zh.md@@ -0,0 +1,20 @@+# Web App 共用的「用 AI 创建」组件包++- **Date:** 2026-09-02+- **Type:** feature+- **Scope:** `web`, `docs`+- **PR:** [#583](https://github.com/Prism-Shadow/penguin-harness/pull/583)++[English](2026-09-02-create-with-ai-kit.md)++Web App 里凡是通过表单创建的对象,都将多出第二条路径:向 Agent 描述它。本次改动加入了这条路径背后可复用的组件包——分别通向两条路径的一对按钮、带可点击示例与折叠完整提示词预览的提示词面板,以及把拼好的提示词交给 Project 默认 Agent、在新对话里预填为草稿的弹窗。各创建页面在各自的改动中接入。++## 细节++- `features/ai-create` 导出桥接 hook(`useAiBridge`)、纯函数的草稿构造、默认 Agent 的选取(`default_agent`,否则取第一个)、提示词拼接、`AiCreatePanel`、`AiCreateModal` 与 `CreateButtons`;`MAGIC_WAND_ICON` 与 `HAND_ICON` 字形加入 `components/ui/icons.tsx`。+- `CreateButtons` 渲染两个分开的按钮,而不是分体式控件或模式切换:先是带魔法棒、取强调色的**用 AI 创建**,再是浅色带手形的**手动创建**。两条路径同时可见;不提供手动路径的页面省去第二个按钮即可。+- 弹窗只有一个出口——**在新对话中编辑**,且不会自动发送任何内容:拼好的提示词落进新对话的输入框,按下发送始终是用户自己的动作。+- 技能标签页的「经对话导入」与记忆标签页的「经对话新增 / 编辑」跳转改走同一座桥;记忆标签页的跳转现在也会先把已输入未发送的草稿文本停放起来,而不是覆盖它。+- 提示词输入框改用较小的控件字号,长草稿在弹窗里也看得清;**完整提示词**预览展开后与上方示例左对齐(`HelpFold` 新增 `flush`,供正文是一个块而非一段散文时使用)。+- 拼好的提示词不再比它所引出的草稿活得更久。它写入草稿缓存时带上「由 AI 拼成、非用户键入」的标记:既不编辑也不发送就离开草稿页时清空该槽位(只保留模型延续,与发送后一致),后续再次跳转时直接丢弃、而不是把它停放为一条草稿对话。用户一旦编辑,它就成为用户自己的文本,与其他草稿一样缓存与停放。+- Web App 文档以双语描述了该模式。diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex 354764c2..95f4e6cd 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -97,6 +97,10 @@ Because the Agent writes to the same Workspace, a file can change while you areUploads go into the current directory (the toolbar's **Upload** button, several files at a time), or files can be **dragged from the desktop onto the panel**: a dashed frame names the directory they will land in, dropping onto a folder row uploads into that folder (the row highlights while the drag is over it), and the first uploaded file opens afterwards. Each file is limited to 14MB — oversize picks are named and skipped before anything is read — and a same-named file in the target directory is overwritten after confirmation. Download is in the preview header.+## Create with AI++Everything the Web App creates from a form — an agent, a model group, a Benchmark, a scheduled task, a vault secret, a hook import, an app, an agent import — can also be described to an agent instead. Each page offers two buttons side by side: **Create with AI** with the magic wand, and **Create manually** with the hand, so both paths are visible at once. The prompt box comes with clickable examples that fill the draft, and a folded **Full prompt** preview shows the fixed instructions that travel with what you typed, with a copy button. There is one way out, **Edit in a new conversation**: it opens a new conversation with the Project's `default_agent` (the first agent when there is none) and prefills the composer with the prompt — whether to send it is yours to decide. A prefilled prompt is not something the browser holds on to: leave the page without editing or sending it and it is dropped, so it cannot resurface in a later conversation. Type into it and it becomes an ordinary draft, kept like anything else you write.+## Agent Management (/agents)The list page creates and deletes Agents — the create dialog can initialize the new agent from an exported Agent State snapshot package (name and description left empty keep the package's values, and plugin picking is unavailable then, since the package carries its own skills and hooks) — and clicking through opens the `/agents/:agentId` settings page, organized into tabs:diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex cf54f7fc..74609dec 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -96,6 +96,10 @@ Agent 写的是同一个 Workspace,你编辑期间文件可能被改动。每上传写入当前目录(工具栏的**上传**按钮,可一次多选),也可以把文件**从桌面拖到面板上**:虚线框会标出文件将落入的目录,拖到某个文件夹行上松开即上传到该文件夹(拖动经过时该行高亮),完成后自动打开第一个上传的文件。单个文件上限 14MB——超限的文件在读取前即被点名跳过——目标目录中已有同名文件时先确认再覆盖。下载按钮在预览标题栏。+## 用 AI 创建++Web App 里凡是通过表单创建的对象——Agent、模型分组、Benchmark、定时任务、密钥保险柜条目、钩子导入、应用、Agent 导入——都可以改为向 Agent 描述。每个页面并排给出两个按钮:带魔法棒的**用 AI 创建**与带手形的**手动创建**,两条路径同时可见。提示词框自带可点击的示例,点一下即填入草稿;折叠的**完整提示词**预览展示随你的输入一起发送的固定说明,并带复制按钮。唯一的出口是**在新对话中编辑**:以 Project 的 `default_agent`(没有时取第一个 Agent)开启新对话,把提示词预填进输入框,发不发送由你决定。预填的提示词不会被浏览器留下:不作修改也不发送就离开该页面,它随即被丢弃,不会在之后的对话里再冒出来;一旦动手编辑,它就成为普通草稿,与你自己写的内容一样保留。+## Agent 管理(/agents)列表页支持创建与删除 Agent——创建弹窗可选从导出的 Agent State 快照包直接初始化(名称与描述留空沿用包内值;此时技能选择不可用,包自带技能);点击进入 `/agents/:agentId` 设置页,按标签页组织:diff --git a/packages/web/src/components/ui/help-fold.tsx b/packages/web/src/components/ui/help-fold.tsxindex 42c9cbde..52340c5b 100644--- a/packages/web/src/components/ui/help-fold.tsx+++ b/packages/web/src/components/ui/help-fold.tsx@@ -32,6 +32,7 @@ export function HelpFold({children,label,title,+ flush,className = "",}: {/** The explanation. Revealed only on request — a description that shows up uninvited is what this replaces. */@@ -49,6 +50,11 @@ export function HelpFold({* it: two names for one trigger is what breaks "label in name".*/title?: string;+ /**+ * The body lines up with the trigger's left edge instead of under its label — for a block, such+ * as a code box, rather than a run of prose.+ */+ flush?: boolean;className?: string;}) {const [open, setOpen] = useState(false);@@ -74,7 +80,7 @@ export function HelpFold({<divid={panelId}hidden={!open}- className="mt-1.5 pl-4.5 text-xs leading-relaxed text-gray-500 dark:text-gray-400"+ className={`mt-1.5 ${flush ? "" : "pl-4.5"} text-xs leading-relaxed text-gray-500 dark:text-gray-400`}>{children}</div>diff --git a/packages/web/src/components/ui/icons.tsx b/packages/web/src/components/ui/icons.tsxindex 1892d8fb..0078fd1f 100644--- a/packages/web/src/components/ui/icons.tsx+++ b/packages/web/src/components/ui/icons.tsx@@ -235,6 +235,18 @@ export const HOOK_ICON =export const PLUGIN_ICON ="M19.439 7.85c-.049.322.059.648.289.878l1.568 1.568c.47.47.706 1.087.706 1.704s-.235 1.233-.706 1.704l-1.611 1.611a.98.98 0 0 1-.837.276c-.47-.07-.802-.48-.968-.925a2.501 2.501 0 1 0-3.214 3.214c.446.166.855.497.925.968a.979.979 0 0 1-.276.837l-1.61 1.61a2.404 2.404 0 0 1-1.705.707 2.402 2.402 0 0 1-1.704-.706l-1.568-1.568a1.026 1.026 0 0 0-.877-.29c-.493.074-.84.504-1.02.968a2.5 2.5 0 1 1-3.237-3.237c.464-.18.894-.527.967-1.02a1.026 1.026 0 0 0-.289-.877l-1.568-1.568A2.402 2.402 0 0 1 1.998 12c0-.617.236-1.234.706-1.704L4.23 8.77c.24-.24.581-.353.917-.303.515.077.877.528 1.073 1.01a2.5 2.5 0 1 0 3.259-3.259c-.482-.196-.933-.558-1.01-1.073-.05-.336.062-.676.303-.917l1.525-1.525A2.402 2.402 0 0 1 12 1.998c.617 0 1.234.236 1.704.706l1.568 1.568c.23.23.556.338.877.29.493-.074.84-.504 1.02-.968a2.5 2.5 0 1 1 3.237 3.237c-.464.18-.894.527-.967 1.02Z";+/**+ * Magic wand with sparkles (after lucide's wand-sparkles, reduced to two sparkles so it still+ * reads at 13px): the mark of "Create with AI" wherever an object can be described to the agent+ * instead of configured by hand — the AI half of the create pair and the dialog's exit.+ */+export const MAGIC_WAND_ICON =+ "M21.64 3.64l-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72zM14 7l3 3M5 6v4M3 8h4M19 14v4M17 16h4";++/** An open hand — the "do it by hand" mark beside the wand, on the 24×24 grid. */+export const HAND_ICON =+ "M18 11V6a2 2 0 0 0-4 0M14 10V4a2 2 0 0 0-4 0v2M10 10.5V6a2 2 0 0 0-4 0v8M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15";+export const NAV_ICONS = {agents: AGENT_GROUP_ICON,/** Plugin library (the puzzle piece). */diff --git a/packages/web/src/features/agents/memory-tab.tsx b/packages/web/src/features/agents/memory-tab.tsxindex 807656db..841c0c27 100644--- a/packages/web/src/features/agents/memory-tab.tsx+++ b/packages/web/src/features/agents/memory-tab.tsx@@ -23,7 +23,6 @@*/import { useCallback, useEffect, useRef, useState } from "react";import type { ChangeEvent, RefObject } from "react";-import { useNavigate } from "react-router";import type {MemoryFileInfo,MemoryImportMode,@@ -55,8 +54,7 @@ import { ConfirmModal, useSaveConfirm } from "../../components/ui/confirm-modal"import { SkeletonList } from "../../components/ui/skeleton";import { toastError, toastSuccess } from "../../components/ui/toast";import { Md } from "../chat/md";-import { DRAFT_SESSION_ID } from "../chat/chat-page";-import { draftKey, loadDraft, saveDraft } from "../chat/draft-cache";+import { useAiBridge } from "../ai-create";import { buildMemoryAddPrompt, buildMemoryEditPrompt } from "./memory-chat-prompts";import {MemoryDocumentError,@@ -139,10 +137,10 @@ export function MemoryTab({/** Config writes happen here directly, so the settings page must refetch its own copy — otherwise a later Prompt-tab save from stale data would silently revert them (e.g. the inserted placeholder). */onConfigChanged?: () => void;}) {- const navigate = useNavigate();+ const { openAiChat } = useAiBridge();const { locale } = useLocale();const userId = useAuth().user?.userId ?? null;- const { currentProject, setCurrentAgentId, reloadAgents } = useProject();+ const { currentProject, reloadAgents } = useProject();const projectId = currentProject?.projectId ?? null;// Import writes a whole group at once, so it follows the Agent State snapshot's owner gate;// the server enforces it either way, this only keeps the control out of a member's reach.@@ -354,28 +352,15 @@ export function MemoryTab({const editCopy = useCopied();/**- * The bridge-to-chat jump shared by edit and add: prefill the draft (merging over what is- * already cached, clearing a stale `/agent` handoff chip that would forward the prompt to a- * different Agent), pin this Agent — and for a Workspace scope pin that Workspace too, so the+ * The bridge-to-chat jump shared by edit and add: the AI bridge prefills the draft with the+ * prompt and pins this Agent — and for a Workspace scope pins that Workspace too, so the* Session reads the very index it is about to change.*/const openChatWithDraft = (text: string, workspacePath: string | undefined) => {- if (!userId || !projectId) return;- const key = draftKey(userId, projectId);- saveDraft(key, {- ...loadDraft(key),+ openAiChat({agentId,text,...(workspacePath !== undefined ? { workspace: workspacePath } : {}),- skills: [],- handoffAgentId: undefined,- });- setCurrentAgentId(agentId);- navigate(`/chat/${DRAFT_SESSION_ID}`, {- state: {- agentId,- ...(workspacePath !== undefined ? { workspace: workspacePath } : {}),- },});};diff --git a/packages/web/src/features/agents/skills-tab.tsx b/packages/web/src/features/agents/skills-tab.tsxindex 2616bfd1..7d2e8925 100644--- a/packages/web/src/features/agents/skills-tab.tsx+++ b/packages/web/src/features/agents/skills-tab.tsx@@ -25,7 +25,6 @@ import * as api from "../../api/endpoints";import { ApiError } from "../../api/client";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";-import { useAuth } from "../../state/auth";import { useLocale } from "../../state/locale";import { agentDisplayName, useProject } from "../../state/project";import { Button } from "../../components/ui/button";@@ -42,8 +41,7 @@ import { toastError, toastSuccess } from "../../components/ui/toast";import { SkillTile } from "../skills/skill-icon-view";import { localizedShortText } from "../chat/skill-use";import { DRAFT_SESSION_ID } from "../chat/chat-page";-import { draftKey, loadDraft, saveDraft } from "../chat/draft-cache";-import { parkActiveDraft } from "../chat/draft-sessions";+import { useAiBridge } from "../ai-create";import { buildImportPrompt } from "./skill-import-source";import { usePromptInjection } from "./prompt-injection-controls";import { HelpFold } from "../../components/ui/help-fold";@@ -74,8 +72,8 @@ export function SkillsTab({onConfigChanged?: () => void;}) {const navigate = useNavigate();+ const { openAiChat } = useAiBridge();const { locale } = useLocale();- const userId = useAuth().user?.userId ?? null;const { currentProject, agents, setCurrentAgentId, reloadAgents } = useProject();const projectId = currentProject?.projectId ?? null;// Prompt-injection controls (toggle / template alert / prompt editor): member-level like@@ -206,25 +204,14 @@ export function SkillsTab({/*** "Open a new chat" with this Agent: the same draft-state entry as the agents page- * "New Chat" button. A non-empty source also prefills the composer with the generated- * install prompt through the draft cache — the mechanism the skill library's quick- * invoke already uses, so draft-view itself needs no changes. handoffAgentId is- * cleared (a leftover handoff target would forward the install prompt to a different- * Agent) and the skill pre-selection reset alongside the overwritten text.+ * "New Chat" button. A non-empty source goes through the AI bridge instead, which prefills+ * the composer with the generated install prompt (parking typed-but-unsent draft text+ * first) and clears a stale handoff target and skill pre-selection along with it.*/const openChat = () => {- if (userId && projectId && trimmedSource) {- // Typed-but-unsent draft text becomes a parked draft conversation instead of being- // clobbered by the canned import prompt (draft-sessions.ts).- parkActiveDraft(userId, projectId);- const key = draftKey(userId, projectId);- saveDraft(key, {- ...loadDraft(key),- agentId,- text: buildImportPrompt(trimmedSource),- skills: [],- handoffAgentId: undefined,- });+ if (trimmedSource) {+ openAiChat({ agentId, text: buildImportPrompt(trimmedSource) });+ return;}setCurrentAgentId(agentId);navigate(`/chat/${DRAFT_SESSION_ID}`, { state: { agentId } });diff --git a/packages/web/src/features/ai-create/ai-bridge.ts b/packages/web/src/features/ai-create/ai-bridge.tsnew file mode 100644index 00000000..180c18d4--- /dev/null+++ b/packages/web/src/features/ai-create/ai-bridge.ts@@ -0,0 +1,87 @@+/**+ * The bridge from a "Create with AI" surface into a new conversation. The prompt is written into+ * the active new-chat draft (the cache draft-view reads on mount), the requested agent becomes+ * the current one, and the route jumps to the draft page with the request in location.state.+ * Nothing is ever submitted here: the prompt lands in the composer and sending stays the user's+ * action, so what reaches the model is always something a person read and pressed Send on.+ *+ * Typed-but-unsent text in the active draft is parked first (draft-sessions.ts) rather than+ * overwritten by the canned prompt, and the model selection carries over, as it does across+ * sends. The composed prompt itself is written as `aiPrefill` (draft-cache.ts) so that it dies+ * with the draft it seeds: nobody typed it, so it is never parked in turn, and leaving the draft+ * page without editing or sending it clears the slot.+ */+import { useCallback } from "react";+import { useNavigate } from "react-router";+import { useAuth } from "../../state/auth";+import { useProject } from "../../state/project";+import { DRAFT_SESSION_ID } from "../chat/chat-page";+import { draftKey, loadDraft, saveDraft } from "../chat/draft-cache";+import type { DraftCache } from "../chat/draft-cache";+import { parkActiveDraft } from "../chat/draft-sessions";++export interface AiChatRequest {+ /** The agent that does the work (normally pickDefaultAgent's choice). */+ agentId: string;+ /** The whole prompt, instruction tail included (composeAiPrompt). */+ text: string;+ /** Pins the draft's Workspace ("" is the temporary Workspace); absent, the draft keeps its cached choice. */+ workspace?: string;+ /** Skills to preselect in the composer; absent or empty clears a stale selection. */+ skills?: string[];+}++/** What the draft page finds in `location.state` after openAiChat. */+export interface AiChatRouteState {+ agentId: string;+ workspace?: string;+}++/**+ * The draft cache entry for a request, merged over what the active slot holds so the model+ * carry-over survives. A leftover `/agent` handoff chip is dropped: it would forward the prompt+ * to a different agent than the one named here. The text is marked as composed rather than typed+ * (`aiPrefill`, see draft-cache.ts), which is what keeps it from outliving the draft it seeds.+ */+export function buildAiDraft(existing: DraftCache, req: AiChatRequest): DraftCache {+ const draft: DraftCache = {+ ...existing,+ agentId: req.agentId,+ text: req.text,+ skills: req.skills ?? [],+ aiPrefill: true,+ };+ if (req.workspace !== undefined) draft.workspace = req.workspace;+ delete draft.handoffAgentId;+ return draft;+}++/** The route state carried to the draft page: only what was asked for, so a request that pins no Workspace leaves no `workspace` key behind. */+export function aiChatRouteState(req: AiChatRequest): AiChatRouteState {+ return {+ agentId: req.agentId,+ ...(req.workspace !== undefined ? { workspace: req.workspace } : {}),+ };+}++export function useAiBridge(): { openAiChat: (req: AiChatRequest) => void } {+ const navigate = useNavigate();+ const userId = useAuth().user?.userId ?? null;+ const { currentProject, setCurrentAgentId } = useProject();+ const projectId = currentProject?.projectId ?? null;+ const openAiChat = useCallback(+ (req: AiChatRequest) => {+ // Without a user or Project there is no account-scoped cache slot to write; the jump still+ // happens, landing on an empty draft for the agent.+ if (userId && projectId) {+ parkActiveDraft(userId, projectId);+ const key = draftKey(userId, projectId);+ saveDraft(key, buildAiDraft(loadDraft(key), req));+ }+ setCurrentAgentId(req.agentId);+ navigate(`/chat/${DRAFT_SESSION_ID}`, { state: aiChatRouteState(req) });+ },+ [userId, projectId, setCurrentAgentId, navigate],+ );+ return { openAiChat };+}diff --git a/packages/web/src/features/ai-create/ai-create-modal.tsx b/packages/web/src/features/ai-create/ai-create-modal.tsxnew file mode 100644index 00000000..64f7f090--- /dev/null+++ b/packages/web/src/features/ai-create/ai-create-modal.tsx@@ -0,0 +1,111 @@+/**+ * "Create with AI" as a dialog: AiCreatePanel plus one way out — the prompt lands in a new+ * conversation's composer, prefilled, for the user to read, edit and send. The dialog never+ * sends anything itself, so no surface has to weigh whether its prompt is safe to submit unread.+ * It owns the draft and the agent pick, and mounts its body fresh on every open, so a reopened+ * dialog starts from `initialValue` again.+ */+import { useState } from "react";+import { S } from "../../lib/strings";+import { Button } from "../../components/ui/button";+import { GlyphIcon } from "../../components/ui/glyph-icon";+import { MAGIC_WAND_ICON } from "../../components/ui/icons";+import { Modal } from "../../components/ui/modal";+import { useAiBridge } from "./ai-bridge";+import { AiCreatePanel } from "./ai-create-panel";+import type { AiCreatePanelProps } from "./ai-create-panel";+import { composeAiPrompt } from "./ai-create-prompt";+import { pickDefaultAgent } from "./default-agent";++export interface AiCreateModalProps extends Omit<+ AiCreatePanelProps,+ "value" | "onChange" | "agentId" | "onAgentChange"+> {+ open: boolean;+ onClose: () => void;+ title: string;+ /** One line under the title saying what the agent will create. */+ description?: string;+ /** Seeds the draft each time the dialog opens. */+ initialValue?: string;+ /** The preselected agent; defaults to pickDefaultAgent(agents). */+ agentId?: string | null;+ /** Pins the new conversation's Workspace ("" is the temporary Workspace). */+ workspace?: string;+ /** Skills to preselect in the new conversation's composer. */+ skills?: string[];+}++export function AiCreateModal(props: AiCreateModalProps) {+ // Mounted only while open, so the body's state (draft, agent pick) starts fresh every time.+ return props.open ? <AiCreateDialog {...props} /> : null;+}++function AiCreateDialog({+ open,+ onClose,+ title,+ description,+ initialValue,+ agentId: initialAgentId,+ workspace,+ skills,+ tail,+ agents,+ ...panel+}: AiCreateModalProps) {+ const { openAiChat } = useAiBridge();+ const [value, setValue] = useState(initialValue ?? "");+ const [picked, setPicked] = useState<string | null>(null);+ // An explicit pick wins, then the caller's choice, then the Project's default agent — resolved+ // on every render, so an agent list that loads after the dialog opened still yields one.+ const agentId = picked ?? initialAgentId ?? pickDefaultAgent(agents)?.agentId ?? null;+ const ready = agentId !== null && value.trim() !== "";++ const go = () => {+ if (agentId === null) return;+ openAiChat({+ agentId,+ text: composeAiPrompt(value, tail),+ ...(workspace !== undefined ? { workspace } : {}),+ ...(skills !== undefined ? { skills } : {}),+ });+ onClose();+ };++ return (+ <Modal+ open={open}+ title={title}+ onClose={onClose}+ widthClass="sm:max-w-xl"+ footer={+ <>+ <Button onClick={onClose}>{S.common.cancel}</Button>+ {/*+ One exit, and its label says where the prompt goes rather than what happens to it:+ the wand marks it as the AI path, and pressing Send is still the user's own move on+ the next screen. Disabled until there is a prompt and an agent to take it.+ */}+ <Button variant="primary" disabled={!ready} onClick={go}>+ <GlyphIcon d={MAGIC_WAND_ICON} />+ {S.aiCreate.editInChat}+ </Button>+ </>+ }+ >+ {description !== undefined && (+ <p className="mb-3 text-sm text-gray-600 dark:text-gray-300">{description}</p>+ )}+ <AiCreatePanel+ {...panel}+ agents={agents}+ value={value}+ onChange={setValue}+ agentId={agentId}+ onAgentChange={setPicked}+ {...(tail !== undefined ? { tail } : {})}+ />+ </Modal>+ );+}diff --git a/packages/web/src/features/ai-create/ai-create-panel.tsx b/packages/web/src/features/ai-create/ai-create-panel.tsxnew file mode 100644index 00000000..7abeac3e--- /dev/null+++ b/packages/web/src/features/ai-create/ai-create-panel.tsx@@ -0,0 +1,173 @@+/**+ * The body of every "Create with AI" surface: who does the work, the prompt box, clickable+ * examples that fill it, and — when the surface appends a fixed instruction tail — a folded+ * preview of the full prompt with a copy button, so a novice sees exactly what is sent and an+ * expert can take it elsewhere. Controlled and embeddable: AiCreateModal wraps it in a dialog, a+ * page may inline it. It sends nothing itself.+ */+import { useLayoutEffect, useRef } from "react";+import type { ReactNode } from "react";+import type { AgentSummary } from "@prismshadow/penguin-server/api";+import { S } from "../../lib/strings";+import { toneInk } from "../../lib/tone";+import { agentDisplayName } from "../../state/project";+import { CopyButton } from "../../components/ui/copy-button";+import { HelpFold } from "../../components/ui/help-fold";+import { Textarea } from "../../components/ui/input";+import { Select } from "../../components/ui/select";+import { composeAiPrompt } from "./ai-create-prompt";++export interface AiExample {+ key: string;+ label: string;+ /** One muted line under the label. */+ description?: string;+ /** Replaces the draft when the example is clicked. */+ prompt: string;+}++export interface AiCreatePanelProps {+ value: string;+ onChange: (value: string) => void;+ placeholder?: string;+ /** Rendered above everything else — a HelpFold or a short lead. */+ intro?: ReactNode;+ examples: AiExample[];+ /** The surface's fixed instruction tail, joined after the draft (composeAiPrompt) and previewed in the fold. */+ tail?: string;+ agents: readonly AgentSummary[];+ agentId: string | null;+ onAgentChange?: (agentId: string) => void;+ /** Offer a picker beside the "done by" line instead of a fixed agent; needs onAgentChange. */+ allowAgentChoice?: boolean;+ disabled?: boolean;+}++/** Minimum height of the prompt box, in rows; it grows with its content beyond that. */+const MIN_ROWS = 6;++const exampleClass =+ "min-w-0 rounded-md border px-2.5 py-1.5 text-left transition-colors duration-150 " ++ "disabled:cursor-not-allowed disabled:opacity-60";+const exampleIdleClass =+ "border-gray-200 hover:bg-gray-50 dark:border-gray-800 dark:hover:bg-gray-800/70";+const exampleSelectedClass = "border-gray-900 bg-gray-50 dark:border-gray-200 dark:bg-gray-800";++export function AiCreatePanel({+ value,+ onChange,+ placeholder,+ intro,+ examples,+ tail,+ agents,+ agentId,+ onAgentChange,+ allowAgentChoice,+ disabled,+}: AiCreatePanelProps) {+ const agent = agents.find((a) => a.agentId === agentId) ?? null;+ const textareaRef = useRef<HTMLTextAreaElement>(null);+ // The height follows the rendered value — a seeded draft on mount, typing, an example click —+ // measured after the commit, as the composer sizes its own box. The border is added back+ // because scrollHeight measures the content box while the box is sized border-box.+ useLayoutEffect(() => {+ const el = textareaRef.current;+ if (!el) return;+ el.style.height = "auto";+ el.style.height = `${el.scrollHeight + el.offsetHeight - el.clientHeight}px`;+ }, [value]);+ const fullPrompt = tail !== undefined && tail.trim() !== "" ? composeAiPrompt(value, tail) : null;+ const picker = allowAgentChoice && onAgentChange !== undefined && agents.length > 0;++ return (+ <div className="space-y-3">+ {intro !== undefined && (+ <div className="text-xs text-gray-500 dark:text-gray-400">{intro}</div>+ )}++ <div className="flex flex-wrap items-center gap-2 text-sm text-gray-600 dark:text-gray-300">+ {agent !== null ? (+ <span>{S.aiCreate.byAgent(agentDisplayName(agent))}</span>+ ) : agents.length === 0 ? (+ <span className={toneInk.attention}>{S.aiCreate.noAgent}</span>+ ) : null}+ {picker && (+ <div className="ml-auto w-44">+ <Select+ size="sm"+ aria-label={S.aiCreate.chooseAgent}+ value={agentId ?? ""}+ disabled={disabled}+ onChange={(e) => onAgentChange(e.target.value)}+ >+ {agents.map((a) => (+ <option key={a.agentId} value={a.agentId}>+ {agentDisplayName(a)}+ </option>+ ))}+ </Select>+ </div>+ )}+ </div>++ <Textarea+ ref={textareaRef}+ rows={MIN_ROWS}+ size="sm"+ value={value}+ placeholder={placeholder ?? S.aiCreate.placeholder}+ aria-label={S.aiCreate.promptLabel}+ disabled={disabled}+ className="max-h-[40vh] resize-none"+ onChange={(e) => onChange(e.target.value)}+ />++ {examples.length > 0 && (+ <div>+ <div className="mb-1.5 text-xs font-medium text-gray-500 dark:text-gray-400">+ {S.aiCreate.examplesTitle}+ </div>+ <div className="grid grid-cols-1 gap-1.5 sm:grid-cols-2">+ {examples.map((ex) => {+ // Selected while the draft still IS the example; the first edit unselects it.+ const selected = value === ex.prompt;+ return (+ <button+ key={ex.key}+ type="button"+ aria-pressed={selected}+ disabled={disabled}+ onClick={() => onChange(ex.prompt)}+ className={`${exampleClass} ${selected ? exampleSelectedClass : exampleIdleClass}`}+ >+ <div className="truncate text-xs font-medium text-gray-800 dark:text-gray-100">+ {ex.label}+ </div>+ {ex.description !== undefined && (+ <div className="truncate text-[11px] text-gray-500 dark:text-gray-400">+ {ex.description}+ </div>+ )}+ </button>+ );+ })}+ </div>+ </div>+ )}++ {fullPrompt !== null && (+ <HelpFold title={S.aiCreate.fullPrompt} flush>+ <div className="relative">+ <pre className="max-h-48 overflow-auto rounded-md border border-gray-200 bg-gray-50 p-2 pr-8 font-sans text-xs leading-relaxed whitespace-pre-wrap text-gray-700 dark:border-gray-800 dark:bg-gray-950 dark:text-gray-300">+ {fullPrompt}+ </pre>+ <div className="absolute top-1.5 right-1.5">+ <CopyButton text={fullPrompt} label={S.aiCreate.copyPrompt} />+ </div>+ </div>+ </HelpFold>+ )}+ </div>+ );+}diff --git a/packages/web/src/features/ai-create/ai-create-prompt.ts b/packages/web/src/features/ai-create/ai-create-prompt.tsnew file mode 100644index 00000000..e1cada7c--- /dev/null+++ b/packages/web/src/features/ai-create/ai-create-prompt.ts@@ -0,0 +1,13 @@+/**+ * The prompt a "Create with AI" surface sends: the user's draft, then the surface's fixed+ * instruction tail after one blank line. The tail is what turns a novice's one-liner into+ * something the agent can act on (which object to create, where it lives, what to confirm),+ * so the panel previews it instead of appending it silently.+ */+export function composeAiPrompt(draft: string, tail?: string): string {+ const body = draft.trim();+ const fixed = tail?.trim() ?? "";+ if (fixed === "") return body;+ if (body === "") return fixed;+ return `${body}\n\n${fixed}`;+}diff --git a/packages/web/src/features/ai-create/create-buttons.tsx b/packages/web/src/features/ai-create/create-buttons.tsxnew file mode 100644index 00000000..03dd38b7--- /dev/null+++ b/packages/web/src/features/ai-create/create-buttons.tsx@@ -0,0 +1,48 @@+/**+ * The header control of every creatable object: two separate buttons, not a split control, a+ * caret menu or a mode switch. Both paths are then visible at once and neither hides behind the+ * other — the reader chooses between two things they can see, instead of discovering the second+ * one inside the first. The wand button always carries the accent and the hand button never+ * does, so the pair reads the same on every page.+ */+import { S } from "../../lib/strings";+import { Button } from "../../components/ui/button";+import { GlyphIcon } from "../../components/ui/glyph-icon";+import { HAND_ICON, MAGIC_WAND_ICON } from "../../components/ui/icons";++export interface CreateButtonsProps {+ onAi: () => void;+ /** Absent: the manual path is not offered on this surface (a member who may not write the form's target still gets the AI path). */+ onManual?: () => void;+ size?: "sm" | "md";+ /** Labels when the object has its own verb ("Import with AI" / "Import manually"); default S.aiCreate.withAi / S.aiCreate.manual. */+ aiLabel?: string;+ manualLabel?: string;+ disabled?: boolean;+ className?: string;+}++export function CreateButtons({+ onAi,+ onManual,+ size = "md",+ aiLabel,+ manualLabel,+ disabled,+ className,+}: CreateButtonsProps) {+ return (+ <div className={`flex flex-wrap items-center gap-2 ${className ?? ""}`}>+ <Button size={size} variant="primary" disabled={disabled} onClick={onAi}>+ <GlyphIcon d={MAGIC_WAND_ICON} />+ {aiLabel ?? S.aiCreate.withAi}+ </Button>+ {onManual !== undefined && (+ <Button size={size} variant="secondary" disabled={disabled} onClick={onManual}>+ <GlyphIcon d={HAND_ICON} />+ {manualLabel ?? S.aiCreate.manual}+ </Button>+ )}+ </div>+ );+}diff --git a/packages/web/src/features/ai-create/default-agent.ts b/packages/web/src/features/ai-create/default-agent.tsnew file mode 100644index 00000000..d4265e6f--- /dev/null+++ b/packages/web/src/features/ai-create/default-agent.ts@@ -0,0 +1,17 @@+/**+ * Which agent a "Create with AI" surface hands its prompt to when the caller names none.+ *+ * The built-in `default_agent` wins over the first agent in the list because it is the one+ * that carries the preinstalled plugin library — agent-tuning, agent-development,+ * software-development — and the canned prompts are written against those skills: a prompt+ * asking for a new agent, a Benchmark or an app assumes the tools those plugins install, which+ * any other agent may lack. The first agent is the fallback for a Project whose default agent+ * was deleted; an empty list yields null and the caller disables sending.+ */+import type { AgentSummary } from "@prismshadow/penguin-server/api";++export const DEFAULT_AGENT_ID = "default_agent";++export function pickDefaultAgent(agents: readonly AgentSummary[]): AgentSummary | null {+ return agents.find((a) => a.agentId === DEFAULT_AGENT_ID) ?? agents[0] ?? null;+}diff --git a/packages/web/src/features/ai-create/index.ts b/packages/web/src/features/ai-create/index.tsnew file mode 100644index 00000000..a5c2d41c--- /dev/null+++ b/packages/web/src/features/ai-create/index.ts@@ -0,0 +1,15 @@+/**+ * The "Create with AI" kit: the bridge into a new conversation with the Project's default agent,+ * the prompt panel with its examples and full-prompt preview, the dialog around it, and the pair+ * of buttons — "Create with AI" beside "Create manually" — that opens either path.+ */+export { aiChatRouteState, buildAiDraft, useAiBridge } from "./ai-bridge";+export type { AiChatRequest, AiChatRouteState } from "./ai-bridge";+export { DEFAULT_AGENT_ID, pickDefaultAgent } from "./default-agent";+export { composeAiPrompt } from "./ai-create-prompt";+export { AiCreatePanel } from "./ai-create-panel";+export type { AiCreatePanelProps, AiExample } from "./ai-create-panel";+export { AiCreateModal } from "./ai-create-modal";+export type { AiCreateModalProps } from "./ai-create-modal";+export { CreateButtons } from "./create-buttons";+export type { CreateButtonsProps } from "./create-buttons";diff --git a/packages/web/src/features/chat/draft-cache.ts b/packages/web/src/features/chat/draft-cache.tsindex 66478a35..f1b39a01 100644--- a/packages/web/src/features/chat/draft-cache.ts+++ b/packages/web/src/features/chat/draft-cache.ts@@ -42,6 +42,15 @@ export interface DraftCache {* installed list once it's ready; cleared along with the entire draft on successful send.*/skills?: string[];+ /**+ * This text was composed by a "Create with AI" surface (features/ai-create/ai-bridge.ts), not+ * typed by anyone: it seeds exactly one draft and dies with it. The mark rides in the cache+ * because the draft page must survive a reload, and it makes the two owners of the slot treat+ * the prompt differently from user content — parkActiveDraft drops it instead of parking it as+ * a draft conversation, and the draft page clears the slot when it is left unedited and unsent.+ * Dropped by the first edit: from then on the text is the user's and is cached like any other.+ */+ aiPrefill?: true;}/** Minimal storage interface (a subset of localStorage). */@@ -100,6 +109,7 @@ export function draftFromUnknown(parsed: unknown): DraftCache {const skills = o.skills.filter((s): s is string => typeof s === "string");if (skills.length > 0) out.skills = skills;}+ if (o.aiPrefill === true) out.aiPrefill = true;if (typeof o.approvalMode === "string" &&APPROVAL_MODES.includes(o.approvalMode as ApprovalMode)diff --git a/packages/web/src/features/chat/draft-sessions.ts b/packages/web/src/features/chat/draft-sessions.tsindex 3da4ac30..7732962d 100644--- a/packages/web/src/features/chat/draft-sessions.ts+++ b/packages/web/src/features/chat/draft-sessions.ts@@ -134,6 +134,12 @@ const randomDraftId = (): string => `draft-${crypto.randomUUID().replace(/-/g, "* slot keeps only the model carry-over (mirroring discardDraft on a successful send).* Dispatches DRAFT_FLUSH_EVENT first so a mounted draft page's debounce-pending* keystrokes reach the cache before it is read.+ *+ * A prompt a "Create with AI" surface composed (`aiPrefill`, draft-cache.ts) is text nobody+ * typed: it is dropped rather than parked, so it never turns up in the sidebar as a draft+ * conversation the user has to recognise and delete. Dropping — rather than leaving it in+ * place — is what keeps the slot this function is vacating actually vacated: every caller goes+ * on to land on a fresh new-chat draft, which would otherwise read the stale prompt back.*/export function parkActiveDraft(userId: string,@@ -148,6 +154,11 @@ export function parkActiveDraft(// which never happens outside a browser (tests always inject a storage).const draft = loadDraft(activeKey, storage);if (!draft.text || draft.text.trim() === "") return null;+ if (draft.aiPrefill) {+ if (draft.modelRef) saveDraft(activeKey, { modelRef: draft.modelRef }, storage);+ else clearDraft(activeKey, storage);+ return null;+ }const key = draftSessionsKey(userId, projectId);const entry: DraftSessionEntry = {id: randomDraftId(),diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsxindex 408c5ce8..4832e48b 100644--- a/packages/web/src/features/chat/draft-view.tsx+++ b/packages/web/src/features/chat/draft-view.tsx@@ -18,6 +18,9 @@* the page resumes where you left off; on successful send the cache clears, except* the model selection, which carries over as the next conversation's default* (switch-becomes-default, mirroring the thinking level persisting on the Agent).+ * The one thing that does not resume is a prompt a "Create with AI" surface composed+ * (`aiPrefill`, draft-cache.ts): nobody typed it, so leaving this page without editing+ * or sending it clears the slot exactly as a send would (see dropAiPrefill).* The sidebar group header "+" / menu "New conversation" explicitly specify an* Agent via route state (overriding the cached selection); the workspace-mode* group header "+" additionally carries a Workspace path pre-filling the@@ -197,6 +200,13 @@ export function DraftView({);const [modelRef, setModelRef] = useState<ModelRefDto | null>(cached.modelRef ?? null);const textRef = useRef(cached.text ?? "");+ /**+ * The text came from a "Create with AI" surface rather than a keyboard (`aiPrefill`,+ * draft-cache.ts): it seeded this draft and dies with it. The mark rides in the cache so a+ * reload restores the same prefilled draft, and it is dropped by the first edit — from then on+ * the text is the user's and is cached, parked and kept exactly like any other draft.+ */+ const aiPrefillRef = useRef(cached.aiPrefill === true);/*** Selected skills (prefilled by "quick invoke" from the Skills page + checked in* the input area): passed to ChatInput as the initial selection via initialSkills@@ -251,7 +261,10 @@ export function DraftView({// on invalid value" effect would let the former write B in one render while the// latter, still judging by the stale closure's invalid value, writes the default// Agent and clobbers B.- const routeState = location.state as { agentId?: string; workspace?: string } | null;+ const routeState = location.state as {+ agentId?: string;+ workspace?: string;+ } | null;const stateAgentId = routeState?.agentId;const appliedStateKey = useRef<string | null>(null);/** One-shot marker for the project-default Agent (seeding precedence, see below). */@@ -507,6 +520,9 @@ export function DraftView({if (agentId) data.agentId = agentId;if (modelRef) data.modelRef = modelRef;if (skillsRef.current.length > 0) data.skills = skillsRef.current;+ // Carried through every write, so a reload finds the prefill still marked as composed+ // rather than resuming it as if it had been typed here.+ if (aiPrefillRef.current) data.aiPrefill = true;// A parked draft writes back into its own list entry; the active draft into its slot.if (draftId !== undefined) saveDraftSession(userId, projectId, draftId, data);else saveDraft(draftKey(userId, projectId), data);@@ -523,6 +539,9 @@ export function DraftView({const onTextChange = useCallback((text: string) => {textRef.current = text;+ // Editing an AI-composed prefill makes it the user's own text — an ordinary draft, kept+ // when the page is left and parkable like any other (see aiPrefillRef).+ aiPrefillRef.current = false;cancelPendingSave();saveTimer.current = window.setTimeout(() => {saveTimer.current = null;@@ -538,10 +557,31 @@ export function DraftView({persistRef.current();}, []);- // Unmount: if there's still unsaved body text, flush it (so a route change/page switch doesn't lose the last few keystrokes).+ /**+ * Leaving an AI-composed prefill the user neither edited nor sent: the slot is left exactly as+ * a successful send leaves it — model carry-over only — so the prompt cannot reappear in a+ * later new conversation, and the next "Create with AI" jump has nothing to park. Storage is+ * all this touches, deliberately: StrictMode runs the unmount cleanup once right after mount,+ * and the persist effect above then rewrites the slot from component state, which must still+ * describe the prefilled draft on screen.+ */+ const dropAiPrefill = useCallback(() => {+ if (!userId) return;+ if (modelRef) saveDraft(draftKey(userId, projectId), { modelRef });+ else clearDraft(draftKey(userId, projectId));+ }, [userId, projectId, modelRef]);+ /** Latest-closure mirror for the unmount cleanup (same convention as persistRef). */+ const dropAiPrefillRef = useRef(dropAiPrefill);+ dropAiPrefillRef.current = dropAiPrefill;++ // Unmount: drop an untouched AI prefill, or else flush still-unsaved body text (so a route+ // change/page switch doesn't lose the last few keystrokes). Exclusive by construction — a+ // pending save exists only after an edit, and an edit clears the prefill mark.useEffect(() => () => {- if (saveTimer.current !== null) {+ if (aiPrefillRef.current) {+ dropAiPrefillRef.current();+ } else if (saveTimer.current !== null) {window.clearTimeout(saveTimer.current);persistRef.current();}@@ -577,6 +617,8 @@ export function DraftView({cancelPendingSave();// Clear the preselected skills too: any subsequent write (e.g. the unmount flush) must not resurrect a selection that's already been sent.skillsRef.current = [];+ // A sent prefill has done its job; the unmount that follows has nothing left to drop.+ aiPrefillRef.current = false;// The unmount flush routes through persistNow, which would otherwise write the// just-sent content back (into the parked entry, resurrecting a deleted row): with// the text gone the flush becomes an idempotent empty-shell write.diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex ebea021c..5fe46acb 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -484,6 +484,23 @@ export const en: Strings = {later: "Later",},+ /** The "Create with AI" kit (features/ai-create): the pair of create buttons, the prompt panel and the bridge into a new conversation with the Project's default agent. */+ aiCreate: {+ withAi: "Create with AI",+ manual: "Create manually",+ editInChat: "Edit in a new conversation",+ copyPrompt: "Copy prompt",+ examplesTitle: "Try an example",+ fullPrompt: "Full prompt",+ /** Who does the work, and where: the panel's lead line. */+ byAgent: (name: string): string => `Done by ${name} in a new conversation`,+ chooseAgent: "Agent that does the work",+ placeholder: "Describe what you want — the more specific, the better",+ /** Accessible name of the prompt box (it has no visible label). */+ promptLabel: "Prompt",+ noAgent: "This Project has no agent yet",+ },+agent: {savedTakesEffect:"Saved. New conversations pick it up right away; running ones after their next compaction.",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex a9c52f0c..640541ea 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -481,6 +481,23 @@ export const zh = {later: "稍后再说",},+ /** The "Create with AI" kit (features/ai-create): the pair of create buttons, the prompt panel and the bridge into a new conversation with the Project's default agent. */+ aiCreate: {+ withAi: "用 AI 创建",+ manual: "手动创建",+ editInChat: "在新对话中编辑",+ copyPrompt: "复制提示词",+ examplesTitle: "试试这些示例",+ fullPrompt: "完整提示词",+ /** Who does the work, and where: the panel's lead line. */+ byAgent: (name: string): string => `将由「${name}」在新对话中完成`,+ chooseAgent: "执行的智能体",+ placeholder: "描述你想要什么,越具体越好",+ /** Accessible name of the prompt box (it has no visible label). */+ promptLabel: "提示词",+ noAgent: "当前 Project 还没有智能体",+ },+agent: {/*** Toast after a save on this page: when the change reaches a Session. Core assembles thediff --git a/packages/web/test/ai-bridge.test.ts b/packages/web/test/ai-bridge.test.tsnew file mode 100644index 00000000..a5db25f1--- /dev/null+++ b/packages/web/test/ai-bridge.test.ts@@ -0,0 +1,51 @@+/**+ * The pure half of the "Create with AI" bridge (src/features/ai-create/ai-bridge.ts): what the+ * draft cache and the route state hold once a surface hands its prompt to the draft page.+ */+import { describe, expect, it } from "vitest";+import { aiChatRouteState, buildAiDraft } from "../src/features/ai-create/ai-bridge";++describe("buildAiDraft", () => {+ it("merges over the cached draft, so the model carry-over survives", () => {+ const draft = buildAiDraft(+ { modelRef: { provider: "p", modelId: "m" }, approvalMode: "read-only", text: "typed" },+ { agentId: "default_agent", text: "prompt" },+ );+ expect(draft.modelRef).toEqual({ provider: "p", modelId: "m" });+ expect(draft.approvalMode).toBe("read-only");+ expect(draft.agentId).toBe("default_agent");+ expect(draft.text).toBe("prompt");+ });++ it("resets the skill selection unless the request pins one", () => {+ expect(buildAiDraft({ skills: ["old"] }, { agentId: "a", text: "t" }).skills).toEqual([]);+ expect(buildAiDraft({}, { agentId: "a", text: "t", skills: ["s"] }).skills).toEqual(["s"]);+ });++ it("pins the Workspace only when asked, keeping the cached one otherwise", () => {+ expect(buildAiDraft({ workspace: "/w" }, { agentId: "a", text: "t" }).workspace).toBe("/w");+ // "" is the temporary Workspace — a pin, not an absence.+ const pinned = buildAiDraft({ workspace: "/w" }, { agentId: "a", text: "t", workspace: "" });+ expect(pinned.workspace).toBe("");+ });++ it("drops a stale handoff target, which would forward the prompt to another agent", () => {+ const draft = buildAiDraft({ handoffAgentId: "other" }, { agentId: "a", text: "t" });+ expect("handoffAgentId" in draft).toBe(false);+ });++ it("marks the prompt as composed, so it is not kept or parked as text the user typed", () => {+ expect(buildAiDraft({ text: "typed" }, { agentId: "a", text: "t" }).aiPrefill).toBe(true);+ });+});++describe("aiChatRouteState", () => {+ it("carries only what was asked for", () => {+ expect(aiChatRouteState({ agentId: "a", text: "t" })).toEqual({ agentId: "a" });+ // "" is the temporary Workspace — a pin, so it travels; an absent one leaves no key behind.+ expect(aiChatRouteState({ agentId: "a", text: "t", workspace: "" })).toEqual({+ agentId: "a",+ workspace: "",+ });+ });+});diff --git a/packages/web/test/ai-create-panel.test.ts b/packages/web/test/ai-create-panel.test.tsnew file mode 100644index 00000000..876beb07--- /dev/null+++ b/packages/web/test/ai-create-panel.test.ts@@ -0,0 +1,48 @@+/**+ * The "Create with AI" panel (src/features/ai-create/ai-create-panel.tsx): the example whose+ * prompt the draft still equals is the selected one, and the full-prompt fold shows what is+ * actually sent.+ */+import { describe, expect, it } from "vitest";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import type { AgentSummary } from "@prismshadow/penguin-server/api";+import { AiCreatePanel } from "../src/features/ai-create/ai-create-panel";+import { composeAiPrompt } from "../src/features/ai-create/ai-create-prompt";+import { S } from "../src/lib/strings";++const agents = [{ agentId: "default_agent", name: "Penguin" } as AgentSummary];+const examples = [+ { key: "cli", label: "A CLI", description: "One command", prompt: "Build a CLI" },+ { key: "bot", label: "A bot", prompt: "Build a bot" },+];+const TAIL = "Confirm the name first.";++function render(value: string) {+ return renderToStaticMarkup(+ createElement(AiCreatePanel, {+ value,+ onChange: () => undefined,+ examples,+ tail: TAIL,+ agents,+ agentId: "default_agent",+ }),+ );+}++describe("AiCreatePanel", () => {+ it("marks the example the draft still equals as selected, and no other", () => {+ const html = render("Build a CLI");+ expect(html.match(/aria-pressed="true"/g)).toHaveLength(1);+ expect(html.match(/aria-pressed="false"/g)).toHaveLength(1);+ expect(render("Build a CLI, edited").match(/aria-pressed="true"/g)).toBeNull();+ });++ it("names who does the work and previews the composed prompt in the fold", () => {+ const html = render("Build a CLI");+ expect(html).toContain(S.aiCreate.byAgent("Penguin"));+ expect(html).toContain(composeAiPrompt("Build a CLI", TAIL));+ expect(html).toContain(S.aiCreate.fullPrompt);+ });+});diff --git a/packages/web/test/ai-create-prompt.test.ts b/packages/web/test/ai-create-prompt.test.tsnew file mode 100644index 00000000..ee851737--- /dev/null+++ b/packages/web/test/ai-create-prompt.test.ts@@ -0,0 +1,23 @@+/**+ * The prompt a "Create with AI" surface sends (src/features/ai-create/ai-create-prompt.ts):+ * the draft, then the surface's fixed tail after a blank line.+ */+import { describe, expect, it } from "vitest";+import { composeAiPrompt } from "../src/features/ai-create/ai-create-prompt";++describe("composeAiPrompt", () => {+ it("joins the trimmed draft and tail with one blank line", () => {+ expect(composeAiPrompt(" Build a CLI \n", "\nConfirm the name first.\n")).toBe(+ "Build a CLI\n\nConfirm the name first.",+ );+ });++ it("omits an absent or blank tail", () => {+ expect(composeAiPrompt("Build a CLI")).toBe("Build a CLI");+ expect(composeAiPrompt("Build a CLI", " ")).toBe("Build a CLI");+ });++ it("previews the tail alone while the draft is still empty", () => {+ expect(composeAiPrompt(" ", "Confirm the name first.")).toBe("Confirm the name first.");+ });+});diff --git a/packages/web/test/default-agent.test.ts b/packages/web/test/default-agent.test.tsnew file mode 100644index 00000000..ab04fe0c--- /dev/null+++ b/packages/web/test/default-agent.test.ts@@ -0,0 +1,22 @@+/**+ * Which agent a "Create with AI" surface sends to when none is named+ * (src/features/ai-create/default-agent.ts).+ */+import { describe, expect, it } from "vitest";+import type { AgentSummary } from "@prismshadow/penguin-server/api";+import { pickDefaultAgent } from "../src/features/ai-create/default-agent";++const agent = (agentId: string) => ({ agentId }) as AgentSummary;++describe("pickDefaultAgent", () => {+ it("prefers default_agent wherever it sits in the list", () => {+ expect(pickDefaultAgent([agent("a"), agent("default_agent"), agent("b")])?.agentId).toBe(+ "default_agent",+ );+ });++ it("falls back to the first agent, and to null for an empty list", () => {+ expect(pickDefaultAgent([agent("b"), agent("a")])?.agentId).toBe("b");+ expect(pickDefaultAgent([])).toBeNull();+ });+});diff --git a/packages/web/test/draft-cache.test.ts b/packages/web/test/draft-cache.test.tsindex 221202c3..e204f662 100644--- a/packages/web/test/draft-cache.test.ts+++ b/packages/web/test/draft-cache.test.ts@@ -66,6 +66,15 @@ describe("parseDraft (field-by-field validation)", () => {});});+ it("the AI-prefill mark round-trips only as true, so nothing else can pass for it", () => {+ // It decides whether the text is treated as the user's own (draft-view, draft-sessions):+ // an "aiPrefill": "yes" left in storage must not read as a composed prompt.+ expect(parseDraft(JSON.stringify({ text: "t", aiPrefill: true })).aiPrefill).toBe(true);+ expect(parseDraft(JSON.stringify({ text: "t", aiPrefill: "yes" })).aiPrefill).toBeUndefined();+ expect(parseDraft(JSON.stringify({ text: "t", aiPrefill: false })).aiPrefill).toBeUndefined();+ expect(parseDraft(JSON.stringify({ text: "t" })).aiPrefill).toBeUndefined();+ });+it("wrongly typed fields are dropped, the rest kept", () => {const raw = JSON.stringify({text: 123,diff --git a/packages/web/test/draft-sessions.test.ts b/packages/web/test/draft-sessions.test.tsindex aafe52ad..85c9b796 100644--- a/packages/web/test/draft-sessions.test.ts+++ b/packages/web/test/draft-sessions.test.ts@@ -66,6 +66,27 @@ describe("parkActiveDraft", () => {expect(loadDraft(draftKey("u-empty", "proj"), s).agentId).toBe("a");});+ it("drops an AI-composed prompt instead of parking it, keeping the model carry-over", () => {+ const s = memStorage();+ saveDraft(+ draftKey("u-ai", "proj"),+ {+ text: "Create a vault entry for OPENAI_API_KEY",+ agentId: "default_agent",+ modelRef: { provider: "anthropic", modelId: "claude-sonnet-5" },+ aiPrefill: true,+ },+ s,+ );+ // Nobody typed it, so it must not become a draft conversation row — and the slot this+ // vacates must be empty, or the new-chat draft the caller lands on would read it back.+ expect(parkActiveDraft("u-ai", "proj", s)).toBeNull();+ expect(s.map.has(draftSessionsKey("u-ai", "proj"))).toBe(false);+ expect(loadDraft(draftKey("u-ai", "proj"), s)).toEqual({+ modelRef: { provider: "anthropic", modelId: "claude-sonnet-5" },+ });+ });+it("newest parked draft sorts first", () => {const s = memStorage();saveDraft(draftKey("u-order", "proj"), { text: "first" }, s);diff --git a/packages/web/test/help-fold.test.ts b/packages/web/test/help-fold.test.tsindex 176dbe64..8dd58b5e 100644--- a/packages/web/test/help-fold.test.ts+++ b/packages/web/test/help-fold.test.ts@@ -42,6 +42,14 @@ describe("HelpFold", () => {expect(html).not.toContain("rotate-90");});+ it("indents the body under the label, unless the caller asks for a flush block", () => {+ // A block with its own left edge — a code box — has to line up with what sits above it, so+ // the chevron's indent is dropped; a run of prose keeps it.+ expect(html).toContain("pl-4.5");+ const flush = renderToStaticMarkup(createElement(HelpFold, { flush: true, children: DESC }));+ expect(flush).not.toContain("pl-4.5");+ });+it("folds the subject into the accessible name, keeping the visible text a prefix of it", () => {// WCAG "label in name": a voice-control user must be able to say what they can see.const named = renderToStaticMarkup(createElement(HelpFold, { label: "Vault", children: DESC }));