pi-better-show 0.4.0 → 0.5.2

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.
@@ -1,7 +1,8 @@
1
+ import { NOTE_FIELD } from "../core/blocks.ts";
1
2
  import { inlinePlain } from "../core/inline.ts";
2
3
  import type { FormData, QuestionData } from "../core/types.ts";
3
4
  import { define, PbsElement } from "./base.ts";
4
- import { controlCss, fieldOf, sendingForm, sentBadge, submitRow } from "./controls.ts";
5
+ import { controlCss, fieldOf, noteBox, noteField, sendingForm, sentBadge, submitRow } from "./controls.ts";
5
6
  import { type Child, h, inlineNodes, uid } from "./dom.ts";
6
7
 
7
8
  /** What the agent reads for a question left empty; kept in English whatever the element's language, as pi-herdr-doc-review did. */
@@ -32,9 +33,11 @@ function answerOf(question: QuestionData, entry: Entry): string {
32
33
  export class PbsForm extends PbsElement<FormData> {
33
34
  static override css = controlCss;
34
35
  #entries: Entry[] | undefined;
36
+ #note = "";
35
37
 
36
38
  protected override reset(): void {
37
39
  this.#entries = undefined;
40
+ this.#note = "";
38
41
  }
39
42
 
40
43
  protected view(data: FormData): Node {
@@ -79,6 +82,7 @@ export class PbsForm extends PbsElement<FormData> {
79
82
  question.name,
80
83
  answerOf(question, entries[index] as Entry) || NO_ANSWER,
81
84
  ]);
85
+ fields.push(...noteField(this.#note));
82
86
  if (data.title) fields.unshift(["form", inlinePlain(data.title)]);
83
87
  const delivered = this.answer({
84
88
  kind: "form",
@@ -92,6 +96,9 @@ export class PbsForm extends PbsElement<FormData> {
92
96
  { part: "form", class: "panel form-panel", ...(data.title ? { "aria-label": inlinePlain(data.title) } : {}) },
93
97
  title,
94
98
  questions,
99
+ noteBox(this.t("otherComments"), this.#note, (text) => {
100
+ this.#note = text;
101
+ }),
95
102
  error,
96
103
  row,
97
104
  );
@@ -225,7 +232,7 @@ export class PbsForm extends PbsElement<FormData> {
225
232
  }),
226
233
  ...sent
227
234
  .filter(([name]) => name !== "form" && !known.has(name))
228
- .map(([name, value]): [string, string] => [name, value]),
235
+ .map(([name, value]): [string, string] => [name === NOTE_FIELD ? this.t("otherComments") : name, value]),
229
236
  ];
230
237
  return h(
231
238
  "section",
@@ -1,9 +1,9 @@
1
- import { reviewItemName } from "../core/blocks.ts";
1
+ import { NOTE_FIELD, reviewItemName } from "../core/blocks.ts";
2
2
  import { inlinePlain } from "../core/inline.ts";
3
3
  import type { ReviewData, ReviewItemData } from "../core/types.ts";
4
4
  import { type AnsweredFields, define, PbsElement } from "./base.ts";
5
5
  import { configuration } from "./config.ts";
6
- import { controlCss, sendingForm, sentBadge, submitRow } from "./controls.ts";
6
+ import { controlCss, noteBox, noteField, sendingForm, sentBadge, submitRow } from "./controls.ts";
7
7
  import { type Child, h, inlineNodes, prose, uid } from "./dom.ts";
8
8
 
9
9
  const reviewCss = `${controlCss}
@@ -36,11 +36,13 @@ export class PbsReview extends PbsElement<ReviewData> {
36
36
  static override css = reviewCss;
37
37
  #picked: string | undefined;
38
38
  #comments: string[] | undefined;
39
+ #note = "";
39
40
  readonly #group = uid("pbs-pick");
40
41
 
41
42
  protected override reset(): void {
42
43
  this.#picked = undefined;
43
44
  this.#comments = undefined;
45
+ this.#note = "";
44
46
  }
45
47
 
46
48
  protected view(data: ReviewData): Node {
@@ -71,10 +73,20 @@ export class PbsReview extends PbsElement<ReviewData> {
71
73
  });
72
74
  const silent = named.filter((_, index) => !(comments[index] as string).trim());
73
75
  if (silent.length > 0) fields.push(["silent", silent.join(", ")]);
76
+ fields.push(...noteField(this.#note));
74
77
  if (this.answer({ kind: "review", ...(data.title ? { title: inlinePlain(data.title) } : {}), fields }))
75
78
  status.textContent = this.t("sent");
76
79
  };
77
- return sendingForm(send, { part: "review", class: "panel form-panel review" }, title, grid, row);
80
+ return sendingForm(
81
+ send,
82
+ { part: "review", class: "panel form-panel review" },
83
+ title,
84
+ grid,
85
+ noteBox(this.t("otherComments"), this.#note, (text) => {
86
+ this.#note = text;
87
+ }),
88
+ row,
89
+ );
78
90
  }
79
91
 
80
92
  private item(item: ReviewItemData, index: number, pickLabel: string | undefined, comments: string[]): HTMLElement {
@@ -168,6 +180,7 @@ export class PbsReview extends PbsElement<ReviewData> {
168
180
  const comments = values("comment");
169
181
  const [picked] = values("picked");
170
182
  const [silent] = values("silent");
183
+ const [note] = values(NOTE_FIELD);
171
184
  const row = (label: string, value: string) => h("div", null, h("dt", null, label), h("dd", null, value));
172
185
  return h(
173
186
  "section",
@@ -179,6 +192,7 @@ export class PbsReview extends PbsElement<ReviewData> {
179
192
  picked && row(this.t("picked"), picked),
180
193
  items.map((item, index) => row(item, comments[index] ?? "")),
181
194
  silent && row(this.t("noFeedback"), silent),
195
+ note && row(this.t("otherComments"), note),
182
196
  ),
183
197
  );
184
198
  }
@@ -13,6 +13,7 @@ export interface Strings {
13
13
  unanswered: string;
14
14
  other: string;
15
15
  feedbackNote: string;
16
+ otherComments: string;
16
17
  noFeedback: string;
17
18
  reviewFallback: string;
18
19
  enlarge: string;
@@ -65,6 +66,7 @@ export const STRINGS: Record<Locale, Strings> = {
65
66
  unanswered: "Not answered yet: ",
66
67
  other: "Other (type your own)",
67
68
  feedbackNote: "Feedback (leave blank for none)",
69
+ otherComments: "Other comments",
68
70
  noFeedback: "No feedback",
69
71
  reviewFallback: "Review",
70
72
  enlarge: "Enlarge",
@@ -114,6 +116,7 @@ export const STRINGS: Record<Locale, Strings> = {
114
116
  unanswered: "還沒回答:",
115
117
  other: "其他(自行填寫)",
116
118
  feedbackNote: "回饋(留白代表沒意見)",
119
+ otherComments: "其他意見",
117
120
  noFeedback: "沒有意見",
118
121
  reviewFallback: "回饋",
119
122
  enlarge: "放大",
@@ -0,0 +1,35 @@
1
+ import { BLOCK_KINDS } from "../core/types.ts";
2
+
3
+ /**
4
+ * The block check for the agent: what is wrong with the blocks of a Markdown file, as the text `show_doc` and the
5
+ * write hook hand back. Nothing here loads at import: the checker (and with it the YAML parser) loads on the first
6
+ * file that holds a block fence, and Mermaid on the first file that holds a diagram.
7
+ */
8
+
9
+ const KINDS = BLOCK_KINDS.filter((kind) => kind !== "alert");
10
+ const BLOCK_FENCE = new RegExp(`^ {0,3}(?:\`{3,}|~{3,})[ \\t]*(?:${KINDS.join("|")})\\b`, "im");
11
+ const MERMAID_FENCE = /^ {0,3}(?:`{3,}|~{3,})[ \t]*mermaid\b/im;
12
+
13
+ export const hasBlockFence = (markdown: string): boolean => BLOCK_FENCE.test(markdown);
14
+
15
+ /** The problems of `markdown` worded for the agent, or undefined when there are none or the file holds no block fence. */
16
+ export async function checkText(name: string, markdown: string): Promise<string | undefined> {
17
+ if (!hasBlockFence(markdown)) return undefined;
18
+ const { checkBlocks, formatProblems } = await import("../core/check.ts");
19
+ const mermaid = MERMAID_FENCE.test(markdown) ? (await import("../server/index.ts")).mermaidSvg : undefined;
20
+ const problems = checkBlocks(markdown, {
21
+ ...(mermaid
22
+ ? {
23
+ mermaid: (source: string) => {
24
+ try {
25
+ mermaid(source);
26
+ return undefined;
27
+ } catch (error) {
28
+ return ((error instanceof Error ? error.message : String(error)).split("\n")[0] as string).trim();
29
+ }
30
+ },
31
+ }
32
+ : {}),
33
+ });
34
+ return problems.length === 0 ? undefined : formatProblems(name, problems);
35
+ }
@@ -15,6 +15,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:pat
15
15
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
16
16
  import { encodeAnswer } from "../core/answer.ts";
17
17
  import type { Answer } from "../core/types.ts";
18
+ import { checkText } from "./check.ts";
18
19
  import {
19
20
  ANSWER_EVENT,
20
21
  ANSWER_RESULT_EVENT,
@@ -319,13 +320,35 @@ export function createBetterShow(pi: ExtensionAPI, deps: Deps = defaultDeps()) {
319
320
  return fromHome.startsWith("..") || isAbsolute(fromHome) ? basename(absolute) : join("~", fromHome);
320
321
  };
321
322
 
323
+ const nameFor = (cwd: string, absolute: string): string => {
324
+ const rel = relative(deps.realpath(cwd), absolute);
325
+ return rel.startsWith("..") ? outside(absolute) : rel;
326
+ };
327
+
322
328
  const load = (cwd: string, path: string): Loaded => {
323
329
  if (/[\n\r]/.test(path)) throw new Error(`cannot open a path containing a line break: ${JSON.stringify(path)}`);
324
330
  const absolute = deps.realpath(isAbsolute(path) ? path : resolve(cwd, path));
325
331
  const content = deps.readFile(absolute);
326
332
  if (content === undefined) throw new Error(`cannot read ${path}`);
327
- const rel = relative(deps.realpath(cwd), absolute);
328
- return { absolute, content, display: rel.startsWith("..") ? outside(absolute) : rel };
333
+ return { absolute, content, display: nameFor(cwd, absolute) };
334
+ };
335
+
336
+ /** What is wrong with the blocks of a Markdown text, worded for the agent; a failure of the check itself is reported, not hidden. */
337
+ const problemsIn = async (display: string, content: string): Promise<string | undefined> => {
338
+ try {
339
+ return await checkText(display, content);
340
+ } catch (error) {
341
+ return `Block check of ${display} failed: ${(error as Error).message}`;
342
+ }
343
+ };
344
+
345
+ /** The block problems of a Markdown file the agent just wrote, or undefined. */
346
+ const problemsOfFile = async (cwd: string, absolute: string): Promise<string | undefined> => {
347
+ if (!MARKDOWN_FILE.test(absolute)) return undefined;
348
+ const content = deps.readFile(absolute);
349
+ return content === undefined
350
+ ? undefined
351
+ : problemsIn(docs.get(absolute)?.display ?? nameFor(cwd, absolute), content);
329
352
  };
330
353
 
331
354
  /** Opens pages in the default browser; a page whose tab the user closed opens again. */
@@ -396,9 +419,15 @@ export function createBetterShow(pi: ExtensionAPI, deps: Deps = defaultDeps()) {
396
419
  opened.push(`${list(texts)} in ${editor}`);
397
420
  }
398
421
  const feedback = texts.length > 0 ? " Their saved edits will reach you as review feedback." : "";
422
+ const checks = (
423
+ await Promise.all(
424
+ loaded.filter((doc) => MARKDOWN_FILE.test(doc.absolute)).map((doc) => problemsIn(doc.display, doc.content)),
425
+ )
426
+ ).filter((found): found is string => found !== undefined);
427
+ const problems = checks.map((found) => `\n\n${found}`).join("");
399
428
  return {
400
429
  opened: loaded.map((doc) => doc.display),
401
- text: `Opened ${opened.join(" and ")} and returned without waiting for the user.${feedback}`,
430
+ text: `Opened ${opened.join(" and ")} and returned without waiting for the user.${feedback}${problems}`,
402
431
  };
403
432
  };
404
433
 
@@ -445,6 +474,7 @@ export function createBetterShow(pi: ExtensionAPI, deps: Deps = defaultDeps()) {
445
474
 
446
475
  return {
447
476
  show,
477
+ problemsOfFile,
448
478
  docs,
449
479
  pages,
450
480
  edits,
@@ -55,9 +55,16 @@ export function install(pi: ExtensionAPI, deps: Deps = defaultDeps()): BetterSho
55
55
  const path = pathOf(ctx.cwd, event.input);
56
56
  if (!path) return;
57
57
  show.agentWrote(event.toolCallId, path);
58
- if (event.isError || !ctx.hasUI || process.env[AUTO_OPEN_ENV] === "off") return;
58
+ if (event.isError) return;
59
+ // The agent reads the block problems of what it just wrote in the result of the write itself.
60
+ const found = await show.problemsOfFile(ctx.cwd, path);
61
+ const amended =
62
+ found === undefined
63
+ ? undefined
64
+ : { content: [...event.content, { type: "text" as const, text: `\n\n${found}` }] };
65
+ if (!ctx.hasUI || process.env[AUTO_OPEN_ENV] === "off") return amended;
59
66
  const followUp = show.miniSddFollowUp(path);
60
- if (followUp.length === 0) return;
67
+ if (followUp.length === 0) return amended;
61
68
  try {
62
69
  await show.show(
63
70
  ctx.cwd,
@@ -68,6 +75,7 @@ export function install(pi: ExtensionAPI, deps: Deps = defaultDeps()): BetterSho
68
75
  } catch (error) {
69
76
  ctx.ui.notify(`better-show could not open ${path}: ${(error as Error).message}`, "warning");
70
77
  }
78
+ return amended;
71
79
  });
72
80
 
73
81
  const stopAnswers = pi.events.on(ANSWER_EVENT, show.onAnswer);
@@ -25,7 +25,8 @@ export const DESCRIPTION =
25
25
  "Put decisions that belong to the page (several questions, or a choice after a comparison) in a ```form at its end; ask a single short question with your question tool. " +
26
26
  'An .html page runs as written under a sandbox (scripts and forms, no storage, nothing from other sites): a <form action="cgi-bin:pi-answer"> sends its fields to you when submitted, and piBetterShow.send(fields) does the same from a script. ' +
27
27
  'When a page needs interaction (inputs that recompute, tabs, filters), write a .tsx or .jsx file and open it with view "page": React is built in, and the "pi-kit" module exports PbsBlock, PbsForm, PbsOptions, PbsReview, PbsChecklist, PbsTable, PbsCallout, PbsCards, PbsMindmap, PbsSuggest, PbsSteps, PbsStats, PbsDiff, PbsDiagram, PbsTree (props data, onAnswer; PbsBlock draws a parsed block), parse, encodeAnswer, and send(answer or fields) to hand you any values as a message. Import sibling modules freely; import no CSS. ' +
28
- "It returns at once without waiting for the user. Pages reload and edited documents refresh when you change them.";
28
+ 'It returns at once without waiting for the user. Block problems (a block that will not parse, a text value cut at " #", an unknown key) come back with line numbers in its result and in the result of your write or edit of a .md file; quote text values that hold " #" or ": ". ' +
29
+ "Pages reload and edited documents refresh when you change them.";
29
30
 
30
31
  export const parameters = Type.Object({
31
32
  paths: Type.Array(Type.String({ description: "File path, absolute or relative to the working directory" }), {