A local-first multi-agent app development platform, built on PenguinHarness
Save your own prompts as shortcuts on the draft screen (#401)
Yaowei Zheng2c5710d6bcf6
diff --git a/changelog/unreleased/2026-08-21-draft-custom-shortcuts.md b/changelog/unreleased/2026-08-21-draft-custom-shortcuts.mdnew file mode 100644index 00000000..b85bcbb5--- /dev/null+++ b/changelog/unreleased/2026-08-21-draft-custom-shortcuts.md@@ -0,0 +1,18 @@+# A folder of the user's own saved prompts on the draft screen++- **Date:** 2026-08-21+- **Type:** feature+- **Scope:** `web`, `server`, `docs`+- **PR:** [#401](https://github.com/Prism-Shadow/penguin-harness/pull/401)++[中文版](2026-08-21-draft-custom-shortcuts.zh.md)++Added a last folder to the draft screen's examples block, holding shortcuts the user saved themselves. **New shortcut** opens an editor already carrying whatever is in the composer, with its first line suggested as the name; saving files it under the folder, and clicking a row fills the composer with that prompt and sends nothing, exactly like a built-in example. Rows carry edit and delete, and the list is stored per user on the server (`ui_prefs.draftShortcuts`), so it follows the account to another browser or machine.++## Details++- A shortcut is a name and a prompt, and pins no Skills: a saved prompt is not authored against the Skill catalog the product ships, and the Agent it runs under is picked after the click. The fill therefore leaves the composer's Skill selection exactly as the user set it.+- `PUT /api/me/prefs` validates and normalizes the key on the way in — at most 3 shortcuts, a name of at most 40 characters, a prompt of at most 4000, unique ids, no extra keys stored — and answers `invalid_draft_shortcuts` (400) without writing anything. The Web App carries the same numbers for its counters and disabled states.+- The examples block still does not change height as folders are switched: the built-in folders stay within a row of each other's length, and the three-shortcut cap keeps the user's folder — its rows plus the **New shortcut** row — within a row of them too. It gets no scroll box and no pinned height of its own; a scrollbar inside a folder of a few rows would read as a defect. The registry docstring and the block's comments state that rule, and a test pins both halves of it.+- The folder header counts `used/limit` (`0/3`, `1/3`, `3/3`), and the **New shortcut** row disappears at the cap rather than sitting there disabled — the header has already said why. An empty folder is just that row.+- The folder header row moved into a shared `ExampleFolderRow` component, rendered by both the built-in folders and this one.diff --git a/changelog/unreleased/2026-08-21-draft-custom-shortcuts.zh.md b/changelog/unreleased/2026-08-21-draft-custom-shortcuts.zh.mdnew file mode 100644index 00000000..6e2c4dc3--- /dev/null+++ b/changelog/unreleased/2026-08-21-draft-custom-shortcuts.zh.md@@ -0,0 +1,18 @@+# 草稿页新增用户自定义快捷指令折叠夹++- **Date:** 2026-08-21+- **Type:** feature+- **Scope:** `web`, `server`, `docs`+- **PR:** [#401](https://github.com/Prism-Shadow/penguin-harness/pull/401)++[English](2026-08-21-draft-custom-shortcuts.md)++在草稿页示例区末尾新增一个折叠夹,存放用户自己保存的快捷指令。点**新建快捷指令**会打开编辑框,其中已带上输入框中现有的内容,并以首行作为建议名称;保存后归入该折叠夹,点击某一行即把该提示词填入输入框、不发送,与内置示例完全一致。每行提供编辑与删除,列表按用户存放在服务端(`ui_prefs.draftShortcuts`),换浏览器、换机器都还在。++## 细节++- 一条快捷指令由名称与提示词组成,不绑定 Skill:用户保存的提示词并非针对产品内置的 Skill 目录撰写,且运行它的 Agent 是在点击之后才选定的。因此填入时输入框中已勾选的 Skill 原样保留。+- `PUT /api/me/prefs` 在写入前校验并规范化该字段——最多 3 条、名称最多 40 个字符、提示词最多 4000 个字符、id 不得重复、多余字段不入库——不合法时返回 `invalid_draft_shortcuts`(400)且不写入任何内容。Web App 侧保有同一组数值,用于计数与禁用态。+- 切换折叠夹时示例区高度仍然不变:内置折叠夹彼此长度相差不超过一行;「最多 3 条」这个上限让用户折叠夹(快捷指令行加上**新建快捷指令**行)同样落在这个范围内。它没有自己的滚动容器,也不再固定高度——只有几行的折叠夹里出现滚动条本身就像是坏了。注册表文档注释与该区块的注释都写明了这条规则,并有测试分别锁住这两半。+- 折叠夹标题右侧显示「已用/上限」(`0/3`、`1/3`、`3/3`);到达上限后**新建快捷指令**行直接消失,而不是留一行禁用状态——标题已经说明了原因。折叠夹为空时就只剩这一行。+- 折叠夹标题行抽出为共用的 `ExampleFolderRow` 组件,内置折叠夹与本折叠夹共同使用。diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex e0553292..281a65a4 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -37,6 +37,8 @@ A new conversation starts as a draft: pick the Agent, the Workspace (via a serveThere are four approval modes: `allow-all`, `deny-all`, `read-only` (only read-only tools pass), and `always-ask`. See [Tools and Approvals](/tools).+Below the composer the draft page files example prompts into folders, exactly one of them open at a time; clicking a row fills the composer with that prompt and sends nothing, so it can be read and edited before Send. The last folder, **My shortcuts**, is your own: **New shortcut** opens an editor already holding whatever is in the composer, with its first line suggested as the name, and saving files it under that folder — a saved shortcut is a name plus a prompt, pins no Skills, and is stored per user on the server, so it follows you to another browser or machine. Rows carry edit and delete, the folder header counts `used/limit`, and the **New shortcut** row disappears once 3 are saved (a name is at most 40 characters, a prompt at most 4000) — the cap is what keeps this folder the same height as a built-in one, with no scrollbar of its own.+### The Conversation ListThe sidebar's conversation list groups by Workspace or by Agent. Grouping and sort order are switched in the **List options** menu (the sliders icon in the section header), where each option carries its own icon: a folder for Workspace grouping, the Agent glyph for Agent grouping, a clock for most-recent order, and up/down arrows for the drag-reordered manual order.diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex 893c410f..0c3bfe20 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -37,6 +37,8 @@ penguin web审批模式共四种:`allow-all`(全部放行)、`deny-all`(全部拒绝)、`read-only`(仅放行只读工具)、`always-ask`(每次询问),详见[工具与审批](/tools)。+草稿页在输入框下方按折叠夹陈列示例提示词,同一时刻只展开一个;点击某一行即把该提示词填入输入框,并不发送,可先阅读修改再自行发出。最后一个折叠夹「我的快捷指令」属于用户自己:点**新建快捷指令**会打开编辑框,其中已带上输入框中现有的内容,并以首行作为建议名称,保存后即归入该折叠夹——一条快捷指令由名称与提示词组成,不绑定 Skill,按用户存放在服务端,因此换浏览器、换机器都还在。每行提供编辑与删除,折叠夹标题显示「已用/上限」,存满 3 条后**新建快捷指令**行即隐藏(名称不超过 40 个字符,提示词不超过 4000 个字符)——这个上限正是为了让该折叠夹与内置折叠夹等高,不需要自己的滚动条。+### 会话列表侧边栏的会话列表按 Workspace 或 Agent 分组,分组方式与排序方式在标题栏的**列表选项**菜单(滑块图标)里切换,每个选项前带一枚对应图标:文件夹表示按 Workspace 分组、机器人表示按 Agent 分组、时钟表示按最近更新排序、上下箭头表示手动拖拽排序。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex febbb558..0b7f25f5 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -231,6 +231,19 @@ export interface ServerSettingsUpdateRequest {attachmentTotalMb?: number;}+/**+ * One draft-screen shortcut: a prompt the user wrote, filed under a name they chose. Clicking it+ * fills the composer exactly like a built-in example does, and sends nothing. Deliberately holds+ * no Skill list — a saved prompt is not authored against a known Skill catalog the way a shipped+ * example is, and the Agent it will run under is picked after the click.+ */+export interface DraftShortcut {+ /** Stable client-generated id: what an edit or a delete addresses the row by. Unique per user. */+ id: string;+ title: string;+ prompt: string;+}+/** User UI preferences (SQLite ui_prefs, free-form JSON; known keys declared here). */export interface UiPrefs {theme?: "light" | "dark";@@ -245,6 +258,13 @@ export interface UiPrefs {showCliSessions?: boolean;/** The initial-password notice banner (app layout) was permanently dismissed by the user. */initialPasswordBannerDismissed?: boolean;+ /**+ * The draft screen's user-defined shortcuts, in display order. Replaced whole on every write+ * (the merge is shallow, so the array is one field like any other) and bounded on write by+ * services/draft-shortcuts.ts — count, title length and prompt length — because this is the one+ * known key holding user-authored text rather than a flag or an id.+ */+ draftShortcuts?: DraftShortcut[];[key: string]: unknown;}diff --git a/packages/server/src/http/routes/me.ts b/packages/server/src/http/routes/me.tsindex 4abe6f9b..f0ddc570 100644--- a/packages/server/src/http/routes/me.ts+++ b/packages/server/src/http/routes/me.ts@@ -2,7 +2,8 @@* Current-user routes: GET /api/me, PUT /api/me/password, GET|PUT /api/me/prefs.* ui_prefs is free-form JSON (theme / lastProjectId / credentialGuideSeen, etc.): GET reads* it whole, PUT shallow-merges (PATCH semantics) — several independent writers each write- * their own fields without clobbering each other.+ * their own fields without clobbering each other. Free-form does not mean unbounded: a key+ * carrying user-authored text is validated and capped on the way in (draftShortcuts).*/import { Hono } from "hono";import type { MeResponse, PrefsResponse, UiPrefs } from "../../api/types.js";@@ -11,6 +12,7 @@ import type { AppEnv } from "../../auth/middleware.js";import { readJson, requireString } from "../validate.js";import type { AppDeps } from "../../app.js";import { resolvePreviewTarget } from "../../services/preview-token.js";+import { validateDraftShortcuts } from "../../services/draft-shortcuts.js";import {INLINE_IMAGE_MAX_MB,MAX_ATTACHMENT_COUNT,@@ -87,6 +89,12 @@ export function meRoutes(deps: AppDeps): Hono<AppEnv> {// clear credentialGuideSeen, breaking the "show onboarding once ever" guarantee.app.put("/prefs", async (c) => {const body = await readJson(c);+ // The one known key whose value is text the user wrote, so the one that needs a bound here:+ // everything else in ui_prefs is a flag or an id, and the store itself has no schema to lean+ // on. Validated (and normalized) before the merge, so a rejected write stores nothing.+ if (body.draftShortcuts !== undefined) {+ body.draftShortcuts = validateDraftShortcuts(body.draftShortcuts);+ }const raw = deps.prefsRepo.get(c.var.user.userId);let current: UiPrefs = {};if (raw !== null) {diff --git a/packages/server/src/services/draft-shortcuts.ts b/packages/server/src/services/draft-shortcuts.tsnew file mode 100644index 00000000..6b316c54--- /dev/null+++ b/packages/server/src/services/draft-shortcuts.ts@@ -0,0 +1,78 @@+/**+ * Bounds on the draft screen's user-defined shortcuts (`ui_prefs.draftShortcuts`).+ *+ * `ui_prefs` is free-form JSON: `PUT /api/me/prefs` shallow-merges whatever it is handed into a+ * single TEXT column, and every other known key there holds a flag or an id. `draftShortcuts` is+ * the first key whose value is text the user wrote, so it is also the first place a client could+ * put an unbounded amount of it into a shared table. The caps are therefore enforced on the write+ * path, not only in the editor that normally produces the value: the Web App carries its own copy+ * of these numbers for its counters, and a request that never goes through that editor still+ * cannot store more than this.+ *+ * The numbers: 3 shortcuts keeps the folder inside the examples block's height, so it never needs+ * a scrollbar and the block does not move as folders are switched; 40 characters is what one+ * folder row shows without truncating; 4000 characters is roughly three times the longest built-in+ * example prompt. Together they bound one user's row at about 12 KB.+ */+import { HttpError } from "../http/errors.js";+import type { DraftShortcut } from "../api/types.js";++export const DRAFT_SHORTCUT_MAX_COUNT = 3;+export const DRAFT_SHORTCUT_TITLE_MAX = 40;+export const DRAFT_SHORTCUT_PROMPT_MAX = 4000;+/** Client-generated id (`sc-` + hex); the length only has to stop an id being used as storage. */+export const DRAFT_SHORTCUT_ID_MAX = 64;++function invalid(message: string): HttpError {+ return new HttpError(400, "invalid_draft_shortcuts", message);+}++/** A required, non-blank, length-capped string field of one shortcut; returns it trimmed. */+function shortcutField(+ entry: Record<string, unknown>,+ key: string,+ index: number,+ maxLen: number,+): string {+ const value = entry[key];+ if (typeof value !== "string") {+ throw invalid(`draftShortcuts[${index}].${key} must be a string.`);+ }+ const trimmed = value.trim();+ if (trimmed === "") throw invalid(`draftShortcuts[${index}].${key} must not be empty.`);+ if (trimmed.length > maxLen) {+ throw invalid(`draftShortcuts[${index}].${key} must be at most ${maxLen} characters.`);+ }+ return trimmed;+}++/**+ * Validates an incoming `draftShortcuts` value and returns the normalized array to store.+ *+ * Normalizing rather than passing the input through is part of the bound: the stored objects hold+ * exactly `id` / `title` / `prompt`, trimmed, so an extra key on an entry cannot ride along as+ * unbounded free storage inside a value that otherwise looks capped. Ids must be unique — they are+ * what the Web App edits and deletes a row by, and a duplicate would make those act on the wrong+ * one. Anything invalid is a 400 that writes nothing, since the array is replaced whole.+ */+export function validateDraftShortcuts(value: unknown): DraftShortcut[] {+ if (!Array.isArray(value)) throw invalid("draftShortcuts must be an array.");+ if (value.length > DRAFT_SHORTCUT_MAX_COUNT) {+ throw invalid(`draftShortcuts must hold at most ${DRAFT_SHORTCUT_MAX_COUNT} shortcuts.`);+ }+ const seen = new Set<string>();+ return value.map((entry, index) => {+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {+ throw invalid(`draftShortcuts[${index}] must be an object.`);+ }+ const raw = entry as Record<string, unknown>;+ const id = shortcutField(raw, "id", index, DRAFT_SHORTCUT_ID_MAX);+ if (seen.has(id)) throw invalid(`draftShortcuts[${index}].id duplicates an earlier id.`);+ seen.add(id);+ return {+ id,+ title: shortcutField(raw, "title", index, DRAFT_SHORTCUT_TITLE_MAX),+ prompt: shortcutField(raw, "prompt", index, DRAFT_SHORTCUT_PROMPT_MAX),+ };+ });+}diff --git a/packages/server/test/draft-shortcuts.test.ts b/packages/server/test/draft-shortcuts.test.tsnew file mode 100644index 00000000..5d857209--- /dev/null+++ b/packages/server/test/draft-shortcuts.test.ts@@ -0,0 +1,144 @@+/**+ * The draft screen's user-defined shortcuts, stored under `ui_prefs.draftShortcuts`.+ *+ * ui_prefs is a free-form JSON column shared by every UI preference, so this key — the only one+ * holding text the user wrote — is the one that has to be bounded on the way in. The cases below+ * go through the real route rather than the validator alone, because the two claims that matter+ * are about the route: a rejected write stores **nothing**, and an accepted one does not disturb+ * the other writers merging into the same object.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { apiClient, createTestApp, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";+import {+ DRAFT_SHORTCUT_MAX_COUNT,+ DRAFT_SHORTCUT_PROMPT_MAX,+ DRAFT_SHORTCUT_TITLE_MAX,+} from "../src/services/draft-shortcuts.js";+import type { DraftShortcut } from "../src/api/types.js";++const shortcut = (id: string): DraftShortcut => ({+ id,+ title: `title ${id}`,+ prompt: `prompt ${id}`,+});++describe("ui_prefs draftShortcuts", () => {+ let t: TestApp;+ let api: ReturnType<typeof apiClient>;++ beforeEach(async () => {+ t = await createTestApp();+ const { cookie } = await provisionUser(t.app, "gina");+ api = apiClient(t.app, cookie);+ });+ afterEach(async () => {+ await t.cleanup();+ });++ const readShortcuts = async (): Promise<DraftShortcut[] | undefined> => {+ const body = (await (await api.get("/api/me/prefs")).json()) as {+ prefs: { draftShortcuts?: DraftShortcut[] };+ };+ return body.prefs.draftShortcuts;+ };++ it("stores a list per user and reads it back in order", async () => {+ const list = [shortcut("a"), shortcut("b")];+ const res = await api.put("/api/me/prefs", { draftShortcuts: list });+ expect(res.status).toBe(200);+ expect(await readShortcuts()).toEqual(list);++ // Another user's shortcuts are their own.+ const other = apiClient(t.app, (await provisionUser(t.app, "hank")).cookie);+ const theirs = (await (await other.get("/api/me/prefs")).json()) as { prefs: object };+ expect(theirs.prefs).toEqual({});+ });++ it("replaces the whole list on write while leaving other preferences alone", async () => {+ await api.put("/api/me/prefs", { lastProjectId: "default_project" });+ await api.put("/api/me/prefs", { draftShortcuts: [shortcut("a"), shortcut("b")] });+ await api.put("/api/me/prefs", { draftShortcuts: [shortcut("b")] });+ const body = (await (await api.get("/api/me/prefs")).json()) as {+ prefs: { lastProjectId?: string; draftShortcuts?: DraftShortcut[] };+ };+ expect(body.prefs.draftShortcuts).toEqual([shortcut("b")]);+ expect(body.prefs.lastProjectId).toBe("default_project");+ });++ it("normalizes what it stores: trimmed fields, and no extra keys riding along", async () => {+ // Passing the entry through as given would let an unbounded field sit inside a value that+ // otherwise looks capped.+ await api.put("/api/me/prefs", {+ draftShortcuts: [+ { id: " a ", title: " name ", prompt: " body ", note: "x".repeat(5000) },+ ],+ });+ expect(await readShortcuts()).toEqual([{ id: "a", title: "name", prompt: "body" }]);+ });++ it("refuses more shortcuts than the cap, and stores nothing when it does", async () => {+ await api.put("/api/me/prefs", { draftShortcuts: [shortcut("keep")] });+ const tooMany = Array.from({ length: DRAFT_SHORTCUT_MAX_COUNT + 1 }, (_, i) =>+ shortcut(`id-${i}`),+ );+ const res = await api.put("/api/me/prefs", { draftShortcuts: tooMany });+ expect(res.status).toBe(400);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe(+ "invalid_draft_shortcuts",+ );+ expect(await readShortcuts()).toEqual([shortcut("keep")]);++ // Exactly at the cap is fine.+ const atCap = tooMany.slice(0, DRAFT_SHORTCUT_MAX_COUNT);+ expect((await api.put("/api/me/prefs", { draftShortcuts: atCap })).status).toBe(200);+ expect(await readShortcuts()).toHaveLength(DRAFT_SHORTCUT_MAX_COUNT);+ });++ it("refuses an over-long title or prompt", async () => {+ const long = async (field: "title" | "prompt", max: number) => {+ const entry = { ...shortcut("a"), [field]: "x".repeat(max + 1) };+ const res = await api.put("/api/me/prefs", { draftShortcuts: [entry] });+ expect(res.status, `${field} over the cap`).toBe(400);+ const ok = { ...shortcut("a"), [field]: "x".repeat(max) };+ expect((await api.put("/api/me/prefs", { draftShortcuts: [ok] })).status).toBe(200);+ };+ await long("title", DRAFT_SHORTCUT_TITLE_MAX);+ await long("prompt", DRAFT_SHORTCUT_PROMPT_MAX);+ });++ it("refuses a malformed entry", async () => {+ const bad: unknown[] = [+ "not an object",+ { title: "no id", prompt: "body" },+ { id: "a", prompt: "no title" },+ { id: "a", title: "no prompt" },+ { id: "a", title: " ", prompt: "blank title" },+ { id: "a", title: "blank prompt", prompt: " " },+ { id: 7, title: "numeric id", prompt: "body" },+ { id: "x".repeat(65), title: "id as storage", prompt: "body" },+ ];+ for (const entry of bad) {+ const res = await api.put("/api/me/prefs", { draftShortcuts: [entry] });+ expect(res.status, JSON.stringify(entry)).toBe(400);+ }+ // A value that is not an array at all.+ expect((await api.put("/api/me/prefs", { draftShortcuts: { a: 1 } })).status).toBe(400);+ expect(await readShortcuts()).toBeUndefined();+ });++ it("refuses a duplicate id", async () => {+ // Ids are what the Web App edits and deletes a row by; two rows wearing one id would make+ // both act on the wrong one.+ const res = await api.put("/api/me/prefs", {+ draftShortcuts: [shortcut("a"), { ...shortcut("b"), id: "a" }],+ });+ expect(res.status).toBe(400);+ });++ it("accepts an empty list, which is how the last shortcut is deleted", async () => {+ await api.put("/api/me/prefs", { draftShortcuts: [shortcut("a")] });+ expect((await api.put("/api/me/prefs", { draftShortcuts: [] })).status).toBe(200);+ expect(await readShortcuts()).toEqual([]);+ });+});diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsxindex 318b3f30..5951c736 100644--- a/packages/web/src/features/chat/draft-view.tsx+++ b/packages/web/src/features/chat/draft-view.tsx@@ -67,6 +67,8 @@ import { adoptDockScope } from "../dock/dock-state";import { setDockCwd } from "../dock/dock-terminal";import { EXAMPLE_FOLDERS } from "./example-tasks";import type { ExampleFolderId, ExampleTask } from "./example-tasks";+import { ExampleFolderRow, exampleRowClass } from "./example-folder-row";+import { SHORTCUTS_FOLDER_ID, ShortcutsFolder } from "./shortcuts-folder";import { clearDraft, draftKey, loadDraft, saveDraft } from "./draft-cache";import type { DraftCache } from "./draft-cache";import {@@ -670,6 +672,14 @@ export function DraftView({// S is a live binding swapped on locale change: read the prompt at click time, not at render.composerRef.current?.fillExample(S.chat.exampleTasks[task.id].prompt, task.skills);}, []);+ /**+ * A saved shortcut takes the same path with no Skills to pin: its prompt is the user's own text,+ * not a card authored against the Skill catalog this product ships (see user-shortcuts.ts). An+ * empty pin list leaves the composer's Skill selection exactly as the user set it.+ */+ const fillShortcut = useCallback((prompt: string) => {+ composerRef.current?.fillExample(prompt, []);+ }, []);/*** The open example folder — bookmark-style, and ALWAYS exactly one: selecting another closes@@ -679,7 +689,9 @@ export function DraftView({* bare folder rows nor grow to the whole catalog, so switching folders moves what sits* below it by at most one row.*/- const [openFolder, setOpenFolder] = useState<ExampleFolderId>(EXAMPLE_FOLDERS[0].id);+ const [openFolder, setOpenFolder] = useState<ExampleFolderId | typeof SHORTCUTS_FOLDER_ID>(+ EXAMPLE_FOLDERS[0].id,+ );const selectedAgent = agents.find((a) => a.agentId === agentId) ?? null;@@ -751,57 +763,31 @@ export function DraftView({</div>{/* Example tasks: canned builds showing off the one-sentence → app flow; a click fills- the composer with the prompt and the user sends it (see fillExample).+ the composer with the prompt and the user sends it (see fillExample). The last folder+ is the user's own saved prompts (see shortcuts-folder.tsx).Bookmark-style folders with ALWAYS exactly one open — selecting another closes the- previous, and the open one cannot be collapsed. The block is therefore three- folder rows plus one folder's rows, with the folders kept within one row of each- other (3–4 examples each), so switching folders moves what sits below by at most- one row and no scroll container is needed — a scrollbar inside a seven-line- showcase reads as a defect. Each example is a single-line title; its one-sentence- description rides in the row tooltip rather than a second line. Rows stay disabled- until the Agent's installed skills are known — that is all a fill still waits for,- and without it the preselect would silently drop the example's skills. */}+ previous, and the open one cannot be collapsed. The block is therefore four folder+ rows plus one folder's rows, with every folder kept within one row of the others+ (3–4 examples each; the user folder is capped so its shortcuts plus its add row come+ to the same), so switching folders moves what sits below by at most one row and no+ folder needs a scroll container — a scrollbar inside a short showcase reads as a+ defect. Each example is a single-line title; its one-sentence description rides in+ the row tooltip rather than a second line. Rows stay disabled until the Agent's+ installed skills are known — that is all a fill still waits for, and without it the+ preselect would silently drop the example's skills (a saved shortcut pins none, so+ it never waits). */}<div className="mt-6 space-y-1">{EXAMPLE_FOLDERS.map((folder) => {const open = folder.id === openFolder;return (<div key={folder.id}>- {/* A tab, not a disclosure: the open folder stays open (clicking it is a- no-op) and carries the selected fill, so the block always shows one- folder's examples and its height never changes. */}- <button- type="button"- aria-expanded={open}- onClick={() => setOpenFolder(folder.id)}- className={`flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left transition-colors duration-150 ${- open- ? "bg-gray-100 dark:bg-gray-800/70"- : "hover:bg-gray-100 dark:hover:bg-gray-800/70"- }`}- >- <span className="shrink-0 text-brand-500 dark:text-brand-400">- <svg- width="16"- height="16"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.7"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden- >- <path d={FOLDER_GLYPHS[folder.id]} />- </svg>- </span>- <span className="min-w-0 flex-1 truncate text-sm font-medium text-gray-700 dark:text-gray-300">- {S.chat.exampleFolders[folder.id]}- </span>- <span className="shrink-0 text-xs text-gray-400 dark:text-gray-500">- {folder.tasks.length}- </span>- <Chevron open={open} size={14} className="text-gray-400" />- </button>+ <ExampleFolderRow+ open={open}+ glyph={FOLDER_GLYPHS[folder.id]}+ label={S.chat.exampleFolders[folder.id]}+ count={folder.tasks.length}+ onOpen={() => setOpenFolder(folder.id)}+ />{open && (<ul className="mt-0.5 space-y-0.5 pl-4">@@ -814,7 +800,7 @@ export function DraftView({title={`${copy.desc}\n${S.chat.exampleFillHint}`}disabled={!skillsLoaded}onClick={() => fillExample(task)}- className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 disabled:cursor-default disabled:opacity-60 disabled:hover:bg-transparent dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"+ className={`flex w-full items-center gap-2 ${exampleRowClass}`}><span className="min-w-0 flex-1 truncate">{copy.label}</span></button>@@ -826,6 +812,12 @@ export function DraftView({</div>);})}+ <ShortcutsFolder+ open={openFolder === SHORTCUTS_FOLDER_ID}+ onOpen={() => setOpenFolder(SHORTCUTS_FOLDER_ID)}+ readComposerText={() => textRef.current}+ onFill={fillShortcut}+ /></div></div>diff --git a/packages/web/src/features/chat/example-folder-row.tsx b/packages/web/src/features/chat/example-folder-row.tsxnew file mode 100644index 00000000..6e92201d--- /dev/null+++ b/packages/web/src/features/chat/example-folder-row.tsx@@ -0,0 +1,69 @@+/**+ * The header row of one draft-screen example folder.+ *+ * A tab, not a disclosure: the open folder stays open (clicking it is a no-op) and carries the+ * block's whole body, so exactly one folder's rows are ever on screen. It lives in its own module+ * because two callers render it — the built-in folders in draft-view.tsx and the user's own+ * shortcuts folder in shortcuts-folder.tsx — and a folder row that reads differently from its+ * neighbours would be read as a different kind of thing.+ */+import { Chevron } from "../../components/ui/chevron";+import { ICON_SIZE } from "../../lib/icon-scale";++export function ExampleFolderRow({+ open,+ glyph,+ label,+ count,+ onOpen,+}: {+ open: boolean;+ /** 24x24 path for the folder's own mark — what the eye scans to pick a category. */+ glyph: string;+ label: string;+ /** Rows inside the folder, shown right of the name — a bare count, or `used/limit` where one applies. */+ count: number | string;+ onOpen: () => void;+}) {+ return (+ <button+ type="button"+ aria-expanded={open}+ onClick={onOpen}+ className={`flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left transition-colors duration-150 ${+ open ? "bg-gray-100 dark:bg-gray-800/70" : "hover:bg-gray-100 dark:hover:bg-gray-800/70"+ }`}+ >+ <span className="shrink-0 text-brand-500 dark:text-brand-400">+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.7"+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden+ >+ <path d={glyph} />+ </svg>+ </span>+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-gray-700 dark:text-gray-300">+ {label}+ </span>+ <span className="shrink-0 text-xs text-gray-400 dark:text-gray-500">{count}</span>+ <Chevron open={open} size={ICON_SIZE.chevron} className="text-gray-400" />+ </button>+ );+}++/**+ * The class string of one row inside an open folder — an example, or a saved shortcut. Shared for+ * the same reason as the header: the two lists sit in the same block and must read as one list+ * shape. Layout (flex, width) is the caller's, since a shortcut row also carries its own actions.+ */+export const exampleRowClass =+ "rounded-md px-2 py-1.5 text-left text-sm text-gray-600 transition-colors duration-150 " ++ "hover:bg-gray-100 hover:text-gray-900 disabled:cursor-default disabled:opacity-60 " ++ "disabled:hover:bg-transparent dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200";diff --git a/packages/web/src/features/chat/example-tasks.ts b/packages/web/src/features/chat/example-tasks.tsindex e2924623..89228ef1 100644--- a/packages/web/src/features/chat/example-tasks.ts+++ b/packages/web/src/features/chat/example-tasks.ts@@ -9,7 +9,9 @@* Keep the folders within one row of each other (3–4 examples each today): the draft page* reserves no scroll area for this block, so its height is the folder rows plus the open* folder's rows — a folder much longer than its siblings is what would make that height jump- * as folders are switched.+ * as folders are switched. The draft screen appends one more folder that this registry does not+ * describe — the user's own saved shortcuts, whose length is theirs and not ours; it is exempt+ * from the rule by capping how many shortcuts it holds, not by scrolling (shortcuts-folder.tsx).** Copy and prompts live in the active locale dictionary at `S.chat.exampleFolders[id]` and* `S.chat.exampleTasks[id]`, which is also where the rule for how long a prompt may get isdiff --git a/packages/web/src/features/chat/shortcuts-folder.tsx b/packages/web/src/features/chat/shortcuts-folder.tsxnew file mode 100644index 00000000..74a5ba1c--- /dev/null+++ b/packages/web/src/features/chat/shortcuts-folder.tsx@@ -0,0 +1,287 @@+/**+ * The examples block's last folder: the shortcuts the user saved themselves.+ *+ * It behaves like a built-in folder on the way out — a click FILLS the composer and sends+ * nothing — and differs from one in three ways, each of which is why it lives here rather than in+ * the registry:+ *+ * - **Its rows are server state**, per user (`ui_prefs.draftShortcuts`), fetched on mount and+ * written back on every change. Optimistic: the list updates first and rolls back with a toast+ * if the write fails, because the value being written is already on screen.+ * - **Its length is the user's**, not the registry's — but bounded to SHORTCUT_MAX_COUNT, chosen+ * so the folder plus its New-shortcut row stays within a row of a built-in folder's height. The+ * examples block reserves no scroll area, and rather than pinning a height and scrolling inside+ * it, the cap is what keeps this folder the same shape as its siblings: no scrollbar, and the+ * block below moves by at most one row.+ * - **Its rows carry their own actions.** Edit and delete are plain icon buttons that are always+ * visible, deliberately not the sidebar's hover-revealed pair: those rows have a long-press menu+ * behind them on touch, and these have nothing, so hover-gating would put a user's own prompts+ * out of reach on a phone.+ */+import { useCallback, useEffect, useRef, useState } from "react";+import * as api from "../../api/endpoints";+import { S } from "../../lib/strings";+import { apiErrorText } from "../../lib/api-error";+import { ICON_SIZE } from "../../lib/icon-scale";+import { Button } from "../../components/ui/button";+import { ConfirmModal } from "../../components/ui/confirm-modal";+import { GlyphIcon } from "../../components/ui/glyph-icon";+import { PlusIcon } from "../../components/ui/icons";+import { Input, Textarea } from "../../components/ui/input";+import { Modal } from "../../components/ui/modal";+import { PENCIL_ICON, TRASH_ICON } from "../../components/ui/session-row-menu";+import { toastError } from "../../components/ui/toast";+import { ExampleFolderRow, exampleRowClass } from "./example-folder-row";+import {+ SHORTCUT_MAX_COUNT,+ SHORTCUT_PROMPT_MAX,+ SHORTCUT_TITLE_MAX,+ canAddShortcut,+ defaultShortcutTitle,+ normalizeShortcuts,+ removeShortcut,+ shortcutDraftError,+ upsertShortcut,+} from "./user-shortcuts";+import type { ShortcutDraft, UserShortcut } from "./user-shortcuts";++/**+ * Folder id for the user's shortcuts. Not a member of EXAMPLE_FOLDERS: that registry is the+ * catalog this product ships, and everything in it resolves its copy through the locale+ * dictionary — this folder's rows are the user's own text in whatever language they wrote it.+ */+export const SHORTCUTS_FOLDER_ID = "shortcuts";++/**+ * Lightning bolt (lucide zap): the folder's mark. Not the bookmark it might suggest — the folders+ * themselves already behave bookmark-style (exactly one open), so that glyph would name the+ * mechanism every folder shares instead of what this one holds.+ */+const SHORTCUTS_GLYPH =+ "M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z";++/** An always-visible row action (edit / delete), sized and coloured to recede until pointed at. */+function RowAction({+ label,+ glyph,+ danger = false,+ onClick,+}: {+ label: string;+ glyph: string;+ danger?: boolean;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ title={label}+ aria-label={label}+ onClick={onClick}+ className={`flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 dark:text-gray-500 ${+ danger+ ? "hover:text-red-600 dark:hover:text-red-400"+ : "hover:text-gray-700 dark:hover:text-gray-200"+ }`}+ >+ <GlyphIcon d={glyph} size={ICON_SIZE.rowLead} />+ </button>+ );+}++export function ShortcutsFolder({+ open,+ onOpen,+ readComposerText,+ onFill,+}: {+ open: boolean;+ onOpen: () => void;+ /** The composer's current text, read at click time — a new shortcut starts from what was typed. */+ readComposerText: () => string;+ /** Hand the saved prompt to the composer. Pins no Skills; see user-shortcuts.ts. */+ onFill: (prompt: string) => void;+}) {+ const [shortcuts, setShortcuts] = useState<UserShortcut[]>([]);+ /** Until the stored list has arrived the body stays blank: the empty state must not flash first. */+ const [loaded, setLoaded] = useState(false);+ const [draft, setDraft] = useState<ShortcutDraft | null>(null);+ const [deleting, setDeleting] = useState<UserShortcut | null>(null);++ useEffect(() => {+ let cancelled = false;+ void api+ .getPrefs()+ .then((res) => {+ if (!cancelled) setShortcuts(normalizeShortcuts(res.prefs.draftShortcuts));+ })+ .catch(() => undefined) // Unreachable prefs read as "none saved"; the draft page still works.+ .finally(() => {+ if (!cancelled) setLoaded(true);+ });+ return () => {+ cancelled = true;+ };+ }, []);++ /** Latest list for the rollback value: a stale closure would restore a list two edits old. */+ const shortcutsRef = useRef(shortcuts);+ shortcutsRef.current = shortcuts;+ const persist = useCallback((next: UserShortcut[]) => {+ const rollback = shortcutsRef.current;+ setShortcuts(next);+ api.putPrefs({ draftShortcuts: next }).catch((e: unknown) => {+ setShortcuts(rollback);+ toastError(apiErrorText(e));+ });+ }, []);++ const startCreate = () => {+ // The high-value path: whatever is already in the composer becomes the body of the new+ // shortcut, with its first line suggested as the name. Both fields stay editable.+ const text = readComposerText().trim();+ setDraft({ id: null, title: defaultShortcutTitle(text), prompt: text });+ };++ const saveDraft = () => {+ if (draft === null || shortcutDraftError(draft) !== null) return;+ persist(upsertShortcut(shortcuts, draft));+ setDraft(null);+ };++ const draftError = draft === null ? null : shortcutDraftError(draft);+ const editing = draft !== null && draft.id !== null;++ return (+ <div>+ <ExampleFolderRow+ open={open}+ glyph={SHORTCUTS_GLYPH}+ label={S.chat.shortcuts.folder}+ count={`${shortcuts.length}/${SHORTCUT_MAX_COUNT}`}+ onOpen={onOpen}+ />++ {open && (+ /* No fixed height and no scroll: SHORTCUT_MAX_COUNT bounds this folder to a built-in+ folder's height plus the New-shortcut row. */+ <div className="mt-0.5 pl-4">+ {loaded && (+ <ul className="space-y-0.5">+ {shortcuts.map((shortcut) => (+ <li key={shortcut.id} className="flex items-center gap-1">+ <button+ type="button"+ title={`${shortcut.title}\n${S.chat.exampleFillHint}`}+ onClick={() => onFill(shortcut.prompt)}+ className={`flex min-w-0 flex-1 items-center gap-2 ${exampleRowClass}`}+ >+ <span className="min-w-0 flex-1 truncate">{shortcut.title}</span>+ </button>+ <RowAction+ label={S.common.edit}+ glyph={PENCIL_ICON}+ onClick={() => setDraft({ ...shortcut })}+ />+ <RowAction+ label={S.common.delete}+ glyph={TRASH_ICON}+ danger+ onClick={() => setDeleting(shortcut)}+ />+ </li>+ ))}+ {/* Gone at the cap rather than disabled: the header already reads 3/3, so a row+ explaining why it cannot be pressed would say the same thing twice. */}+ {canAddShortcut(shortcuts) && (+ <li>+ <button+ type="button"+ title={S.chat.shortcuts.newFromComposer}+ onClick={startCreate}+ className={`flex w-full items-center gap-2 ${exampleRowClass}`}+ >+ <PlusIcon size={ICON_SIZE.inlineGlyph} />+ <span className="min-w-0 flex-1 truncate">{S.chat.shortcuts.new}</span>+ </button>+ </li>+ )}+ </ul>+ )}+ </div>+ )}++ {/* Create and edit share one dialog — the fields and the rules are identical, and only the+ dialog's name says which one is happening (the same Modal + Input idiom as the sidebar's+ rename dialogs). */}+ <Modal+ open={draft !== null}+ title={editing ? S.chat.shortcuts.editTitle : S.chat.shortcuts.createTitle}+ onClose={() => setDraft(null)}+ widthClass="sm:max-w-lg"+ footer={+ <>+ <Button onClick={() => setDraft(null)}>{S.common.cancel}</Button>+ <Button variant="primary" disabled={draftError !== null} onClick={saveDraft}>+ {S.common.save}+ </Button>+ </>+ }+ >+ {draft !== null && (+ <div className="space-y-3">+ <Input+ label={S.chat.shortcuts.titleLabel}+ hint={S.chat.shortcuts.titleHint(SHORTCUT_TITLE_MAX)}+ error={+ draftError === "titleTooLong"+ ? S.chat.shortcuts.titleTooLong(SHORTCUT_TITLE_MAX)+ : undefined+ }+ value={draft.title}+ autoFocus+ maxLength={SHORTCUT_TITLE_MAX}+ onChange={(e) => setDraft({ ...draft, title: e.target.value })}+ onKeyDown={(e) => {+ // isComposing guard (the repo's IME convention): accepting a Chinese candidate+ // fires Enter, which would otherwise save the raw pinyin.+ if (e.key === "Enter" && !e.nativeEvent.isComposing) saveDraft();+ }}+ />+ <Textarea+ label={S.chat.shortcuts.promptLabel}+ info={S.chat.shortcuts.promptInfo}+ infoLabel={S.common.moreInfoAbout(S.chat.shortcuts.promptLabel)}+ hint={S.chat.shortcuts.promptHint(SHORTCUT_PROMPT_MAX)}+ error={+ draftError === "promptTooLong"+ ? S.chat.shortcuts.promptTooLong(SHORTCUT_PROMPT_MAX)+ : undefined+ }+ value={draft.prompt}+ rows={8}+ size="sm"+ maxLength={SHORTCUT_PROMPT_MAX}+ onChange={(e) => setDraft({ ...draft, prompt: e.target.value })}+ />+ </div>+ )}+ </Modal>++ <ConfirmModal+ open={deleting !== null}+ title={S.chat.shortcuts.deleteTitle}+ confirmLabel={S.common.delete}+ onClose={() => setDeleting(null)}+ onConfirm={() => {+ if (deleting !== null) persist(removeShortcut(shortcuts, deleting.id));+ setDeleting(null);+ }}+ >+ <p className="text-sm text-gray-600 dark:text-gray-300">+ {deleting !== null ? S.chat.shortcuts.deleteConfirm(deleting.title) : ""}+ </p>+ </ConfirmModal>+ </div>+ );+}diff --git a/packages/web/src/features/chat/user-shortcuts.ts b/packages/web/src/features/chat/user-shortcuts.tsnew file mode 100644index 00000000..b0a6f7c4--- /dev/null+++ b/packages/web/src/features/chat/user-shortcuts.ts@@ -0,0 +1,152 @@+/**+ * The draft screen's user-defined shortcuts: prompts the user wrote and saved, one click away+ * from the composer. Storage, shape and the rules the editor enforces all live here.+ *+ * **Where they are stored, and why it is not the browser.** These are per-user server state+ * (`ui_prefs.draftShortcuts`, PUT /api/me/prefs), not localStorage. Every other draft-screen+ * preference — the cached draft, the collapsed groups, the sidebar width — can be recreated by+ * doing the thing again; a prompt the user typed and named cannot. Losing it by opening the app+ * on another machine, or by clearing site data, would be losing their work.+ *+ * **A shortcut is a title and a prompt, and pins no Skills.** A built-in example is authored+ * against the Skill catalog this product ships, so it can name the Skills its prompt depends on;+ * a prompt the user saved has no such guarantee, and the Agent it will eventually run under is+ * picked *after* the click. Pinning would therefore mean either silently dropping names the+ * selected Agent lacks, or growing the editor a Skill picker whose contents change with a+ * selection made elsewhere on the page. The composer's own Skills dropdown is one click away and+ * keeps working: a shortcut fills the text and leaves the selection exactly as the user set it.+ *+ * **The caps are duplicated on the server on purpose** (`services/draft-shortcuts.ts`), which is+ * where they are enforced — ui_prefs is a free-form JSON column, so a bound that lives only in+ * this editor is not a bound at all. The numbers here drive the counters and the disabled states;+ * `test/user-shortcuts.test.ts` fails if the two copies drift apart.+ */+import type { DraftShortcut } from "@prismshadow/penguin-server/api";++/** A saved shortcut, as stored and as rendered. Re-exported from the API type so the two cannot drift. */+export type UserShortcut = DraftShortcut;++/** Most shortcuts one user may keep. Past this a click-to-pick list is a search problem. */+export const SHORTCUT_MAX_COUNT = 3;+/** Longest title, in characters: what one folder row shows without truncating. */+export const SHORTCUT_TITLE_MAX = 40;+/** Longest prompt body, in characters: about three times the longest built-in example. */+export const SHORTCUT_PROMPT_MAX = 4000;++/**+ * A fresh shortcut id. Same generator as the parked-draft ids (draft-sessions.ts): random,+ * opaque, and never derived from the title — a rename must not change what an edit addresses.+ */+export function newShortcutId(): string {+ return `sc-${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`;+}++/** One trimmed, length-capped string field read back out of free-form JSON; null when unusable. */+function readField(value: unknown, maxLen: number): string | null {+ if (typeof value !== "string") return null;+ const trimmed = value.trim();+ if (trimmed === "") return null;+ return trimmed.slice(0, maxLen);+}++/**+ * Reads the stored value back into a list the UI can render.+ *+ * The server validates what it accepts, so in practice this receives what it wrote — but the+ * column is free-form JSON shared with every other preference, and a value that has been through+ * a hand-edited database, a future cap change or an older client must still render rather than+ * throw. Unusable entries are dropped; over-long fields are truncated instead of dropped, because+ * a shortened prompt is recoverable and a vanished one is not.+ */+export function normalizeShortcuts(value: unknown): UserShortcut[] {+ if (!Array.isArray(value)) return [];+ const out: UserShortcut[] = [];+ const seen = new Set<string>();+ for (const entry of value) {+ if (out.length >= SHORTCUT_MAX_COUNT) break;+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) continue;+ const raw = entry as Record<string, unknown>;+ const id = readField(raw.id, 64);+ const title = readField(raw.title, SHORTCUT_TITLE_MAX);+ const prompt = readField(raw.prompt, SHORTCUT_PROMPT_MAX);+ if (id === null || title === null || prompt === null || seen.has(id)) continue;+ seen.add(id);+ out.push({ id, title, prompt });+ }+ return out;+}++/** What the editor is holding: an `id` means it is editing that shortcut, null means a new one. */+export interface ShortcutDraft {+ id: string | null;+ title: string;+ prompt: string;+}++/** Which rule an editor draft breaks, as a dictionary key; null when it is saveable. */+export type ShortcutDraftError =+ "titleRequired" | "promptRequired" | "titleTooLong" | "promptTooLong";++/**+ * Validates an editor draft the way the server validates a write, so Save is refused here rather+ * than by a 400. The length rules look redundant against the fields' own `maxLength` — they are+ * not: `maxLength` bounds typing and pasting, not a value restored from a draft written under a+ * different cap, and the rule has to be stated where it can be tested.+ */+export function shortcutDraftError(draft: {+ title: string;+ prompt: string;+}): ShortcutDraftError | null {+ const title = draft.title.trim();+ const prompt = draft.prompt.trim();+ if (title === "") return "titleRequired";+ if (title.length > SHORTCUT_TITLE_MAX) return "titleTooLong";+ if (prompt === "") return "promptRequired";+ if (prompt.length > SHORTCUT_PROMPT_MAX) return "promptTooLong";+ return null;+}++/** Whether another shortcut still fits. The add affordance reads this; the server enforces it. */+export function canAddShortcut(list: readonly UserShortcut[]): boolean {+ return list.length < SHORTCUT_MAX_COUNT;+}++/**+ * Saves an editor draft into the list and returns the new one.+ *+ * Order is insertion order and stays that way: a new shortcut is appended, and an edited one keeps+ * its position, so saving a title fix does not move the row out from under the cursor that is+ * about to click it. A draft whose id is no longer in the list (deleted in another tab while the+ * editor was open) is appended rather than dropped — the user typed it, so it lands somewhere.+ * Appending past the cap is a no-op: the add affordance is disabled there and never reaches this.+ */+export function upsertShortcut(+ list: readonly UserShortcut[],+ draft: ShortcutDraft,+): UserShortcut[] {+ const saved: UserShortcut = {+ id: draft.id ?? newShortcutId(),+ title: draft.title.trim(),+ prompt: draft.prompt.trim(),+ };+ const at = list.findIndex((s) => s.id === saved.id);+ if (at !== -1) return list.map((s, i) => (i === at ? saved : s));+ if (!canAddShortcut(list)) return [...list];+ return [...list, saved];+}++/** Removes one shortcut by id, closing the gap. An unknown id leaves the list as it was. */+export function removeShortcut(list: readonly UserShortcut[], id: string): UserShortcut[] {+ return list.filter((s) => s.id !== id);+}++/**+ * The title a new shortcut opens with, derived from the prompt it is being saved from: the first+ * line that has anything on it, with runs of whitespace collapsed, cut to the title cap. A+ * suggestion only — the editor puts it in an editable field, and an empty prompt suggests nothing.+ */+export function defaultShortcutTitle(prompt: string): string {+ const line = prompt.split("\n").find((l) => l.trim() !== "");+ if (line === undefined) return "";+ return line.trim().replace(/\s+/g, " ").slice(0, SHORTCUT_TITLE_MAX);+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 73de2298..c33e44e1 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1168,6 +1168,24 @@ export const en: Strings = {},/** Second tooltip line on an example row: the click fills the composer, it does not send. */exampleFillHint: "Click to fill the composer — edit it if you like, then send",+ shortcuts: {+ folder: "My shortcuts",+ new: "New shortcut",+ newFromComposer: "Starts from whatever is in the composer",+ createTitle: "New shortcut",+ editTitle: "Edit shortcut",+ titleLabel: "Name",+ titleHint: (max: number) => `At most ${max} characters`,+ promptLabel: "Prompt",+ promptHint: (max: number) => `At most ${max} characters`,+ promptInfo:+ "Clicking this shortcut puts the text into the composer verbatim and sends nothing; Skills stay a separate pick in the composer.",+ titleTooLong: (max: number) => `The name may be at most ${max} characters`,+ promptTooLong: (max: number) => `The prompt may be at most ${max} characters`,+ deleteTitle: "Delete shortcut",+ deleteConfirm: (title: string) =>+ `Delete "${title}"? The shortcut disappears from every device you use.`,+ },exampleTasks: {game: {label: "2D penguin sled game",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex d207fdf9..bff72232 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1130,6 +1130,30 @@ export const zh = {},/** Second tooltip line on an example row: the click fills the composer, it does not send. */exampleFillHint: "点击填入输入框,可修改后自行发送",+ /** The examples block's last folder: prompts the user wrote and saved, stored per user on the server. */+ shortcuts: {+ folder: "我的快捷指令",+ new: "新建快捷指令",+ /**+ * Tooltip on the new-shortcut row. Unconditional, and worded to hold either way: the+ * editor opens on whatever the composer holds, which is a blank draft when it holds+ * nothing — saving what was just typed is the path this folder exists to shorten.+ */+ newFromComposer: "以输入框中的内容作为起点",+ createTitle: "新建快捷指令",+ editTitle: "编辑快捷指令",+ titleLabel: "名称",+ titleHint: (max: number) => `最多 ${max} 个字符`,+ promptLabel: "提示词",+ promptHint: (max: number) => `最多 ${max} 个字符`,+ /** Semantics behind the prompt field's "?": what the saved text does when clicked. */+ promptInfo:+ "点击这条快捷指令时,这段文字会原样填入输入框,不会自动发送;需要的 Skill 仍在输入框里自行勾选。",+ titleTooLong: (max: number) => `名称最多 ${max} 个字符`,+ promptTooLong: (max: number) => `提示词最多 ${max} 个字符`,+ deleteTitle: "删除快捷指令",+ deleteConfirm: (title: string) => `确定删除「${title}」?该快捷指令会从你的所有设备上消失。`,+ },/*** Example task cards on the draft screen: one click fills the composer with the canned* prompt, which the user reads, edits and sends. That is why a prompt is SHORT — a shortdiff --git a/packages/web/test/user-shortcuts.test.ts b/packages/web/test/user-shortcuts.test.tsnew file mode 100644index 00000000..a6660db8--- /dev/null+++ b/packages/web/test/user-shortcuts.test.ts@@ -0,0 +1,278 @@+/**+ * The draft screen's user-defined shortcuts: the rules the editor enforces, the shape that comes+ * back out of free-form storage, and the two invariants the feature had to keep.+ *+ * Three groups worth naming.+ *+ * - **The caps are duplicated across packages on purpose** — the Web App's copy drives the+ * counters, the server's copy is the enforcement — so the parity check reads the server module+ * as text rather than importing it: `@prismshadow/penguin-server` is a type-only dependency+ * here, and making it a runtime one to check three numbers would be a worse trade than a regex.+ * - **The examples block's height must not move** when folders are switched. The built-in folders+ * keep that by staying within a row of each other; the user's folder cannot, so it is pinned to+ * the tallest built-in folder's height and scrolls. Both halves are asserted.+ * - **A click on a shortcut is a fill, not a send**, and it pins no Skills — checked through+ * buildExampleFill and against the real handler in draft-view.tsx, the way+ * test/example-fill.test.ts checks the built-in rows.+ */+import { describe, expect, it } from "vitest";+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { buildExampleFill } from "../src/features/chat/example-fill";+import { EXAMPLE_FOLDERS } from "../src/features/chat/example-tasks";+import {+ SHORTCUT_MAX_COUNT,+ SHORTCUT_PROMPT_MAX,+ SHORTCUT_TITLE_MAX,+ canAddShortcut,+ defaultShortcutTitle,+ newShortcutId,+ normalizeShortcuts,+ removeShortcut,+ shortcutDraftError,+ upsertShortcut,+} from "../src/features/chat/user-shortcuts";+import type { UserShortcut } from "../src/features/chat/user-shortcuts";++const shortcut = (id: string, title = `title ${id}`, prompt = `prompt ${id}`): UserShortcut => ({+ id,+ title,+ prompt,+});++const read = (relative: string): string =>+ readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8");++describe("normalizeShortcuts — reading the list back out of free-form JSON", () => {+ it("reads a stored list through unchanged", () => {+ const stored = [shortcut("a"), shortcut("b")];+ expect(normalizeShortcuts(stored)).toEqual(stored);+ });++ it("treats anything that is not an array as no shortcuts", () => {+ // ui_prefs is one shared JSON column: a key that was never written, or written by an older+ // client, must render as an empty folder rather than throw on the draft screen.+ for (const value of [undefined, null, {}, "", 3, true]) {+ expect(normalizeShortcuts(value)).toEqual([]);+ }+ });++ it("drops entries that cannot be rendered as a row", () => {+ const list = normalizeShortcuts([+ null,+ "a string",+ ["an array"],+ { id: "a", title: "kept", prompt: "body" },+ { id: "", title: "no id", prompt: "body" },+ { id: "b", title: " ", prompt: "body" },+ { id: "c", title: "no prompt", prompt: "" },+ { id: "d", title: "wrong type", prompt: 42 },+ ]);+ expect(list.map((s) => s.id)).toEqual(["a"]);+ });++ it("trims whitespace and drops a duplicate id", () => {+ // The id is what an edit and a delete address, so a second row wearing it would make both+ // act on the wrong one.+ const list = normalizeShortcuts([+ { id: " a ", title: " first ", prompt: " body " },+ { id: "a", title: "second", prompt: "body" },+ ]);+ expect(list).toEqual([{ id: "a", title: "first", prompt: "body" }]);+ });++ it("truncates an over-long field instead of dropping the shortcut", () => {+ // A shortened prompt is recoverable; a vanished one is the user's own text, gone.+ const list = normalizeShortcuts([+ {+ id: "a",+ title: "T".repeat(SHORTCUT_TITLE_MAX + 20),+ prompt: "P".repeat(SHORTCUT_PROMPT_MAX + 20),+ },+ ]);+ expect(list).toHaveLength(1);+ expect(list[0]!.title).toHaveLength(SHORTCUT_TITLE_MAX);+ expect(list[0]!.prompt).toHaveLength(SHORTCUT_PROMPT_MAX);+ });++ it("stops at the count cap", () => {+ const stored = Array.from({ length: SHORTCUT_MAX_COUNT + 5 }, (_, i) => shortcut(`id-${i}`));+ expect(normalizeShortcuts(stored)).toHaveLength(SHORTCUT_MAX_COUNT);+ });+});++describe("shortcutDraftError — what the editor refuses to save", () => {+ it("accepts a title and a prompt", () => {+ expect(+ shortcutDraftError({ title: "Weekly report", prompt: "Summarize the week." }),+ ).toBeNull();+ });++ it("requires both fields, whitespace not counting as content", () => {+ expect(shortcutDraftError({ title: "", prompt: "body" })).toBe("titleRequired");+ expect(shortcutDraftError({ title: " \n ", prompt: "body" })).toBe("titleRequired");+ expect(shortcutDraftError({ title: "name", prompt: "" })).toBe("promptRequired");+ expect(shortcutDraftError({ title: "name", prompt: " \t " })).toBe("promptRequired");+ });++ it("enforces both length caps on the trimmed value", () => {+ expect(shortcutDraftError({ title: "T".repeat(SHORTCUT_TITLE_MAX), prompt: "p" })).toBeNull();+ expect(shortcutDraftError({ title: "T".repeat(SHORTCUT_TITLE_MAX + 1), prompt: "p" })).toBe(+ "titleTooLong",+ );+ expect(shortcutDraftError({ title: "t", prompt: "P".repeat(SHORTCUT_PROMPT_MAX) })).toBeNull();+ expect(+ shortcutDraftError({ title: "t", prompt: ` ${"P".repeat(SHORTCUT_PROMPT_MAX + 1)} ` }),+ ).toBe("promptTooLong");+ });+});++describe("the list operations — order is insertion order", () => {+ it("appends a new shortcut at the end and gives it an id", () => {+ const list = [shortcut("a"), shortcut("b")];+ const next = upsertShortcut(list, { id: null, title: "third", prompt: "body" });+ expect(next.map((s) => s.title)).toEqual(["title a", "title b", "third"]);+ expect(next[2]!.id).not.toBe("");+ expect(list).toHaveLength(2); // the input list is not mutated+ });++ it("keeps an edited shortcut where it was", () => {+ // Saving a title fix must not move the row out from under the cursor about to click it.+ const list = [shortcut("a"), shortcut("b"), shortcut("c")];+ const next = upsertShortcut(list, { id: "b", title: "renamed", prompt: "new body" });+ expect(next.map((s) => s.id)).toEqual(["a", "b", "c"]);+ expect(next[1]).toEqual({ id: "b", title: "renamed", prompt: "new body" });+ });++ it("trims what it saves", () => {+ const next = upsertShortcut([], { id: null, title: " name ", prompt: " body " });+ expect(next[0]).toMatchObject({ title: "name", prompt: "body" });+ });++ it("appends a draft whose shortcut was deleted elsewhere rather than losing it", () => {+ const next = upsertShortcut([shortcut("a")], { id: "gone", title: "typed", prompt: "body" });+ expect(next.map((s) => s.id)).toEqual(["a", "gone"]);+ });++ it("refuses to grow past the cap, but still edits in place at the cap", () => {+ const full = Array.from({ length: SHORTCUT_MAX_COUNT }, (_, i) => shortcut(`id-${i}`));+ expect(canAddShortcut(full)).toBe(false);+ expect(canAddShortcut(full.slice(1))).toBe(true);+ expect(upsertShortcut(full, { id: null, title: "one more", prompt: "body" })).toHaveLength(+ SHORTCUT_MAX_COUNT,+ );+ const edited = upsertShortcut(full, { id: "id-0", title: "renamed", prompt: "body" });+ expect(edited).toHaveLength(SHORTCUT_MAX_COUNT);+ expect(edited[0]!.title).toBe("renamed");+ });++ it("removes by id, closing the gap, and ignores an id it does not hold", () => {+ const list = [shortcut("a"), shortcut("b"), shortcut("c")];+ expect(removeShortcut(list, "b").map((s) => s.id)).toEqual(["a", "c"]);+ expect(removeShortcut(list, "zzz")).toEqual(list);+ });++ it("mints distinct ids", () => {+ expect(newShortcutId()).not.toBe(newShortcutId());+ });+});++describe("defaultShortcutTitle — the name suggested when saving what was typed", () => {+ it("takes the first line that has anything on it", () => {+ expect(defaultShortcutTitle("\n\n Build a landing page \nsecond line")).toBe(+ "Build a landing page",+ );+ });++ it("collapses whitespace runs so a wrapped heading stays one line", () => {+ expect(defaultShortcutTitle("Build\ta landing page")).toBe("Build a landing page");+ });++ it("cuts to the title cap", () => {+ expect(defaultShortcutTitle("T".repeat(200))).toHaveLength(SHORTCUT_TITLE_MAX);+ });++ it("suggests nothing for an empty composer", () => {+ expect(defaultShortcutTitle("")).toBe("");+ expect(defaultShortcutTitle(" \n ")).toBe("");+ });+});++describe("the examples block keeps its height", () => {+ it("keeps the built-in folders within one row of each other", () => {+ // The draft page reserves no scroll area for this block, so a folder much longer than its+ // siblings is what makes the height jump as folders are switched.+ const lengths = EXAMPLE_FOLDERS.map((folder) => folder.tasks.length);+ expect(Math.max(...lengths) - Math.min(...lengths)).toBeLessThanOrEqual(1);+ });++ it("keeps the user folder within one row of the built-in ones", () => {+ // Its tallest state is either the cap with no add row, or one below the cap plus the add+ // row — both SHORTCUT_MAX_COUNT rows. The cap is what holds this, not a pinned height with+ // a scrollbar inside it.+ const tallestBuiltIn = Math.max(...EXAMPLE_FOLDERS.map((f) => f.tasks.length));+ const tallestUser = Math.max(SHORTCUT_MAX_COUNT, SHORTCUT_MAX_COUNT - 1 + 1);+ expect(tallestUser - tallestBuiltIn).toBeLessThanOrEqual(1);+ });++ it("drops the add row at the cap instead of disabling it", () => {+ // The header already reads 3/3; a disabled row explaining the same thing is the second+ // telling, and it is the row that would otherwise make the folder one taller than its cap.+ const source = read("../src/features/chat/shortcuts-folder.tsx");+ expect(source).toContain("canAddShortcut(shortcuts) && (");+ expect(source).not.toContain("disabled={!canAddShortcut");+ });++ it("labels the folder used/limit rather than a bare count", () => {+ const source = read("../src/features/chat/shortcuts-folder.tsx");+ expect(source).toContain("count={`${shortcuts.length}/${SHORTCUT_MAX_COUNT}`}");+ });++ it("gives the user folder no scroll box of its own", () => {+ // A scrollbar inside a folder of at most a few rows reads as a defect; the cap removes the+ // need for one, so the markup must not reintroduce it.+ const source = read("../src/features/chat/shortcuts-folder.tsx");+ expect(source).not.toContain("overflow-y-auto");+ expect(source).not.toContain("bodyHeight");+ });+});++describe("clicking a shortcut", () => {+ it("hands the composer the saved prompt and leaves the Skill selection alone", () => {+ // A saved prompt is not authored against the shipped Skill catalog, so it pins nothing —+ // and an empty pin list is exactly what leaves a selection the user made by hand intact.+ const fill = buildExampleFill({+ prompt: "Summarize the week.",+ exampleSkills: [],+ installedSkills: ["web-design", "memory"],+ selectedSkills: ["memory"],+ });+ expect(fill.text).toBe("Summarize the week.");+ expect(fill.skills).toEqual(["memory"]);+ });++ it("routes the click through the composer handle and never sends", () => {+ const source = read("../src/features/chat/draft-view.tsx");+ const handler = /const fillShortcut = useCallback\(([\s\S]*?)\n \}, \[\]\);/.exec(source);+ expect(handler, "the fillShortcut handler").not.toBeNull();+ expect(handler?.[1]).toContain("composerRef.current?.fillExample(prompt, [])");+ expect(handler?.[1]).not.toContain("onSend");+ expect(handler?.[1]).not.toContain("api.");+ });+});++describe("the caps the server enforces", () => {+ it("matches the Web App's copy of them", () => {+ // Two copies on purpose: the server owns enforcement (ui_prefs is a free-form JSON column),+ // this package owns the counters, and penguin-server is a type-only dependency here.+ const source = read("../../server/src/services/draft-shortcuts.ts");+ const capOf = (name: string): number => {+ const m = new RegExp(`export const ${name} = (\\d+);`).exec(source);+ expect(m, `${name} in the server module`).not.toBeNull();+ return Number(m?.[1]);+ };+ expect(capOf("DRAFT_SHORTCUT_MAX_COUNT")).toBe(SHORTCUT_MAX_COUNT);+ expect(capOf("DRAFT_SHORTCUT_TITLE_MAX")).toBe(SHORTCUT_TITLE_MAX);+ expect(capOf("DRAFT_SHORTCUT_PROMPT_MAX")).toBe(SHORTCUT_PROMPT_MAX);+ });+});