@g9tm/aiassistant-lynx 1.0.0 → 1.1.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.
package/README.md CHANGED
@@ -7,8 +7,14 @@ names and the same ways to customise as the Svelte package.
7
7
  accessibility labels survive. Do not exclude the package from that build.
8
8
  - Surfaces and parts: the root, the chat, the panel in its layouts, a recycled message list (the growing answer is drawn
9
9
  below it), the composer, the work card, blocks and approval cards.
10
- - Customising: theme tokens as an object (Lynx has no CSS variables), per-part classes and styles, `unstyled`, and
11
- replaced components by name.
10
+ - Pages: `History`, `Abilities`, `KnowledgePage`, `LearnedPage`, `FindingsPage`, `RoutineWizard`, `ActionsPage`
11
+ (or `Page` with a `kind`). Small surfaces: `Surfaces` with `kind` `hero`, `bar-button` or `ask-about`.
12
+ - The built-in `Chart`: bars, one or several lines with a legend, and a donut (lines and the donut use the `svg`
13
+ element, Lynx 3.7). `StagesThinking` and `ThinkingOrb` are their own parts.
14
+ - Customising: theme tokens as an object (Lynx has no CSS variables; series colours `chart-1`, `chart-2`...), per-part
15
+ classes and styles, `unstyled`, and replaced components by name. Every slot (`Button`, `PinPad`, `SecretField`,
16
+ `Dialog`, `Sheet`, `Chart`), every page and `Surfaces` can be replaced through `components` of `AssistantRoot`; the
17
+ replacement gets the same props plus the library's own as `Default`.
12
18
  - Laid out by the rules a device engine holds: rows reversed for right to left, growth by the long-hand flex
13
19
  properties, a size on every input, `display: "flex"` on every container.
14
20
  - `@g9tm/aiassistant-lynx/admin`: the manager's page as a separate entry.
package/dist/admin.jsx CHANGED
@@ -6,7 +6,7 @@
6
6
  import { useEffect, useState } from "@lynx-js/react";
7
7
  import { AdminClient, adminTexts } from "@g9tm/aiassistant/admin";
8
8
  import { cls, fill, rowOf, tok, useUi } from "./context.jsx";
9
- import { Button } from "./parts.jsx";
9
+ import { Button } from "./slots.jsx";
10
10
  const grow = { ...fill, minWidth: 0 };
