paseo-plugin-genui 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/OVERVIEW.md +5 -3
  2. package/README.md +15 -7
  3. package/assets/screenshot-chat.png +0 -0
  4. package/assets/screenshot-gallery.png +0 -0
  5. package/assets/screenshot-map.png +0 -0
  6. package/assets/screenshot-playground.png +0 -0
  7. package/client/components/content.tsx +41 -21
  8. package/client/components/data.tsx +18 -7
  9. package/client/components/dev.tsx +38 -26
  10. package/client/components/diagram.tsx +1 -1
  11. package/client/components/feedback.tsx +333 -0
  12. package/client/components/inputs.tsx +54 -47
  13. package/client/components/layout.tsx +3 -1
  14. package/client/components/media.tsx +2 -2
  15. package/client/components/project.tsx +7 -2
  16. package/client/components/widgets.tsx +35 -24
  17. package/client/gallery.tsx +7 -5
  18. package/client/live-ui.tsx +26 -2
  19. package/client/markdown.tsx +1 -5
  20. package/client/node-renderer.tsx +6 -1
  21. package/client/queue-pill.tsx +123 -0
  22. package/client/render.tsx +2 -0
  23. package/client/reply-queue.ts +82 -0
  24. package/client/runtime.ts +7 -0
  25. package/gallery/Other.ui +11 -0
  26. package/gallery/Plan.ui +1 -1
  27. package/index.client.tsx +6 -1
  28. package/index.server.ts +10 -0
  29. package/package.json +2 -2
  30. package/paseo-plugin.json +2 -1
  31. package/server/render-tool.ts +34 -0
  32. package/shared/core/catalog.ts +23 -5
  33. package/shared/core/evaluate.ts +2 -0
  34. package/shared/core/markdown.ts +2 -0
  35. package/shared/core/types.ts +2 -1
  36. package/shared/diagram/markdown.test.ts +13 -0
  37. package/shared/diagram/markdown.ts +15 -1
  38. package/shared/fallback.ts +1 -1
  39. package/shared/hermes-syntax.test.ts +1 -1
  40. package/shared/instructions.ts +3 -1
  41. package/shared/logic/reply.test.ts +29 -0
  42. package/shared/logic/reply.ts +33 -0
  43. package/shared/logic/values.ts +1 -0
@@ -0,0 +1,34 @@
1
+ import { defineAgentTool } from "@getpaseo/plugin/server";
2
+ import { z } from "zod";
3
+ import { specProblems } from "../shared/fallback";
4
+ import { GENUI_BLOCK_KIND } from "../shared/segment";
5
+ import { loadAgentFile } from "./data-source";
6
+
7
+ let seq = 0;
8
+
9
+ /** Shows a ui spec in the agent's chat only when it renders; otherwise returns the errors so the agent fixes them in the same turn. */
10
+ export const renderUiTool = defineAgentTool({
11
+ name: "render_ui",
12
+ title: "Show UI",
13
+ description:
14
+ "Show a ui spec to the user as live UI; use it instead of writing a ```ui block. The spec is checked first: if it has errors, nothing is shown and the errors come back. Fix them and call again without mentioning the errors or the retry to the user. Write your answer sentence before the call, and do not repeat the UI's content in text after it.",
15
+ input: z.object({ spec: z.string().describe("The ui spec, without the ``` fence") }),
16
+ async execute({ spec }, { agent, paseo }) {
17
+ const { problems } = await specProblems(spec, (request) => loadAgentFile(paseo, agent.id, request.path, request));
18
+ if (problems.length > 0) {
19
+ return {
20
+ isError: true,
21
+ text: `Nothing was shown. Fix these and call render_ui again; do not tell the user about them:\n${problems.join("\n")}`,
22
+ };
23
+ }
24
+ const id = `genui-render-${Date.now()}-${++seq}`;
25
+ await paseo.agents.ref(agent.id).timeline.append({
26
+ type: "plugin",
27
+ id,
28
+ kind: GENUI_BLOCK_KIND,
29
+ version: 1,
30
+ data: { language: "ui", code: spec, complete: true, fenceIndex: 0, messageId: id },
31
+ });
32
+ return { text: "Shown to the user. Do not repeat its content or mention earlier failed calls." };
33
+ },
34
+ });
@@ -60,6 +60,10 @@ const tone = { name: "tone", kind: "enum", optional: true, values: TONES } as co
60
60
  const label = { name: "label", kind: "string", optional: true } as const;
61
61
  const children = { name: "children", kind: "nodes" } as const;