11
11
  function useAdmin() {
12
12
  const ui = useUi();
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The built-in light chart for Lynx: horizontal bars for rankings, bars and stacks; one or several lines on a time axis
3
+ * (a legend for several); and a donut with its legend. Lines and the donut are an SVG drawn from numbers and theme
4
+ * colours only (the `svg` element's content, Lynx 3.7). A host gives its own chart library by replacing `Chart`, or
5
+ * the whole block with `components.Block.chart`; either gets the same view.
6
+ */
7
+ import type { BlockView } from "@g9tm/aiassistant";
8
+ import type { Part } from "./context.jsx";
9
+ export type ChartView = Extract<BlockView, {
10
+ type: "chart";
11
+ }>;
12
+ export declare const Chart: Part<{
13
+ view: ChartView;
14
+ }>;
package/dist/chart.jsx ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The built-in light chart for Lynx: horizontal bars for rankings, bars and stacks; one or several lines on a time axis
3
+ * (a legend for several); and a donut with its legend. Lines and the donut are an SVG drawn from numbers and theme
4
+ * colours only (the `svg` element's content, Lynx 3.7). A host gives its own chart library by replacing `Chart`, or
5
+ * the whole block with `components.Block.chart`; either gets the same view.
6
+ */
7
+ import { formatNumber, shares } from "@g9tm/aiassistant";
8
+ import { cls, fill, rowOf, swappable, tok, useUi } from "./context.jsx";
9
+ const PALETTE = ["#8a4b2a", "#2a6f8a", "#5f8a2a", "#8a2a6a", "#a35a00", "#4b4b8a"];
10
+ const W = 300;
11
+ const H = 140;
12
+ /** The colour of series or slice i: the host's chart-1, chart-2... tokens (the first falls back to chart-bar). */
13
+ function colour(ui, i) {
14
+ const base = i === 0 ? tok(ui, "chart-bar", "#8a4b2a") : (PALETTE.at(i % PALETTE.length) ?? "#888");
15
+ return tok(ui, "chart-" + String(i + 1), base).replace(/[^#\w(),.% -]/gu, ""); // it goes into SVG text: no quotes or tags
16
+ }
17
+ function Legend(props) {
18
+ const ui = useUi();
19
+ return (<view className="g9a-legend" style={{ ...rowOf(ui, "10px"), flexWrap: "wrap", marginTop: "6px" }}>
20
+ {props.names.map((n, i) => (<view key={i} style={rowOf(ui, "4px")}>
21
+ <view style={{ width: "10px", height: "10px", borderRadius: "5px", backgroundColor: colour(ui, i) }}/>
22
+ <text style={{ fontSize: "12px", color: tok(ui, "muted", "#6b6660") }} text-maxline="1">{n}</text>
23
+ </view>))}
24
+ </view>);
25
+ }
26
+ function svg(viewBox, body) {
27
+ return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="' + viewBox + '" preserveAspectRatio="none">' + body + "</svg>";
28
+ }
29
+ export const Chart = swappable("Chart", (props) => {
30
+ const ui = useUi();
31
+ const v = props.view;
32
+ const first = v.series[0]?.values ?? [];
33
+ if (v.kind === "hbars" || v.kind === "bars" || v.kind === "stacked") {
34
+ const sh = shares(first);
35
+ return (<view className="g9a-hbars">
36
+ {v.labels.map((l, i) => (<view key={i} className={cls(ui, "block.chart.bar")} style={{ marginBottom: "6px" }}>
37
+ <text text-maxline="1">{l}</text>
38
+ {/* a row, so in right to left the bar grows from the right */}
39
+ <view style={{ ...rowOf(ui), height: "10px", borderRadius: "5px", backgroundColor: tok(ui, "surface", "#fff") }}>
40
+ <view style={{ height: "10px", borderRadius: "5px", width: String(Math.round((sh.at(i) ?? 0) * 100)) + "%", backgroundColor: colour(ui, 0) }}/>
41
+ </view>
42
+ <text style={{ fontSize: "12px" }}>{formatNumber(first.at(i) ?? 0, ui.texts.locale)}</text>
43
+ </view>))}
44
+ </view>);
45
+ }
46
+ if (v.kind === "donut") {
47
+ const total = first.reduce((a, b) => a + Math.max(0, b), 0) || 1;
48
+ const p = (f) => (50 + 40 * Math.sin(f * 2 * Math.PI)).toFixed(2) + " " + (50 - 40 * Math.cos(f * 2 * Math.PI)).toFixed(2);
49
+ let at = 0;
50
+ const arcs = first.map((x, i) => {
51
+ const from = at;
52
+ at += Math.max(0, x) / total;
53
+ const to = Math.min(at, from + 0.9999);
54
+ return to <= from ? "" : '<path d="M ' + p(from) + " A 40 40 0 " + (to - from > 0.5 ? "1" : "0") + " 1 " + p(to) + '" fill="none" stroke="' + colour(ui, i) + '" stroke-width="14"/>';
55
+ });
56
+ return (<view className="g9a-donut">
57
+ <svg content={svg("0 0 100 100", arcs.join(""))} style={{ width: "120px", height: "120px" }}/>
58
+ <Legend names={v.labels}/>
59
+ </view>);
60
+ }
61
+ // a line (or several) on a time axis: in right to left time runs from the right
62
+ const rtl = ui.assistant.host.dir === "rtl";
63
+ const max = Math.max(1, ...v.series.flatMap((s) => s.values));
64
+ const path = (values) => values.map((x, i) => {
65
+ const across = (i / Math.max(1, values.length - 1)) * W;
66
+ return (i === 0 ? "M" : "L") + (rtl ? W - across : across).toFixed(1) + " " + (H - (x / max) * H).toFixed(1);
67
+ }).join(" ");
68
+ const lines = v.series.map((s, i) => '<path d="' + path(s.values) + '" fill="none" stroke="' + colour(ui, i) + '" stroke-width="2" stroke-linejoin="round"/>');
69
+ return (<view className={cls(ui, "block.chart.line")}>
70
+ <view style={{ ...rowOf(ui), height: String(H) + "px" }}>
71
+ <svg content={svg("0 0 " + String(W) + " " + String(H), lines.join(""))} style={{ ...fill, height: String(H) + "px" }}/>
72
+ </view>
73
+ {v.series.length > 1 ? <Legend names={v.series.map((s) => s.name)}/> : null}
74
+ </view>);
75
+ });
package/dist/context.d.ts CHANGED
@@ -6,6 +6,8 @@ import type { ReactNode } from "@lynx-js/react";
6
6
  import type { Assistant, AssistantSnapshot, PartName, PartStyles, Texts } from "@g9tm/aiassistant";
7
7
  /** Any component a host gives in place of the library's (it gets the same props, plus the default as Default). */
8
8
  export type HostComponent = (props: Record<string, unknown>) => ReactNode;
9
+ /** A component of the library (a plain function of its props). */
10
+ export type Part<P> = (props: P) => ReactNode;
9
11
  export interface Overrides {
10
12
  [name: string]: HostComponent | Record<string, HostComponent> | undefined;
11
13
  Block?: Record<string, HostComponent>;
@@ -42,4 +44,9 @@ export declare function rowOf(ui: LynxUi, gap?: string): Record<string, string>;
42
44
  /** A theme token (the host's over the defaults), or the fallback. */
43
45
  export declare function tok(ui: LynxUi, name: string, fallback?: string): string;
44
46
  export declare function override(ui: LynxUi, name: string): HostComponent | undefined;
47
+ /**
48
+ * A component a host can replace by name wherever it is drawn, by the library or by the host's own composition. The
49
+ * host's one gets the same props plus the library's as `Default`, so it can wrap it without drawing itself again.
50
+ */
51
+ export declare function swappable<P extends object>(name: string, Base: Part<P>): Part<P>;
45
52
  export declare function blockOverride(ui: LynxUi, type: string): HostComponent | undefined;
package/dist/context.jsx CHANGED
@@ -41,6 +41,16 @@ export function override(ui, name) {
41
41
  const c = new Map(Object.entries(ui.components)).get(name);
42
42
  return typeof c === "function" ? c : undefined;
43
43
  }
44
+ /**
45
+ * A component a host can replace by name wherever it is drawn, by the library or by the host's own composition. The
46
+ * host's one gets the same props plus the library's as `Default`, so it can wrap it without drawing itself again.
47
+ */
48
+ export function swappable(name, Base) {
49
+ return (props) => {
50
+ const Own = override(useUi(), name);
51
+ return Own ? <Own {...props} Default={Base}/> : <Base {...props}/>;
52
+ };
53
+ }
44
54
  export function blockOverride(ui, type) {
45
55
  return ui.components.Block ? new Map(Object.entries(ui.components.Block)).get(type) : undefined;
46
56
  }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,13 @@
1
1
  /** @g9tm/aiassistant-lynx: ReactLynx components of the G9 AI assistant, customisable like the Svelte ones. */
2
- export { AssistantRoot, AssistantChat, AssistantPanel, MessageList } from "./surfaces.jsx";
3
- export { ApprovalCard, BlockView, Cards, Composer, Message, RevealText, Small, TextView, WorkCard } from "./parts.jsx";
4
- export { cls, override, blockOverride, tok, useSnapshot, useUi, UiProvider } from "./context.jsx";
2
+ export { AssistantRoot, AssistantChat, AssistantPanel, MessageList, PdfDownload, Surfaces } from "./surfaces.jsx";
3
+ export type { SurfaceKind, SurfaceProps } from "./surfaces.jsx";
4
+ export { ApprovalCard, BlockView, Cards, Composer, CsvButton, Message, RevealText, Small, StagesThinking, TextView, ThinkingOrb, WorkCard } from "./parts.jsx";
5
+ export { Chart } from "./chart.jsx";
6
+ export type { ChartView } from "./chart.jsx";
7
+ export { Button, Dialog, field, PinPad, SecretField } from "./slots.jsx";
8
+ export type { ButtonProps } from "./slots.jsx";
9
+ export type { CsvButtonProps } from "./parts.jsx";
10
+ export { Abilities, ActionsPage, FindingsPage, History, HistoryRow, KnowledgePage, LearnedPage, Page, RoutineWizard, SlotPicker } from "./pages.jsx";
11
+ export type { HistoryRowProps, PageKind, PageProps, SlotPickerProps } from "./pages.jsx";
12
+ export { cls, fill, override, blockOverride, rowOf, swappable, tok, useSnapshot, useUi, UiProvider } from "./context.jsx";
5
13
  export type { HostComponent, LynxUi, Overrides } from "./context.jsx";
package/dist/index.js CHANGED
@@ -1,4 +1,7 @@
1
1
  /** @g9tm/aiassistant-lynx: ReactLynx components of the G9 AI assistant, customisable like the Svelte ones. */
2
- export { AssistantRoot, AssistantChat, AssistantPanel, MessageList } from "./surfaces.jsx";
3
- export { ApprovalCard, BlockView, Cards, Composer, Message, RevealText, Small, TextView, WorkCard } from "./parts.jsx";
4
- export { cls, override, blockOverride, tok, useSnapshot, useUi, UiProvider } from "./context.jsx";
2
+ export { AssistantRoot, AssistantChat, AssistantPanel, MessageList, PdfDownload, Surfaces } from "./surfaces.jsx";
3
+ export { ApprovalCard, BlockView, Cards, Composer, CsvButton, Message, RevealText, Small, StagesThinking, TextView, ThinkingOrb, WorkCard } from "./parts.jsx";
4
+ export { Chart } from "./chart.jsx";
5
+ export { Button, Dialog, field, PinPad, SecretField } from "./slots.jsx";
6
+ export { Abilities, ActionsPage, FindingsPage, History, HistoryRow, KnowledgePage, LearnedPage, Page, RoutineWizard, SlotPicker } from "./pages.jsx";
7
+ export { cls, fill, override, blockOverride, rowOf, swappable, tok, useSnapshot, useUi, UiProvider } from "./context.jsx";
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The assistant's pages for ReactLynx: history, abilities, knowledge, what it learned, findings, routines and the
3
+ * actions it took. Each reads its own endpoint (as the Svelte pages do), with type checks only; each page is
4
+ * replaceable by name (`History`, `Abilities`...), and its rows draw with the Button slot. History has four tabs with
5
+ * counts, a search, pin and delete; the routine wizard asks a routine's slots (a picker for things, typed fields for the
6
+ * rest), previews it, and runs it with the person's code.
7
+ */
8
+ import type { ConversationRow, RoutineSlot } from "@g9tm/aiassistant/pages";
9
+ export type PageKind = "history" | "abilities" | "knowledge" | "learned" | "findings" | "routines" | "actions";
10
+ export interface PageProps {
11
+ onOpen?: (conversationId: string) => void;
12
+ }
13
+ /** A page by its kind (history and the routine wizard have their own state; the rest read one endpoint). */
14
+ export declare function Page(props: PageProps & {
15
+ kind: PageKind;
16
+ }): import("@lynx-js/react").JSX.Element;
17
+ export interface HistoryRowProps {
18
+ row: ConversationRow;
19
+ onOpen: () => void;
20
+ onPin: () => void;
21
+ onDelete: () => void;
22
+ }
23
+ /** One conversation: its title opens it; pin (or unpin) and delete keep their size. Replaceable as `HistoryRow`. */
24
+ export declare const HistoryRow: import("./context.jsx").Part<HistoryRowProps>;
25
+ export interface SlotPickerProps {
26
+ slot: RoutineSlot;
27
+ onPick: (pick: {
28
+ id: string;
29
+ label: string;
30
+ }) => void;
31
+ onClose: () => void;
32
+ }
33
+ /** A searchable picker over the host's things of the slot's kind (asked after a short pause). Replaceable as `SlotPicker`. */
34
+ export declare const SlotPicker: import("./context.jsx").Part<SlotPickerProps>;
35
+ export declare const History: import("./context.jsx").Part<PageProps>;
36
+ export declare const Abilities: import("./context.jsx").Part<PageProps>;
37
+ export declare const KnowledgePage: import("./context.jsx").Part<PageProps>;
38
+ export declare const LearnedPage: import("./context.jsx").Part<PageProps>;
39
+ export declare const FindingsPage: import("./context.jsx").Part<PageProps>;
40
+ export declare const RoutineWizard: import("./context.jsx").Part<PageProps>;
41
+ export declare const ActionsPage: import("./context.jsx").Part<PageProps>;
package/dist/pages.jsx ADDED
@@ -0,0 +1,336 @@
1
+ /**
2
+ * The assistant's pages for ReactLynx: history, abilities, knowledge, what it learned, findings, routines and the
3
+ * actions it took. Each reads its own endpoint (as the Svelte pages do), with type checks only; each page is
4
+ * replaceable by name (`History`, `Abilities`...), and its rows draw with the Button slot. History has four tabs with
5
+ * counts, a search, pin and delete; the routine wizard asks a routine's slots (a picker for things, typed fields for the
6
+ * rest), previews it, and runs it with the person's code.
7
+ */
8
+ import { useEffect, useRef, useState } from "@lynx-js/react";
9
+ import { afterConfirm, ApiError, arr, formatNumber, needsCode, num, obj, planView, str, timer } from "@g9tm/aiassistant";
10
+ import { HISTORY_TABS, historyTabs, missingSlots, pageCalls, readConversations, readPicks, readRoutines, slotValue, tabCounts } from "@g9tm/aiassistant/pages";
11
+ import { cls, fill, rowOf, swappable, tok, useSnapshot, useUi } from "./context.jsx";
12
+ import { BlockView } from "./parts.jsx";
13
+ import { Button, Dialog, field, PinPad } from "./slots.jsx";
14
+ const PATHS = new Map([
15
+ ["abilities", "capabilities"], ["knowledge", "knowledge"], ["learned", "learned/dashboard?capability=chat"], ["findings", "findings"], ["actions", "conversations"],
16
+ ]);
17
+ const grow = { ...fill, minWidth: 0 };
18
+ function Title(props) {
19
+ return <text style={{ fontWeight: "bold", marginTop: "8px", marginBottom: "4px" }} text-maxline="1">{props.text}</text>;
20
+ }
21
+ /** One line of a page: its text takes the room, its buttons keep their size. */
22
+ function Line(props) {
23
+ const ui = useUi();
24
+ return (<view style={{ ...rowOf(ui, "6px"), minHeight: "32px" }}>
25
+ <view style={grow}><text style={{ color: props.muted ? tok(ui, "muted", "#6b6660") : tok(ui, "ink", "#22201d") }} text-maxline="2">{props.text}</text></view>
26
+ {props.children}
27
+ </view>);
28
+ }
29
+ /** Nothing to show yet: a dash, never an empty hole or a key. */
30
+ function Empty() {
31
+ const ui = useUi();
32
+ return <text className="g9a-empty" style={{ color: tok(ui, "muted", "#6b6660") }}>—</text>;
33
+ }
34
+ /** A page's frame: the network notice above, the body in a vertical scroll. */
35
+ function Frame(props) {
36
+ const ui = useUi();
37
+ return (<view className={cls(ui, "panel.body")} style={{ display: "flex", flexDirection: "column", ...fill, minHeight: 0, padding: "12px", backgroundColor: tok(ui, "surface", "#fff") }}>
38
+ {props.failed ? <text style={{ color: tok(ui, "danger", "#b42318") }} text-maxline="2">{ui.texts.t("error.network")}</text> : null}
39
+ <scroll-view scroll-orientation="vertical" style={{ ...fill }}>{props.children}</scroll-view>
40
+ </view>);
41
+ }
42
+ /** A page by its kind (history and the routine wizard have their own state; the rest read one endpoint). */
43
+ export function Page(props) {
44
+ if (props.kind === "history")
45
+ return <HistoryBody {...props}/>;
46
+ if (props.kind === "routines")
47
+ return <RoutineBody />;
48
+ return <PlainPage {...props}/>;
49
+ }
50
+ function PlainPage(props) {
51
+ const ui = useUi();
52
+ const t = ui.texts.t;
53
+ const api = ui.assistant.api;
54
+ const snap = useSnapshot(ui.assistant);
55
+ const [data, setData] = useState(null);
56
+ const [failed, setFailed] = useState(false);
57
+ const load = () => api.get(PATHS.get(props.kind) ?? "").then((r) => { setData(obj(r)); setFailed(false); }, () => { setData({}); setFailed(true); });
58
+ useEffect(() => { void load(); }, [props.kind]);
59
+ const act = (path, body) => { void api.post(path, body).catch(() => undefined).then(load); };
60
+ const d = data ?? {};
61
+ const list = (rows, draw) => (data !== null && rows.length === 0 ? <Empty /> : rows.map(draw));
62
+ const id = (r) => encodeURIComponent(str(r["id"]));
63
+ let body = null;
64
+ if (props.kind === "abilities") {
65
+ const groups = arr(d["groups"]).map(obj);
66
+ const closed = arr(d["closed"]).map(obj);
67
+ body = (<view>
68
+ {data !== null && groups.length === 0 && closed.length === 0 ? <Empty /> : null}
69
+ {groups.map((g) => (<view key={str(g["name"])}>
70
+ <Title text={str(g["title"], str(g["name"]))}/>
71
+ {arr(g["tools"]).map(obj).map((x) => <Line key={str(x["name"])} text={str(x["title"], str(x["name"]))}/>)}
72
+ </view>))}
73
+ {closed.map((c) => <Line key={str(c["name"])} text={str(c["name"]) + " · " + str(c["layer"])} muted/>)}
74
+ </view>);
75
+ }
76
+ else if (props.kind === "knowledge") {
77
+ body = <view>{list(arr(d["notes"] ?? d["items"]).map(obj), (n, i) => <Line key={i} text={str(n["text"], str(n["name"]))}/>)}</view>;
78
+ }
79
+ else if (props.kind === "learned") {
80
+ body = (<view>
81
+ {data !== null ? <Title text={formatNumber(Math.round(num(d["modelFreeRate"]) * 100), ui.texts.locale) + "% · " + formatNumber(num(d["tokensSaved"]), ui.texts.locale)}/> : null}
82
+ {list(arr(d["items"]).map(obj), (x, i) => <Line key={i} text={str(x["signature"]) + " · " + str(x["status"]) + " · " + formatNumber(num(x["hits"]), ui.texts.locale)} muted={str(x["status"]) !== "approved"}/>)}
83
+ </view>);
84
+ }
85
+ else if (props.kind === "findings") {
86
+ body = (<view>
87
+ {list(arr(d["findings"]).map(obj), (f) => (<Line key={str(f["id"])} text={str(obj(f["title"])["text"], t(str(obj(f["title"])["key"])))}>
88
+ <Button label="✓" onTap={() => act("findings/" + id(f) + "/fixed")}/>
89
+ <Button label={t("no")} onTap={() => act("findings/" + id(f) + "/dismiss", { reason: "—" })}/>
90
+ </Line>))}
91
+ </view>);
92
+ }
93
+ else {
94
+ const done = [...snap.plans.values()].filter((p) => p.answered === "confirmed");
95
+ body = (<view>
96
+ {done.length === 0 ? <Empty /> : done.map((p) => <Line key={p.id} text={p.title}><Button label={t("undo.all")} onTap={() => void ui.assistant.undo(p.id)}/></Line>)}
97
+ </view>);
98
+ }
99
+ return <Frame failed={failed}>{body}</Frame>;
100
+ }
101
+ /** One tab of the history: its name and its count in separate texts (a number and a Persian word in one text reverse). */
102
+ function Tab(props) {
103
+ const ui = useUi();
104
+ const ink = props.on ? tok(ui, "accent-ink", "#fff") : tok(ui, "ink", "#22201d");
105
+ return (<view className={"g9a-history-tab" + (props.on ? " g9a-history-tab--on" : "")} accessibility-element={true} accessibility-label={props.label} bindtap={props.onTap} style={{ ...rowOf(ui, "6px"), minHeight: "34px", paddingLeft: "10px", paddingRight: "10px", borderRadius: tok(ui, "radius-s", "6px"), borderWidth: "1px",
106
+ borderColor: tok(ui, "line", "#e4ded6"), backgroundColor: props.on ? tok(ui, "accent", "#8a4b2a") : tok(ui, "surface", "#fff") }}>
107
+ <text style={{ color: ink }} text-maxline="1">{props.label}</text>
108
+ <text className="g9a-history-count" style={{ color: ink, fontSize: "12px" }} text-maxline="1">{formatNumber(props.count, ui.texts.locale)}</text>
109
+ </view>);
110
+ }
111
+ /** One conversation: its title opens it; pin (or unpin) and delete keep their size. Replaceable as `HistoryRow`. */
112
+ export const HistoryRow = swappable("HistoryRow", (props) => {
113
+ const ui = useUi();
114
+ const t = ui.texts.t;
115
+ const r = props.row;
116
+ return (<view className="g9a-history-row" style={{ ...rowOf(ui, "6px"), minHeight: "40px", marginBottom: "4px" }}>
117
+ <view style={grow} accessibility-element={true} accessibility-label={r.title} bindtap={props.onOpen}>
118
+ <text style={{ color: tok(ui, "ink", "#22201d") }} text-maxline="2">{r.title}</text>
119
+ {r.waiting ? <text style={{ fontSize: "11px", color: tok(ui, "warn", "#a35a00") }} text-maxline="1">{t("history.waiting")}</text> : null}
120
+ </view>
121
+ <Button label={t(r.pinned ? "history.unpin" : "history.pin")} onTap={props.onPin}/>
122
+ <Button label={t("history.delete")} onTap={props.onDelete}/>
123
+ </view>);
124
+ });
125
+ /** The history: four tabs with counts over one search, pin and unpin, delete after a confirm, open. */
126
+ function HistoryBody(props) {
127
+ const ui = useUi();
128
+ const t = ui.texts.t;
129
+ const api = ui.assistant.api;
130
+ const [rows, setRows] = useState(null);
131
+ const [failed, setFailed] = useState(false);
132
+ const [search, setSearch] = useState("");
133
+ const [tab, setTab] = useState("today");
134
+ const [doomed, setDoomed] = useState(null);
135
+ const load = () => api.get("conversations").then((r) => { setRows(readConversations(r)); setFailed(false); }, () => { setRows((x) => x ?? []); setFailed(true); });
136
+ useEffect(() => { void load(); }, []);
137
+ // a change, then the list again; a change that failed says so after the reload
138
+ const change = (call) => { void call.then(load, () => load().then(() => setFailed(true))); };
139
+ const tabs = historyTabs(rows ?? [], new Date(timer(ui.assistant.host).now()), search);
140
+ const counts = tabCounts(tabs);
141
+ const shown = tabs[tab];
142
+ const open = async (id) => { await ui.assistant.open(id); props.onOpen?.(id); };
143
+ return (<Frame failed={failed}>
144
+ <input style={{ ...field(ui), marginBottom: "8px" }} placeholder={t("history.search")} accessibility-label={t("history.search")} bindinput={(e) => setSearch(e.detail.value)}/>
145
+ <view className="g9a-history-tabs" style={{ ...rowOf(ui, "6px"), flexWrap: "wrap", marginBottom: "8px" }}>
146
+ {HISTORY_TABS.map((k) => <Tab key={k} label={t("history." + k)} count={counts[k]} on={tab === k} onTap={() => setTab(k)}/>)}
147
+ </view>
148
+ {rows !== null && shown.length === 0 ? <Empty /> : shown.map((c) => (<HistoryRow key={c.id} row={c} onOpen={() => void open(c.id)} onPin={() => change(pageCalls.pin(api, c.id, !c.pinned))} onDelete={() => setDoomed(c)}/>))}
149
+ <Dialog open={doomed !== null} label={t("history.delete_confirm")} onClose={() => setDoomed(null)}>
150
+ <text style={{ marginBottom: "8px" }} text-maxline="3">{doomed?.title ?? ""}</text>
151
+ <view style={rowOf(ui, "8px")}>
152
+ <Button primary label={t("history.delete")} onTap={() => { const c = doomed; setDoomed(null); if (c)
153
+ change(pageCalls.remove(api, c.id)); }}/>
154
+ <Button label={t("no")} onTap={() => setDoomed(null)}/>
155
+ </view>
156
+ </Dialog>
157
+ </Frame>);
158
+ }
159
+ /** How long the picker waits after a key before it asks the server. */
160
+ const PICK_WAIT_MS = 250;
161
+ /** A searchable picker over the host's things of the slot's kind (asked after a short pause). Replaceable as `SlotPicker`. */
162
+ export const SlotPicker = swappable("SlotPicker", (props) => {
163
+ const ui = useUi();
164
+ const t = ui.texts.t;
165
+ const clock = timer(ui.assistant.host);
166
+ const [items, setItems] = useState(null);
167
+ const [failed, setFailed] = useState(false);
168
+ const wait = useRef(null);
169
+ const asked = useRef(0);
170
+ const find = (q) => {
171
+ const n = ++asked.current;
172
+ pageCalls.pick(ui.assistant.api, props.slot.kind, q).then((r) => { if (n === asked.current) {
173
+ setItems(readPicks(r));
174
+ setFailed(false);
175
+ } }, () => { if (n === asked.current) {
176
+ setItems([]);
177
+ setFailed(true);
178
+ } });
179
+ };
180
+ useEffect(() => {
181
+ find("");
182
+ return () => { if (wait.current !== null)
183
+ clock.clear(wait.current); asked.current++; };
184
+ }, [props.slot.name]);
185
+ const typed = (q) => {
186
+ if (wait.current !== null)
187
+ clock.clear(wait.current);
188
+ wait.current = clock.set(() => { wait.current = null; find(q); }, PICK_WAIT_MS);
189
+ };
190
+ return (<Dialog open={true} label={props.slot.name} onClose={props.onClose}>
191
+ <view className="g9a-slot-picker">
192
+ <input style={{ ...field(ui), marginBottom: "8px" }} placeholder={t("history.search")} accessibility-label={t("history.search")} bindinput={(e) => typed(e.detail.value)}/>
193
+ {failed ? <text style={{ color: tok(ui, "danger", "#b42318") }} text-maxline="2">{t("error.network")}</text> : null}
194
+ {items !== null && items.length === 0 && !failed ? <Empty /> : (items ?? []).map((p) => <Button key={p.id} label={p.label} onTap={() => props.onPick(p)}/>)}
195
+ </view>
196
+ </Dialog>);
197
+ });
198
+ /** One routine's form: its slots, the preview, then a report or a card confirmed with the person's code. */
199
+ function RoutineForm(props) {
200
+ const ui = useUi();
201
+ const t = ui.texts.t;
202
+ const api = ui.assistant.api;
203
+ const snap = useSnapshot(ui.assistant);
204
+ const r = props.routine;
205
+ const [typed, setTyped] = useState(new Map());
206
+ const [picked, setPicked] = useState(new Map());
207
+ const [picking, setPicking] = useState(null);
208
+ const [tried, setTried] = useState(false);
209
+ const [told, setTold] = useState([]); // the slots the server says are still missing
210
+ const [busy, setBusy] = useState(false);
211
+ const [failed, setFailed] = useState(false);
212
+ const [report, setReport] = useState(null);
213
+ const [pending, setPending] = useState(null);
214
+ const code = useRef(""); // read from the field, never kept in state
215
+ const [epoch, setEpoch] = useState(0); // a new key clears the code field after a try
216
+ const [result, setResult] = useState(null);
217
+ const values = new Map();
218
+ const wrong = new Set();
219
+ for (const s of r.slots) {
220
+ const v = s.field === "pick" ? (picked.get(s.name)?.id ?? null) : slotValue(s, typed.get(s.name) ?? "");
221
+ if (v !== null)
222
+ values.set(s.name, v);
223
+ else if (s.field !== "pick" && (typed.get(s.name) ?? "").trim().length > 0)
224
+ wrong.add(s.name);
225
+ }
226
+ const missing = new Set([...missingSlots(r.slots, Object.fromEntries(values)).map((s) => s.name), ...told.filter((n) => !values.has(n))]);
227
+ const preview = async () => {
228
+ setTried(true);
229
+ if (busy || wrong.size > 0 || missing.size > 0)
230
+ return;
231
+ setBusy(true);
232
+ setFailed(false);
233
+ setResult(null);
234
+ try {
235
+ const p = obj(await pageCalls.preview(api, r.id, Object.fromEntries(values), snap.conversationId ?? undefined));
236
+ setTold(arr(p["missing"]).map((x) => str(x)).filter((x) => x.length > 0));
237
+ setReport(str(p["state"]) === "report" ? arr(p["blocks"]) : null);
238
+ const card = p["card"];
239
+ if (str(p["state"]) !== "report" && card !== undefined && card !== null) {
240
+ const plan = planView(card);
241
+ setPending({ routineRunId: str(p["routineRunId"]), hash: str(p["hash"], plan.hash), plan });
242
+ }
243
+ else
244
+ setPending(null);
245
+ }
246
+ catch {
247
+ setFailed(true);
248
+ }
249
+ finally {
250
+ setBusy(false);
251
+ }
252
+ };
253
+ const run = async () => {
254
+ if (!pending || busy || pending.plan.answered)
255
+ return;
256
+ const plan = pending.plan;
257
+ const withCode = needsCode(plan.method);
258
+ const typedCode = code.current;
259
+ if (withCode && typedCode.trim().length === 0)
260
+ return;
261
+ setBusy(true);
262
+ try {
263
+ const body = await pageCalls.run(api, r.id, pending.routineRunId, pending.hash, withCode ? typedCode : undefined);
264
+ const next = afterConfirm(plan, true, body);
265
+ setPending({ ...pending, plan: next });
266
+ if (next.answered === "confirmed")
267
+ setResult(str(obj(body)["text"], t("routine.done")));
268
+ }
269
+ catch (e) {
270
+ setPending({ ...pending, plan: afterConfirm(plan, false, e instanceof ApiError ? e.body : null) });
271
+ }
272
+ finally {
273
+ setBusy(false);
274
+ code.current = "";
275
+ setEpoch((n) => n + 1);
276
+ }
277
+ };
278
+ const edit = (name, text) => { setTyped((m) => new Map(m).set(name, text)); setPending(null); setReport(null); };
279
+ const danger = tok(ui, "danger", "#b42318");
280
+ const p = pending?.plan;
281
+ return (<view className="g9a-routine-form">
282
+ <view style={rowOf(ui, "8px")}>
283
+ <view style={grow}><Title text={r.title}/></view>
284
+ <Button label={t("routine.back")} onTap={props.onBack}/>
285
+ </view>
286
+ {r.slots.map((s) => {
287
+ const flag = wrong.has(s.name) ? "routine.invalid" : tried && missing.has(s.name) ? "routine.missing" : null;
288
+ return (<view key={s.name} className="g9a-routine-slot" style={{ marginBottom: "8px" }}>
289
+ <text style={{ fontSize: "13px", color: tok(ui, "muted", "#6b6660") }} text-maxline="1">{s.name}</text>
290
+ {s.field === "pick" ? (<view style={rowOf(ui, "8px")}>
291
+ <view style={grow}><text text-maxline="1">{picked.get(s.name)?.label ?? "—"}</text></view>
292
+ <Button label={t("routine.choose")} onTap={() => setPicking(s)}/>
293
+ </view>) : (<input style={{ ...field(ui) }} type="text" placeholder={s.name} accessibility-label={s.name} bindinput={(e) => edit(s.name, e.detail.value)}/>)}
294
+ {flag ? <text className="g9a-routine-flag" style={{ fontSize: "12px", color: danger }} text-maxline="1">{t(flag)}</text> : null}
295
+ </view>);
296
+ })}
297
+ <Button primary label={t("routine.preview")} onTap={() => void preview()}/>
298
+ {failed ? <text style={{ color: danger }} text-maxline="2">{t("error.network")}</text> : null}
299
+ {report ? <view className="g9a-routine-report" style={{ marginTop: "8px" }}>{report.map((b, i) => <BlockView key={i} block={b}/>)}</view> : null}
300
+ {p ? (<view className={cls(ui, "card.approval")} style={{ marginTop: "8px", padding: "12px", borderRadius: "10px", borderWidth: "1px", borderColor: tok(ui, "approval-card-border", "#8a4b2a") }}>
301
+ <text style={{ fontWeight: "bold" }} text-maxline="2">{p.readOnly ? t("card.readonly_routine") : p.title}</text>
302
+ {p.warning ? <text style={{ color: tok(ui, "warn", "#a35a00") }} text-maxline="2">{t("card.tainted")}</text> : null}
303
+ {p.steps.map((s) => <text key={s.index} className={cls(ui, "card.approval.step")} text-maxline="2">{String(s.index) + ". " + s.text + (s.undoable ? "" : " (" + t("card.irreversible") + ")")}</text>)}
304
+ {p.answered === null ? (<view>
305
+ {needsCode(p.method) ? <view className={cls(ui, "card.approval.code")}><PinPad key={epoch} label={t("card.code")} onInput={(v) => { code.current = v; }}/></view> : null}
306
+ {p.failCode === "confirm.waiting" ? <text>{t("card.waiting")}</text> : p.failCode ? <text text-maxline="2">{p.failCode + (p.triesLeft !== null ? " · " + t("card.tries_left", { count: p.triesLeft }) : "")}</text> : null}
307
+ <view style={rowOf(ui, "8px")}>
308
+ <Button part="card.approval.confirm" primary label={t("card.confirm")} onTap={() => void run()}/>
309
+ <Button part="card.approval.refuse" label={t("card.refuse")} onTap={() => setPending(null)}/>
310
+ </view>
311
+ </view>) : null}
312
+ </view>) : null}
313
+ {result !== null ? <text className="g9a-routine-result" style={{ marginTop: "8px" }} text-maxline="6">{result}</text> : null}
314
+ {picking ? (<SlotPicker slot={picking} onClose={() => setPicking(null)} onPick={(x) => { const name = picking.name; setPicked((m) => new Map(m).set(name, x)); setPicking(null); setPending(null); setReport(null); }}/>) : null}
315
+ </view>);
316
+ }
317
+ /** The routines the person may run; choosing one opens its form. */
318
+ function RoutineBody() {
319
+ const ui = useUi();
320
+ const [list, setList] = useState(null);
321
+ const [failed, setFailed] = useState(false);
322
+ const [chosen, setChosen] = useState(null);
323
+ useEffect(() => { pageCalls.routines(ui.assistant.api).then((r) => { setList(readRoutines(r)); setFailed(false); }, () => { setList([]); setFailed(true); }); }, []);
324
+ return (<Frame failed={failed}>
325
+ {chosen ? <RoutineForm key={chosen.id} routine={chosen} onBack={() => setChosen(null)}/>
326
+ : list === null ? null : list.length === 0 ? <Empty /> : list.map((r) => <Button key={r.id} label={r.title} onTap={() => setChosen(r)}/>)}
327
+ </Frame>);
328
+ }
329
+ const pageOf = (name, kind) => swappable(name, (props) => <Page {...props} kind={kind}/>);
330
+ export const History = pageOf("History", "history");
331
+ export const Abilities = pageOf("Abilities", "abilities");
332
+ export const KnowledgePage = pageOf("KnowledgePage", "knowledge");
333
+ export const LearnedPage = pageOf("LearnedPage", "learned");
334
+ export const FindingsPage = pageOf("FindingsPage", "findings");
335
+ export const RoutineWizard = pageOf("RoutineWizard", "routines");
336
+ export const ActionsPage = pageOf("ActionsPage", "actions");
package/dist/parts.d.ts CHANGED
@@ -4,13 +4,7 @@
4
4
  * every interactive element has an accessibility label; the growing message is drawn below the recycled list.
5
5
  */
6
6
  import type { AssistantState, MessageView, PlanView, Provenance, RunView } from "@g9tm/aiassistant";
7
- import { cls } from "./context.jsx";
8
- export declare function Button(props: {
9
- label: string;
10
- onTap: () => void;
11
- primary?: boolean;
12
- part?: Parameters<typeof cls>[1];
13
- }): import("@lynx-js/react").JSX.Element;
7
+ import type { Part } from "./context.jsx";
14
8
  export declare function TextView(props: {
15
9
  text: string;
16
10
  }): import("@lynx-js/react").JSX.Element;
@@ -23,6 +17,16 @@ export declare function Small(props: {
23
17
  provenance?: Provenance | null;
24
18
  state?: AssistantState | null;
25
19
  }): import("@lynx-js/react").JSX.Element | null;
20
+ export interface CsvButtonProps {
21
+ title?: string | undefined;
22
+ labels: string[];
23
+ rows: string[][];
24
+ }
25
+ /**
26
+ * "Save as CSV" for a table or an export block, through the host's saveFile; a small notice says saved or not saved.
27
+ * Hidden when the host cannot save files. Replaceable as `CsvButton`.
28
+ */
29
+ export declare const CsvButton: Part<CsvButtonProps>;
26
30
  export declare function BlockView(props: {
27
31
  block: unknown;
28
32
  compact?: boolean;
@@ -35,6 +39,7 @@ export declare function Message(props: {
35
39
  plans: ReadonlyMap<string, PlanView>;
36
40
  runId: string | null;
37
41
  }): import("@lynx-js/react").JSX.Element;
42
+ /** The other cards: undo all (its steps, then what the undo said), a question (options, a field or a secret field), "learn this?" and "make it a routine?". */
38
43
  export declare function Cards(props: {
39
44
  card: {
40
45
  kind: string;
@@ -42,7 +47,14 @@ export declare function Cards(props: {
42
47
  body: Record<string, unknown>;
43
48
  };
44
49
  runId: string | null;
45
- }): import("@lynx-js/react").JSX.Element;
50
+ }): import("@lynx-js/react").JSX.Element | null;
51
+ /** The thinking orb: only transform and opacity change (a slow pulse); still with reduced motion. */
52
+ export declare const ThinkingOrb: Part<Record<string, never>>;
53
+ /** Named stages lit by the run's real stage events (a pipeline's roles too, by the names given); never a show of thinking. */
54
+ export declare const StagesThinking: Part<{
55
+ run: RunView;
56
+ names?: Record<string, string>;
57
+ }>;
46
58
  export declare function WorkCard(props: {
47
59
  run: RunView;
48
60
  }): import("@lynx-js/react").JSX.Element | null;