62
62
 
63
+ /** Lets the user comment on each item, and edit its text, before replying; both are queued into the reply. */
64
+ const comments = { name: "comments", kind: "boolean", optional: true } as const;
65
+ const editable = { name: "editable", kind: "boolean", optional: true } as const;
66
+
63
67
  export const COMPONENTS = {
64
68
  Card: {
65
69
  group: "Layout",
@@ -148,6 +152,7 @@ export const COMPONENTS = {
148
152
  params: [
149
153
  { name: "columns", kind: "list" },
150
154
  { name: "rows", kind: "list" },
155
+ comments,
151
156
  ],
152
157
  summary: "rows: lists of values or components",
153
158
  },
@@ -178,7 +183,7 @@ export const COMPONENTS = {
178
183
  },
179
184
  Steps: {
180
185
  group: "Data",
181
- params: [{ name: "items", kind: "list" }],
186
+ params: [{ name: "items", kind: "list" }, comments, editable],
182
187
  summary: "{title,detail?,status?:done|current|blocked}",
183
188
  },
184
189
  Timeline: {
@@ -395,7 +400,7 @@ export const COMPONENTS = {
395
400
  },
396
401
  List: {
397
402
  group: "Content",
398
- params: [{ name: "items", kind: "list" }],
403
+ params: [{ name: "items", kind: "list" }, comments, editable],
399
404
  summary: "rows {title, detail?, icon?, value?, tone?, action?}",
400
405
  },
401
406
  Calendar: {
@@ -435,9 +440,17 @@ export const COMPONENTS = {
435
440
  params: [children],
436
441
  summary: "a swipeable row of cards",
437
442
  },
443
+ Other: {
444
+ group: "Inputs",
445
+ params: [
446
+ { name: "label", kind: "string", optional: true },
447
+ { name: "placeholder", kind: "string", optional: true },
448
+ ],
449
+ summary: "an \"Other…\" button that opens a box for free-form feedback, queued into the reply",
450
+ },
438
451
  OptionCards: {
439
452
  group: "Inputs",
440
- params: [{ name: "value", kind: "binding" }, { name: "options", kind: "list" }, label],
453
+ params: [{ name: "value", kind: "binding" }, { name: "options", kind: "list" }, label, comments],
441
454
  summary: "picture or detail options {value, title?, detail?, image?, icon?}; a list state picks several",
442
455
  },
443
456
  Swatches: {
@@ -518,7 +531,7 @@ export const COMPONENTS = {
518
531
  },
519
532
  Findings: {
520
533
  group: "Dev",
521
- params: [{ name: "items", kind: "any" }, { name: "title", kind: "string", optional: true }],
534
+ params: [{ name: "items", kind: "any" }, { name: "title", kind: "string", optional: true }, comments, editable],
522
535
  summary: "review/lint/type errors [{severity, title, file?, line?, detail?, fix?, status?: open|fixed|confirmed|rejected}] or Load ESLint JSON, SARIF, tsc output",
523
536
  },
524
537
  Coverage: {
@@ -569,7 +582,7 @@ export const COMPONENTS = {
569
582
  },
570
583
  Plan: {
571
584
  group: "Manage",
572
- params: [{ name: "steps", kind: "list" }, { name: "submit", kind: "string", optional: true }],
585
+ params: [{ name: "steps", kind: "list" }, { name: "submit", kind: "string", optional: true }, comments, editable],
573
586
  summary: "steps the user approves before you start [{title, detail?, files?, risk?, estimate?}]",
574
587
  },
575
588
  Decision: {
@@ -577,6 +590,7 @@ export const COMPONENTS = {
577
590
  params: [
578
591
  { name: "options", kind: "list" },
579
592
  { name: "criteria", kind: "list" },
593
+ comments,
580
594
  ],
581
595
  summary: "options [{name, scores: 1-5 per criterion, pros?, cons?}] vs criteria; user tunes weights",
582
596
  },
@@ -660,6 +674,10 @@ export const ACTIONS = {
660
674
  params: [{ name: "text", kind: "string" }],
661
675
  summary: "copy text to the clipboard",
662
676
  },
677
+ Queue: {
678
+ params: [{ name: "text", kind: "string" }],
679
+ summary: "add text to the user's reply without sending; the next Send sends it too",
680
+ },
663
681
  } as const satisfies Record<string, ComponentSpec>;
664
682
 
665
683
  export type ActionName = keyof typeof ACTIONS;
@@ -601,6 +601,8 @@ const Interpreter = defineClass(
601
601
  return { kind: "action", type: "send", text };
602
602
  case "Copy":
603
603
  return { kind: "action", type: "copy", text };
604
+ case "Queue":
605
+ return { kind: "action", type: "queue", text };
604
606
  case "OpenUrl":
605
607
  if (!/^https?:\/\//i.test(text)) throw new RuntimeError(first.pos, "OpenUrl needs an http:// or https:// URL");
606
608
  return { kind: "action", type: "openUrl", url: text };
@@ -639,6 +639,8 @@ function block(node: UiNode): string {
639
639
  }
640
640
  case "Button":
641
641
  return `Options: ${buttonLabel(node)}`;
642
+ case "Other":
643
+ return `Options: ${inline(props.label).trim() || "Other…"}`;
642
644
  case "Form":
643
645
  return paragraphs([...blocks(children(props.children), false), `Submit: ${inline(props.submit).trim() || "Send"}`]);
644
646
  case "Timer": {
@@ -64,7 +64,8 @@ export type Action =
64
64
  readonly value: Value;
65
65
  }
66
66
  | { readonly kind: "action"; readonly type: "openUrl"; readonly url: string }
67
- | { readonly kind: "action"; readonly type: "copy"; readonly text: string };
67
+ | { readonly kind: "action"; readonly type: "copy"; readonly text: string }
68
+ | { readonly kind: "action"; readonly type: "queue"; readonly text: string };
68
69
 
69
70
  /** Mutable state of one rendered UI: `$name` → value (keys exclude the `$`). */
70
71
  export type UiState = Readonly<Record<string, Value>>;
@@ -26,3 +26,16 @@ describe("parseInline links", () => {
26
26
  expect(parseInline("[x](javascript:void)")).toEqual([{ kind: "text", text: "x" }]);
27
27
  });
28
28
  });
29
+
30
+ describe("parseInline underscores", () => {
31
+ it("keeps underscores inside identifiers as text", () => {
32
+ const spans = parseInline("One migration for: review_gate per project, task_checks, task_ideas, task_links.");
33
+ expect(spans.every((span) => span.kind === "text")).toBe(true);
34
+ expect(spans.map((span) => span.text).join("")).toBe("One migration for: review_gate per project, task_checks, task_ideas, task_links.");
35
+ });
36
+
37
+ it("still reads _word_ and __word__ at word boundaries", () => {
38
+ expect(parseInline("an _important_ step")[1]).toEqual({ kind: "italic", text: "important" });
39
+ expect(parseInline("a __bold__ word")[1]).toEqual({ kind: "bold", text: "bold" });
40
+ });
41
+ });
@@ -28,10 +28,24 @@ const INLINE =
28
28
  /(`[^`]+`|\[[^\]\n]+\]\([^)\s]+\)|https?:\/\/[^\s<>]*[^\s<>.,;:!?'")\]*_]|\*\*[^*]+\*\*|__[^_]+__|\*[^*\n]+\*|_[^_\n]+_)/;
29
29
  const LINK = /^\[([^\]\n]+)\]\(([^)\s]+)\)$/;
30
30
 
31
+ const WORD_CHAR = /[A-Za-z0-9]/;
32
+
33
+ /** `_x_` inside a word, as in review_gate_per_project, is not emphasis (CommonMark's rule). */
34
+ function intraword(pieces: readonly string[], index: number): boolean {
35
+ const before = pieces[index - 1] ?? "";
36
+ const after = pieces[index + 1] ?? "";
37
+ return WORD_CHAR.test(before.slice(-1)) || WORD_CHAR.test(after.slice(0, 1));
38
+ }
39
+
31
40
  export function parseInline(text: string): Inline[] {
32
41
  const out: Inline[] = [];
33
- for (const piece of text.split(INLINE)) {
42
+ const pieces = text.split(INLINE);
43
+ for (const [index, piece] of pieces.entries()) {
34
44
  if (piece.length === 0) continue;
45
+ if (piece.startsWith("_") && piece.endsWith("_") && intraword(pieces, index)) {
46
+ out.push({ kind: "text", text: piece });
47
+ continue;
48
+ }
35
49
  const link = LINK.exec(piece);
36
50
  if (piece.startsWith("`") && piece.endsWith("`") && piece.length > 1) {
37
51
  out.push({ kind: "code", text: piece.slice(1, -1) });
@@ -96,7 +96,7 @@ export async function renderReplyMarkdown(text: string, load: Loader, find?: Ima
96
96
  }
97
97
 
98
98
  /** What is wrong with a spec: compile errors, files that failed to load, and evaluation errors. Empty when it renders cleanly. */
99
- async function specProblems(spec: string, load: Loader): Promise<{ problems: string[]; roots: UiNode[] | null }> {
99
+ export async function specProblems(spec: string, load: Loader): Promise<{ problems: string[]; roots: UiNode[] | null }> {
100
100
  const compiled = compile(spec);
101
101
  if (compiled.program === null) {
102
102
  return { problems: [`The block does not compile:\n${formatDiagnostics(compiled.diagnostics)}`], roots: null };
@@ -37,5 +37,5 @@ describe("Hermes compatibility", () => {
37
37
  path.join(root, "index.client.tsx"),
38
38
  ];
39
39
  expect(files.flatMap(classesIn)).toEqual([]);
40
- });
40
+ }, 30_000); // Parsing every file takes ~5 s under a full parallel run, past vitest's 5 s default.
41
41
  });
@@ -27,7 +27,8 @@ The \`\`\`ui language used by the Inline UI section below.
27
27
  Syntax: one statement per line. \`$x = 8\` is state inputs bind to; \`name = expr\` names a value and \`f = (a, b) => expr\` a function; each bare expression renders. JS expressions incl. ** ?: ?? ?. ...spread, destructuring, \`x => { const y = ...; return y }\`, \`\${x}\`, the common list and text methods, Math.*, Object.keys/entries, Number(), String(), JSON.stringify; plus round(x, d), fmt(x, d), sum, Load(path). No if, for or reassignment. Named args go last: Slider($n, 0, 10, label: "N").
28
28
  Components (? optional; tone: neutral|good|warn|bad|info if meaningful; more in the next section):
29
29
  ${componentLines(REFERENCE_GROUPS)}
30
- Actions: ${actionList}; a list runs in order; Send posts as the user.
30
+ Actions: ${actionList}; a list runs in order; Send posts as the user, together with anything queued.
31
+ Replies the user builds: when a reply has several independent choices (across cards too), make each a Button with Queue and keep Send for the one that finishes the reply. comments: true lets the user comment on each item, and editable: true lets them rewrite an item's text, before replying; Other() gives a free-form box. Use them where the user may want to adjust what you propose. Plan, Decision, Findings and Form have their own send buttons; do not add another.
31
32
  Data: Load("path") reads JSON/CSV/TSV/JSONL from the workspace, "$BB_THREAD_STORAGE/x.json" or /tmp into lists and objects, and other files (a log, tsc output) as text; never retype values a file or command output holds. Snippet and Image read files the same way. Any other path fails to load: copy the file into $BB_THREAD_STORAGE first.
32
33
  Games, simulations, custom visuals: write \`\`\`app, a self-contained HTML page (inline CSS/JS, CSS vars --foreground --muted-foreground --border --primary --card; sandboxed, no network).`;
33
34
 
@@ -76,6 +77,7 @@ Card("Dark mode", [Estimate([{title: "Theme tokens", low: 0.5, high: 1}, {title:
76
77
 
77
78
  export const AGENT_INSTRUCTIONS = `# Inline UI
78
79
  This chat renders \`\`\`ui and \`\`\`app code blocks as live UI, and the user prefers them to markdown. Use them only in replies to the user, including after a task; never in progress notes, files, commits, PR text or tool input.
80
+ Show each ui spec with the render_ui tool instead of a \`\`\`ui block: write the answer sentence, then call render_ui with the spec (no fence). It shows the UI only when the spec renders; otherwise it returns the errors, and you fix them and call again without telling the user. Write a \`\`\`ui block only when you have no render_ui tool. \`\`\`app blocks stay in the reply.
79
81
  Write \`\`\`ui instead of a markdown table, a comparison of options, a plan (dated items on a Calendar, status or effort as Steps), a series of numbers (chart it), a list of changed files or commits (Changes(), Changes(sha), Commits(), PullRequest() read them from Paseo), or pasted output: save it to $BB_THREAD_STORAGE and Load it into its component (Inline UI for code work, above). For a calculation (how much, what if), make the user's numbers sliders and a list of items with amounts an EditableTable, and compute the result live. To let the user pick, give buttons; to ask more than one question, one Form; never a question tool or a numbered list. When you explain how something works (a flow, a request path, a lifecycle), put it in a \`\`\`ui block, even when asked to be brief: a Diagram of the flow, the steps as Steps({title, detail}) instead of a numbered list in prose, and Snippets of the key lines; file:line references go in the step details. When the user asks to see code or where something is, answer with a Snippet of those lines; to see an image file, an Image. The user never sees what your tools read: a file or image you opened is not on their screen, and pasted code drifts. Open the reply with one plain sentence that gives the answer (previews show only text); the UI carries the rest, so never restate it.
80
82
  Match the content: a trip, places or a route → a Map of the stops, beside any day-by-day plan; a physical thing with parts → Hotspots on its image; a worked solution → Walkthrough; products or places → Entity cards in a Grid, the pages you read → Sources; activity per day → CalendarHeatmap; shares of a whole → SegmentedBar; a funnel → Chart("funnel"); colours → Swatches; picture options → OptionCards. Give a Diagram's key nodes details (text or a Snippet) so a click explains them. When the next steps are questions, end with FollowUps.
81
83
  Wrap each UI in one Card. Examples:
@@ -0,0 +1,29 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { commentText, composeReply, editText, hasOwnNumber } from "./reply";
3
+
4
+ describe("reply", () => {
5
+ it("joins queued items before the final message and drops blanks", () => {
6
+ expect(composeReply(["Fix all", " ", "On step 3 (Checks): use nudge"], "Go ahead with the plan.")).toBe(
7
+ "Fix all\n\nOn step 3 (Checks): use nudge\n\nGo ahead with the plan.",
8
+ );
9
+ expect(composeReply([], "Go")).toBe("Go");
10
+ expect(composeReply(["Only queued"], null)).toBe("Only queued");
11
+ });
12
+
13
+ it("writes comments and edits, and skips empty ones", () => {
14
+ expect(commentText("step 2 (Spec)", " split it ")).toBe("On step 2 (Spec): split it");
15
+ expect(commentText("step 2 (Spec)", " ")).toBeNull();
16
+ expect(editText("step 2", { title: "Spec", detail: "One migration" }, { title: "Spec v2", detail: "One migration" })).toBe(
17
+ 'Edit step 2: title "Spec" → "Spec v2"',
18
+ );
19
+ expect(editText("step 2", { title: "Spec" }, { title: "Spec " })).toBeNull();
20
+ });
21
+
22
+ it("detects titles that carry their own number", () => {
23
+ expect(hasOwnNumber("1. Spec + shared schema")).toBe(true);
24
+ expect(hasOwnNumber("2a. Needs you")).toBe(true);
25
+ expect(hasOwnNumber("3) Release")).toBe(true);
26
+ expect(hasOwnNumber("2026 roadmap")).toBe(false);
27
+ expect(hasOwnNumber("Spec")).toBe(false);
28
+ });
29
+ });
@@ -0,0 +1,33 @@
1
+ // What the user's reply says when it collects queued choices, comments and edits.
2
+
3
+ /** The queued items, then `last`, as one message; blank parts are dropped. */
4
+ export function composeReply(queued: readonly string[], last: string | null): string {
5
+ return [...queued, last ?? ""]
6
+ .map((part) => part.trim())
7
+ .filter((part) => part !== "")
8
+ .join("\n\n");
9
+ }
10
+
11
+ export function commentText(label: string, comment: string): string | null {
12
+ const trimmed = comment.trim();
13
+ return trimmed === "" ? null : `On ${label}: ${trimmed}`;
14
+ }
15
+
16
+ /** `Edit step 2 (Spec): title "A" → "B"; detail "C" → "D"`, or null when nothing changed. */
17
+ export function editText(
18
+ label: string,
19
+ before: Readonly<Record<string, string>>,
20
+ after: Readonly<Record<string, string>>,
21
+ ): string | null {
22
+ const changes = Object.keys(before).flatMap((field) => {
23
+ const was = before[field] ?? "";
24
+ const now = (after[field] ?? was).trim();
25
+ return now === was.trim() ? [] : [`${field} "${was}" → "${now}"`];
26
+ });
27
+ return changes.length === 0 ? null : `Edit ${label}: ${changes.join("; ")}`;
28
+ }
29
+
30
+ /** True when a title already carries its own number, as in "2a. Checks" or "3) Release". */
31
+ export function hasOwnNumber(title: string): boolean {
32
+ return /^\s*\d+[a-z]?[.):]\s/i.test(title);
33
+ }
@@ -42,6 +42,7 @@ export function isAction(value: unknown): value is Action {
42
42
  switch (value.type) {
43
43
  case "send":
44
44
  case "copy":
45
+ case "queue":
45
46
  return typeof value.text === "string";
46
47
  case "openUrl":
47
48
  return typeof value.url === "string";