Public: anyone can read this; the crew can change it.
Talk: the model is a button beside Send, with a list you can type in, and plain names #17794
Merged 15h 27m ago, live in production
talk-model-sheet → main 0 commits
10 files
changed +401
−71
docs/design/areas/talk.md +5 −1
| @@ -97,7 +97,11 @@ The window is the thread's one scroller; the list and a side pane are sticky col | ||
| 97 | 97 | - `.talk-hint` — "Enter sends", only where there is a mouse. |
| 98 | 98 | - `.talk-dock` — below 56.25rem the conversation's controls in one 44 px row above the composer, inside `.talk-base` (the sticky wrapper that rides `--kb`): Chats, New, Chat/Preview when a preview is live, and the menu (#16586). `.talk-head` is the title alone there; from 56.25rem the dock is hidden. |
| 99 | 99 | - `.talk-foot` — the line under the box: the status while it says something, else the crew line. |
| 100 | - `.talk-model` — the model picker's line over the box, at every width and in the build composer: the word Model, a select of the forge's own and each working connection's models, and Use for a page with no script. Absent when no connection offers a model. | |
| 100 | - `.talk-model-open` — the button beside Send that names the model in use and opens the list, at every width and in the build composer; bordered, with a chevron, so it reads as a control. Absent when no connection offers a model. With it, the words have their own row over the tools. | |
| 101 | - `.talk-model` — the same choice with the script off: the word Model, the select and Use. | |
| 102 | - `.talk-models` — the list as a `.dialog`: over the button from 720 px, a sheet from the bottom edge below. Opened by a key (`data-still`), or from 720 px, it has no motion. The filter takes the focus with a mouse; with a finger the list does, so the keyboard stays down. | |
| 103 | - `.talk-models-list`, `.talk-models-none` — its rows, and the line that says none matched or why a choice was refused. | |
| 104 | - `.talk-m` — one row: the plain name, whose account and who pays (prices when the listing has them), the id; `data-at` is the row the keys are on, `aria-selected` the model in use. | |
| 101 | 105 | - `.talk-fold` — one run of steps (the calls and thoughts between words) folded into one closed disclosure, one tab stop: one step by its words, more by their count. |
| 102 | 106 | - `.talk-fold-list` — the steps inside it, on a hairline at the start edge. |
| 103 | 107 | - `.talk-live` — the block being written; its running line shimmers (plain under reduced motion). |
docs/features/talk.md +8 −6
| @@ -131,19 +131,21 @@ Prior art read: Vercel AI Elements (Apache-2.0 React on shadcn; anatomy and beha | ||
| 131 | 131 | |
| 132 | 132 | ## The model picker |
| 133 | 133 | |
| 134 | When a connection on Connect your AI offers models (docs/features/connections.md), a | |
| 135 | line over the box, on a phone as on a desktop, says Model: the forge's model, then each model a | |
| 136 | working connection offers, by connection. The choice | |
| 137 | is the conversation's own and is kept with it; the line under each reply names the model it ran on | |
| 134 | When a connection on Connect your AI offers models (docs/features/connections.md), the | |
| 135 | composer has a button beside Send that names the model in use. It opens a list: the forge's model | |
| 136 | first, then each model a working connection offers, with a plain name, whose account it is and who | |
| 137 | pays, its price when the listing has one, the connection's effort, and the id. Type to find one; an | |
| 138 | alias ("-latest" beside its version) and the models Talk does not offer are under More models, the | |
| 139 | latter with the reason. The choice is the conversation's own and is kept with it; the line under each reply names the model it ran on | |
| 138 | 140 | (and its cost when the price table knows the model, never $0). It is a plain form, so it works with |
| 139 | the script off; with the script it is sent as soon as it changes. In the terminal, `m` in an open | |
| 141 | the script off (a select and Use); with the script the list closes once the forge has kept the choice. In the terminal, `m` in an open | |
| 140 | 142 | conversation is the same picker. |
| 141 | 143 | |
| 142 | 144 | **Remembered.** A new conversation starts on the model you chose last, wherever you chose it, while it |
| 143 | 145 | is still offered to you; if it is not, it starts on the forge's model and says so. Choosing in one |
| 144 | 146 | conversation never changes another. |
| 145 | 147 | |
| 146 | **In the build composer** (`?build=1`) the same line is part of the build's form, so the first turn | |
| 148 | **In the build composer** (`?build=1`) the same button is there and the choice is part of the build's form, so the first turn | |
| 147 | 149 | runs on it. `POST /api/v1/builds` takes it as `model`: the connection's id, a space and the model; |
| 148 | 150 | empty is the forge's own, and left out it is your last choice. In the terminal, `m` on Build an app. |
| 149 | 151 |
src/core/model_choice.ts +28 −9
| @@ -38,6 +38,8 @@ export const notForTalk = (model: string): string | undefined => | ||
| 38 | 38 | export interface Offer { |
| 39 | 39 | readonly connection: Connection; |
| 40 | 40 | readonly models: readonly string[]; |
| 41 | /** The ones listed that Talk does not offer (`notForTalk`), to show with the reason, never to choose. */ | |
| 42 | readonly held: readonly string[]; | |
| 41 | 43 | } |
| 42 | 44 | |
| 43 | 45 | /** A conversation's choice: a connection and one of its models. */ |
| @@ -56,6 +58,24 @@ export const choiceLabel = ( | ||
| 56 | 58 | model: string, |
| 57 | 59 | ): string => `${model} · ${connection.name}`; |
| 58 | 60 | |
| 61 | /** | |
| 62 | * A model's id as a plain name: without its maker's path, and without a first word that is its | |
| 63 | * connection's own name, which stands beside it ("lab/one-mini-1.4" on the connection "one" is | |
| 64 | * "Mini 1.4"). Only how it reads: the id is shown too wherever there is room. | |
| 65 | */ | |
| 66 | export function plainName(model: string, connection: string): string { | |
| 67 | const id = model.slice(model.lastIndexOf("/") + 1); | |
| 68 | const own = id.toLowerCase().startsWith(connection.toLowerCase()) && /^[-_:]+[^-_:]/.test(id.slice(connection.length)); | |
| 69 | const words = (own ? id.slice(connection.length) : id).split(/[-_:]+/).filter((w) => w !== ""); | |
| 70 | return words.map((w) => w[0]!.toUpperCase() + w.slice(1)).join(" ") || model; | |
| 71 | } | |
| 72 | ||
| 73 | /** A "-latest" id listed beside a version of the same model: the same thing twice, so it is second. */ | |
| 74 | export function isAlias(model: string, beside: readonly string[]): boolean { | |
| 75 | const base = model.replace(/[-:]latest$/, ""); | |
| 76 | return base !== model && beside.some((m) => m !== model && (m.startsWith(`${base}-`) || m.startsWith(`${base}:`))); | |
| 77 | } | |
| 78 | ||
| 59 | 79 | /** What the picker calls the forge's own, the choice of every conversation that made none. */ |
| 60 | 80 | export const FORGE_MODEL = "The forge's model"; |
| 61 | 81 | |
| @@ -86,15 +106,14 @@ export function offers( | ||
| 86 | 106 | ): Offer[] { |
| 87 | 107 | return listConnections(db, user.id) |
| 88 | 108 | .filter((c) => c.working === true && mayUse(db, user, c)) |
| 89 | .map((c) => ({ | |
| 90 | connection: c, | |
| 91 | models: (c.chosen.length > 0 | |
| 92 | ? c.chosen | |
| 93 | : c.models.map((m) => m.id) | |
| 94 | ) | |
| 95 | .filter((m) => notForTalk(m) === undefined) | |
| 96 | .slice(0, OFFERED_MAX), | |
| 97 | })) | |
| 109 | .map((c) => { | |
| 110 | const listed = c.chosen.length > 0 ? c.chosen : c.models.map((m) => m.id); | |
| 111 | return { | |
| 112 | connection: c, | |
| 113 | models: listed.filter((m) => notForTalk(m) === undefined).slice(0, OFFERED_MAX), | |
| 114 | held: listed.filter((m) => notForTalk(m) !== undefined).slice(0, OFFERED_MAX), | |
| 115 | }; | |
| 116 | }) | |
| 98 | 117 | .filter((o) => o.models.length > 0); |
| 99 | 118 | } |
| 100 | 119 |
src/web/pages/talk.ts +10 −7
| @@ -89,7 +89,7 @@ import { chatBuildOf } from "../../core/chat_build.ts"; | ||
| 89 | 89 | import { ownAppOf, receiptIssues, runningStep, stepOf, repoOf, steerOf, type Step } from "../../core/talk_steps.ts"; |
| 90 | 90 | import { paneCss, VIEWS, talkPane, type View } from "./talk_preview.ts"; |
| 91 | 91 | import { TALK_KEYS, talkCss, talkJs } from "./talk_client.ts"; |
| 92 | import { modelForm, modelPicker } from "../talk_model.ts"; | |
| 92 | import { modelCss, modelJs, modelPicker } from "../talk_model.ts"; | |
| 93 | 93 | import { liveRegionsJs } from "../client.ts"; |
| 94 | 94 | |
| 95 | 95 | /** A stream lasts this long at most; the client reconnects from its last turn id. */ |
| @@ -690,7 +690,9 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string | | ||
| 690 | 690 | const crewRepo = paneRow?.name; |
| 691 | 691 | const crew = crewRepo === undefined ? [] : crewOn(liveCrewRows(ctx, user), crewRepo); |
| 692 | 692 | // The model picker (`talk_model.ts`), only where a connection offers a model. |
| 693 | const picker = modelPicker(ctx, user, conversation.id, { builds: buildMode, empty }); | |
| 693 | const picker = modelPicker(ctx, user, urlOf(conversation), conversation.id, { builds: buildMode, empty }); | |
| 694 | // With a model to choose, the words have a row of their own over the tools; without, they share one. | |
| 695 | const input = html`<textarea class="talk-input" name="${buildMode ? "prompt" : "text"}" rows="1" maxlength="${WORDS_MAX}" required placeholder="${buildMode ? (chosen === undefined ? "A tip calculator for friends" : `What to make from ${chosen}`) : "Message the forge"}" aria-label="${buildMode ? "What to build" : "Talk to the forge"}" aria-keyshortcuts="/ Enter Shift+Enter" title="Enter sends, Shift+Enter adds a line" aria-describedby="talk-error">${editing === undefined ? "" : editing.text}</textarea>`; | |
| 694 | 696 | const tabs = split ? html`<nav class="seg talk-tabs" aria-label="Chat or preview"><a href="?pane=chat${paneQ === "" ? "" : `&${paneQ}`}"${shown === "chat" ? raw(' aria-current="page"') : null}>Chat</a><a href="?pane=preview${paneQ === "" ? "" : `&${paneQ}`}"${shown !== "chat" ? raw(' aria-current="page"') : null}>Preview</a></nav>` : null; |
| 695 | 697 | const body = html`<div class="talk-page" data-shell${!split ? null : html` data-frame-origins="${frames.join(" ")}"`} data-pane="${shown}"${listing ? raw(" data-view=\"list\"") : null}${split ? raw(" data-split") : null}><h1 class="sr-only">Talk</h1> |
| 696 | 698 | <div class="talk-side">${chats(ctx, conversation, showArchived, typed)}</div> |
| @@ -719,14 +721,15 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string | | ||
| 719 | 721 | conversation.archivedAt === null ? null : html`<p class="small muted" data-archived-note>Archived: sending here keeps it archived; Restore puts it back in the list.</p>`}${about}${editing === undefined && about !== null ? html`<input type="hidden" name="about" value="${ctx.url.searchParams.get("about")}" />` : null}${editing === undefined && !buildMode ? html`<input type="hidden" name="key" value="${last === "" ? "start" : last}" />` : null} |
| 720 | 722 | ${chosen === undefined ? null : html`<input type="hidden" name="template" value="${chosen}" />`} |
| 721 | 723 | ${confirmsDock(pendingConfirms)} |
| 722 | <p class="sr-only" role="status" data-confirms-said></p>${picker} | |
| 724 | <p class="sr-only" role="status" data-confirms-said></p>${picker?.note} | |
| 723 | 725 | <div class="talk-box"> |
| 724 | 726 | <div class="talk-chips" data-chips role="group" aria-label="Attached files">${buildMode ? null : unsent.map((f) => html`<span class="badge" data-pending-file="${f.id}">${f.name}</span>`)}</div> |
| 725 | 727 | <p class="talk-to small" data-to-line hidden><span></span> <button type="button" class="btn btn-icon" data-variant="ghost" data-to-off aria-label="Talk to the forge instead" title="Talk to the forge instead">${icon("x")}</button></p> |
| 726 | <div class="talk-tools"> | |
| 728 | ${picker?.control ? input : null}<div class="talk-tools"> | |
| 727 | 729 | ${buildMode ? null : html`<button type="button" class="btn btn-icon" data-variant="ghost" data-attach hidden aria-label="Attach files" title="Attach files">${icon("paperclip")}</button><input type="file" multiple hidden data-files />`} |
| 728 | <textarea class="talk-input" name="${buildMode ? "prompt" : "text"}" rows="1" maxlength="${WORDS_MAX}" required placeholder="${buildMode ? (chosen === undefined ? "A tip calculator for friends" : `What to make from ${chosen}`) : "Message the forge"}" aria-label="${buildMode ? "What to build" : "Talk to the forge"}" aria-keyshortcuts="/ Enter Shift+Enter" title="Enter sends, Shift+Enter adds a line" aria-describedby="talk-error">${editing === undefined ? "" : editing.text}</textarea> | |
| 730 | ${picker?.control ? null : input} | |
| 729 | 731 | ${editing === undefined ? null : html`<a class="btn" data-size="sm" href="${here}">Keep as it was</a>`} |
| 732 | ${picker?.control} | |
| 730 | 733 | <button type="button" class="btn talk-steer" data-size="sm" data-steer hidden title="Stop this answer and send now">Steer</button> |
| 731 | 734 | ${buildMode ? null : html`<button type="button" class="btn btn-icon talk-dictate" data-variant="ghost" data-dictate aria-pressed="false" aria-label="Dictate" title="Dictate" hidden>${icon("mic")}</button>`} |
| 732 | 735 | <button type="button" class="btn btn-icon talk-stop" data-stop hidden aria-label="Stop the answer" title="Stop the answer">${icon("square")}</button> |
| @@ -739,13 +742,13 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string | | ||
| 739 | 742 | <button type="button" class="btn talk-jump" data-jump hidden title="Jump to the latest message">${icon("pause")}${icon("arrowDown")}<span data-word></span><i class="talk-dot"></i></button> |
| 740 | 743 | </form> |
| 741 | 744 | </div> |
| 742 | ${picker === null || buildMode ? null : modelForm(urlOf(conversation))} | |
| 745 | ${picker?.sheet} | |
| 743 | 746 | <template id="talk-ico">${icon("copy")}${icon("check")}</template> |
| 744 | 747 | <template id="talk-queued">${queuedHtml({ id: "", text: "" })}</template> |
| 745 | 748 | </div> |
| 746 | 749 | ${split ? html`<div class="talk-work">${panel}${pane.html}</div>` : null} |
| 747 | 750 | </div>`; |
| 748 | return page({ ctx, title: conversation.title === "" ? "Talk" : `${conversation.title} · Talk`, body, styleCss: talkCss + paneCss + codePaneCss + (panel === null ? "" : buildCss) + voiceCss + pinnedPlanCss, scriptJs: `${talkJs}\n${liveRegionsJs}\n${ownTokenJs}`, description: "Talk to the forge.", wide: true, noDock: true, ...(!split ? {} : { frameSrc: frames }) }); | |
| 751 | return page({ ctx, title: conversation.title === "" ? "Talk" : `${conversation.title} · Talk`, body, styleCss: talkCss + paneCss + codePaneCss + (picker?.control ? modelCss : "") + (panel === null ? "" : buildCss) + voiceCss + pinnedPlanCss, scriptJs: `${talkJs}\n${liveRegionsJs}\n${ownTokenJs}${picker?.control ? modelJs : ""}`, description: "Talk to the forge.", wide: true, noDock: true, ...(!split ? {} : { frameSrc: frames }) }); | |
| 749 | 752 | } |
| 750 | 753 | |
| 751 | 754 | /** |
src/web/pages/talk_client.ts −4
| @@ -258,8 +258,6 @@ html:has(.talk-page) { scroll-padding-bottom: 8rem; } | ||
| 258 | 258 | .talk-steer { border-radius: 999px; } |
| 259 | 259 | .talk-dictate[aria-pressed="true"] { background: var(--accent); color: var(--bg); } |
| 260 | 260 | .talk-foot { margin: 6px 16px 0; } |
| 261 | .talk-model { margin: 0 0 8px; padding-inline: 16px 4px; display: flex; align-items: center; gap: 8px; } | |
| 262 | .talk-model select { flex: 0 1 20rem; min-width: 0; min-height: 2.75rem; font-size: 16px; text-overflow: ellipsis; } | |
| 263 | 261 | .talk-status { margin: 4px 16px 0; min-height: 1.25rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } |
| 264 | 262 | [data-answering] .talk-status { background: none; animation: none; color: transparent; } |
| 265 | 263 | .talk-error { margin: 6px 4px 0; color: var(--danger); } |
| @@ -450,8 +448,6 @@ if (root) { | ||
| 450 | 448 | if (head) head.addEventListener("focusin", () => head.removeAttribute("data-away")); |
| 451 | 449 | const jump = form.querySelector("[data-jump]"); |
| 452 | 450 | const err = form.querySelector("[data-error]"); |
| 453 | const pick = form.querySelector("[data-model-pick]"); | |
| 454 | if (pick) { root.querySelector("[data-model-use]").hidden = true; pick.onchange = () => pick.form.requestSubmit(); } | |
| 455 | 451 | box.required = false; |
| 456 | 452 | const fail = (words) => { say(""); err.textContent = words; err.hidden = false; box.setAttribute("aria-invalid", "true"); }; |
| 457 | 453 | // The keyboard covers the layout viewport on phones: lift the composer by what it hides. Only |
src/web/talk_model.ts +192 −25
| @@ -1,12 +1,13 @@ | ||
| 1 | 1 | /** |
| 2 | * Talk's model picker, the line over the composer's box at every width (`core/model_choice.ts`): the | |
| 3 | * word Model and a select of the forge's own and every model the person may use on a working | |
| 4 | * connection. In a conversation it is saved by a plain form post (`POST /talk/:id/model`), sent on | |
| 5 | * change by the script; in the build composer it is a field of the build's own form, so the first | |
| 6 | * turn runs on it. Absent when no connection offers a model, so a forge without connections looks as | |
| 7 | * before. | |
| 2 | * Talk's model picker, beside Send in the composer (`core/model_choice.ts`): one button that names | |
| 3 | * the model in use and opens a list, the forge's own first, then every model the person may use on a | |
| 4 | * working connection. In a conversation the choice is kept by a plain form post | |
| 5 | * (`POST /talk/:id/model`); in the build composer it is a field of the build's own form, so the first | |
| 6 | * turn runs on it. Without the script it is a select. Absent when no connection offers a model, so a | |
| 7 | * forge without connections looks as before. | |
| 8 | 8 | */ |
| 9 | import { choiceLabel, choiceOf, choiceValue, choiceWords, FORGE_MODEL, lostModelLine, notForTalk, offers, setChoice, startingChoice } from "../core/model_choice.ts"; | |
| 9 | import { connectionFor, type Connection } from "../core/connections.ts"; | |
| 10 | import { choiceLabel, choiceOf, choiceValue, choiceWords, FORGE_MODEL, isAlias, lostModelLine, notForTalk, offers, plainName, setChoice, startingChoice, type Offer } from "../core/model_choice.ts"; | |
| 10 | 11 | import { anyTalkConnection } from "../core/subscriptions.ts"; |
| 11 | 12 | import { getConversation } from "../core/conversations.ts"; |
| 12 | 13 | import type { User } from "../core/users.ts"; |
| @@ -14,13 +15,36 @@ import type { Ctx } from "../http/context.ts"; | ||
| 14 | 15 | import { notFoundPage, signInFirst } from "./chrome.ts"; |
| 15 | 16 | import { field, readForm } from "./form.ts"; |
| 16 | 17 | import { html, raw, type Html } from "./html.ts"; |
| 17 | import { flashTo } from "./layout.ts"; | |
| 18 | import { flashOrJson } from "./layout.ts"; | |
| 19 | import { icon } from "./ui.ts"; | |
| 20 | ||
| 21 | /** Who pays for a model's turns, and what is known of it: no purpose is written anywhere, so none is said. */ | |
| 22 | function metaOf(c: Connection, model: string): string { | |
| 23 | const price = c.models.find((x) => x.id === model); | |
| 24 | return [ | |
| 25 | c.name, | |
| 26 | c.scope === "yours" ? "your key" : "the forge's credit", | |
| 27 | ...(price?.inUsd === undefined || price.outUsd === undefined ? [] : [`$${String(price.inUsd)} in, $${String(price.outUsd)} out per million tokens`]), | |
| 28 | ...(c.effort === "" ? [] : [`effort ${c.effort}`]), | |
| 29 | ].join(" · "); | |
| 30 | } | |
| 31 | ||
| 32 | export interface Picker { | |
| 33 | /** In the composer's tools, beside Send: the button, and the select it stands for. */ | |
| 34 | readonly control: Html | null; | |
| 35 | /** Outside the composer's form: the list, and the form a choice is posted by. */ | |
| 36 | readonly sheet: Html | null; | |
| 37 | /** Over the box: the person's last model is no longer offered. */ | |
| 38 | readonly note: Html | null; | |
| 39 | } | |
| 18 | 40 | |
| 19 | 41 | /** |
| 20 | * The picker, its form outside the composer's (`form=`) unless it `builds`, or null with nothing to | |
| 21 | * offer. An empty conversation also says when the person's last model is no longer offered. | |
| 42 | * The picker, or null with nothing to offer. The select is the truth and all a page without the | |
| 43 | * script has; the script hides it and draws the list from its options (`data-name`, `data-meta`), | |
| 44 | * so a connection of a hundred models is sent once. An empty conversation also says when the | |
| 45 | * person's last model is no longer offered. | |
| 22 | 46 | */ |
| 23 | export function modelPicker(ctx: Ctx, user: User, conversationId: string, o: { readonly builds: boolean; readonly empty: boolean }): Html | null { | |
| 47 | export function modelPicker(ctx: Ctx, user: User, here: string, conversationId: string, o: { readonly builds: boolean; readonly empty: boolean }): Picker | null { | |
| 24 | 48 | // A forge with no connection Talk could run on draws no picker and reads nothing for it. |
| 25 | 49 | if (!anyTalkConnection(ctx.app.db)) return null; |
| 26 | 50 | const offered = offers(ctx.app.db, user); |
| @@ -29,23 +53,166 @@ export function modelPicker(ctx: Ctx, user: User, conversationId: string, o: { r | ||
| 29 | 53 | const lost = o.empty && now === undefined ? lostModelLine(ctx.app.db, user) : undefined; |
| 30 | 54 | const note = lost === undefined ? null : html`<p class="talk-foot small muted">${lost}</p>`; |
| 31 | 55 | // A conversation on a model that stopped answering keeps its picker: the way back to the forge's own. |
| 32 | if (offered.length === 0 && now === undefined) return note; | |
| 56 | if (offered.length === 0 && now === undefined) return { control: null, sheet: null, note }; | |
| 33 | 57 | const current = now === undefined ? "" : choiceValue(now); |
| 34 | 58 | const listed = offered.some((on) => on.connection.id === now?.connectionId && on.models.includes(now.model)); |
| 35 | // A choice whose connection stopped answering stays shown as the conversation's, never offered anew. | |
| 36 | return html`${note}<p class="talk-model small"> | |
| 37 | <label for="talk-model-pick">Model</label> | |
| 38 | <select class="input" id="talk-model-pick" name="model"${o.builds ? null : raw(' form="talk-model" data-model-pick')}> | |
| 39 | <option value=""${current === "" ? html` selected` : null}>${FORGE_MODEL}</option> | |
| 40 | ${now !== undefined && !listed ? html`<option value="${current}" selected>${choiceWords(ctx.app.db, user.id, now)} (${notForTalk(now.model) ?? "not answering"})</option>` : null} | |
| 41 | ${offered.map((on) => html`<optgroup label="${on.connection.name}">${on.models.map((m) => html`<option value="${choiceValue({ connectionId: on.connection.id, model: m })}"${choiceValue({ connectionId: on.connection.id, model: m }) === current ? html` selected` : null}>${choiceLabel(on.connection, m)}</option>`)}</optgroup>`)} | |
| 59 | const gone = now === undefined || listed ? undefined : (notForTalk(now.model) ?? "not answering"); | |
| 60 | const option = (on: Offer, model: string): Html => { | |
| 61 | const value = choiceValue({ connectionId: on.connection.id, model }); | |
| 62 | return html`<option value="${value}"${value === current ? html` selected` : null}${isAlias(model, on.models) ? raw(" data-more") : null} data-name="${plainName(model, on.connection.name)}" data-meta="${metaOf(on.connection, model)}">${choiceLabel(on.connection, model)}</option>`; | |
| 63 | }; | |
| 64 | const nowName = now === undefined ? "" : plainName(now.model, connectionFor(ctx.app.db, user.id, now.connectionId)?.name ?? ""); | |
| 65 | const name = now === undefined ? "Forge's model" : nowName; | |
| 66 | const control = html`<button type="button" class="btn js-only talk-model-open" data-size="sm" data-model-open aria-haspopup="dialog" title="Choose the model"><span class="sr-only">Model:</span><span class="truncate" data-model-name>${name}${gone === undefined ? null : html` (${gone})`}</span>${icon("chevronDown")}</button> | |
| 67 | <span class="talk-model small" data-nojs><label for="talk-model-pick">Model</label> | |
| 68 | <select class="input" id="talk-model-pick" name="model"${o.builds ? null : raw(' form="talk-model"')}> | |
| 69 | <option value=""${current === "" ? html` selected` : null} data-name="${FORGE_MODEL}" data-meta="The account granted to you, or the forge's own">${FORGE_MODEL}</option> | |
| 70 | ${gone === undefined || now === undefined ? null : html`<option value="${current}" selected data-name="${nowName}" data-meta="${gone}">${choiceWords(ctx.app.db, user.id, now)} (${gone})</option>`} | |
| 71 | ${offered.map((on) => html`<optgroup label="${on.connection.name}">${on.models.map((x) => option(on, x))}${on.held.map((x) => html`<option value="held ${x}" disabled data-more data-name="${plainName(x, on.connection.name)}" data-meta="Not for Talk: ${notForTalk(x)}">${x} (not for Talk)</option>`)}</optgroup>`)} | |
| 42 | 72 | </select> |
| 43 | ${o.builds ? null : html`<button type="submit" class="btn" data-size="sm" data-variant="ghost" form="talk-model" data-model-use>Use</button>`} | |
| 44 | </p>`; | |
| 73 | ${o.builds ? null : html`<button type="submit" class="btn" data-size="sm" data-variant="ghost" form="talk-model">Use</button>`}</span>`; | |
| 74 | const sheet = html`${o.builds ? null : modelForm(here)}<dialog class="dialog talk-models" id="talk-models" aria-labelledby="talk-models-title"> | |
| 75 | <div class="dialog-head"><h2 id="talk-models-title">Model</h2><button type="button" class="btn btn-icon" data-variant="ghost" data-models-close aria-label="Close" title="Close">${icon("x")}</button></div> | |
| 76 | <div class="dialog-body"><input class="input" type="search" role="combobox" aria-expanded="true" aria-controls="talk-models-list" aria-autocomplete="list" aria-label="Find a model" placeholder="Find a model" autocomplete="off" spellcheck="false" /></div> | |
| 77 | <div class="talk-models-list" id="talk-models-list" role="listbox" tabindex="0" autofocus aria-label="Models"></div> | |
| 78 | <p class="small muted talk-models-none" role="status" data-models-none></p> | |
| 79 | <div class="dialog-foot"><button type="button" class="btn" data-size="sm" data-variant="ghost" data-models-more hidden>More models</button><a class="btn" data-size="sm" data-variant="ghost" href="/settings/model">Connections and effort</a></div> | |
| 80 | </dialog>`; | |
| 81 | return { control, sheet, note }; | |
| 45 | 82 | } |
| 46 | 83 | |
| 84 | /** | |
| 85 | * The sheet's look, on a page that draws one. Below 720 px `.dialog` is a sheet from the bottom edge | |
| 86 | * already; from it up, a panel over the button. The script only says where the button is | |
| 87 | * (`--open-right`, `--open-top`) and what a raised keyboard covers (`--lift`, `--room`); which of them | |
| 88 | * counts is a width, and the sheet's to answer. A key or a wide screen has no motion. | |
| 89 | */ | |
| 90 | export const modelCss = /* css */ ` | |
| 91 | .talk-box > .talk-input { padding: 12px 16px 4px; } | |
| 92 | .talk-model-open { min-width: 6rem; max-width: 16rem; min-height: 2.75rem; gap: 4px; border-radius: 999px; } | |
| 93 | .talk-tools > .talk-model-open { margin-inline-start: auto; } | |
| 94 | /* In the site's own layer, where its rule that hides [data-nojs] under a script wins: the rest of this | |
| 95 | sheet is in no layer, and a display out there would draw the select beside the button. */ | |
| 96 | components { .talk-model { display: flex; align-items: center; gap: 8px; min-width: 0; } } | |
| 97 | .talk-model select { min-width: 0; min-height: 2.75rem; font-size: 16px; text-overflow: ellipsis; } | |
| 98 | .talk-models { max-height: min(80dvh, 32rem, calc(var(--room, 100dvh) - 16px)); } | |
| 99 | .talk-models[data-still] { transition: none; } | |
| 100 | (prefers-reduced-motion: reduce) { .talk-models { transition: none; } } | |
| 101 | (max-width: 719px) { .talk-models { margin-bottom: var(--lift, 0px); } } | |
| 102 | .talk-models .input { font-size: 16px; } | |
| 103 | .talk-models-list { min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: 0 8px; } | |
| 104 | .talk-models-none { margin: 0; padding: 0 16px; } | |
| 105 | .talk-m { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 0 8px; min-height: 2.75rem; padding: 8px; border-radius: var(--radius-sm); cursor: pointer; } | |
| 106 | .talk-m[hidden] { display: none; } | |
| 107 | .talk-m > span { grid-column: 1; overflow-wrap: anywhere; } | |
| 108 | .talk-m > .ico { grid-column: 2; grid-row: 1; } | |
| 109 | .talk-m:not([aria-selected="true"]) > .ico { visibility: hidden; } | |
| 110 | .talk-m[aria-selected="true"] > span:first-child { font-weight: 600; } | |
| 111 | .talk-m[data-at] { background: var(--muted); } | |
| 112 | .talk-m[aria-disabled="true"] { cursor: not-allowed; color: var(--muted-fg); } | |
| 113 | (min-width: 720px) { | |
| 114 | .talk-models { width: 26rem; margin: 0; inset: auto auto calc(100dvh - var(--open-top, 100dvh) + 8px) max(8px, calc(var(--open-right, 27rem) - 26rem)); max-height: min(32rem, calc(var(--open-top, 100dvh) - 16px)); transition: none; } | |
| 115 | .talk-models::backdrop { background: none; backdrop-filter: none; } | |
| 116 | } | |
| 117 | (forced-colors: active) { .talk-m[data-at] { outline: 2px solid CanvasText; outline-offset: -2px; } } | |
| 118 | `; | |
| 119 | ||
| 120 | /** | |
| 121 | * The button opens the list, drawn once from the select's options. Type to filter, arrows, Enter, | |
| 122 | * Esc; the overlay host returns the focus to the button. In a conversation the choice is posted and | |
| 123 | * the list stays open, over the composer, until the forge has answered, so no message can be sent | |
| 124 | * between the two; in the build composer it is the form's own field. On a touch screen the list takes | |
| 125 | * the focus, so the keyboard rises only when the filter is tapped. | |
| 126 | */ | |
| 127 | export const modelJs = ` | |
| 128 | (() => { | |
| 129 | const talk = document.querySelector("[data-talk]"), btn = talk && talk.querySelector("[data-model-open]"), sel = document.getElementById("talk-model-pick"), d = document.getElementById("talk-models"); | |
| 130 | if (!btn || !sel || !d) return; | |
| 131 | const find = d.querySelector("input"), list = d.querySelector("[role=listbox]"), none = d.querySelector("[data-models-none]"), more = d.querySelector("[data-models-more]"); | |
| 132 | const name = btn.querySelector("[data-model-name]"), vv = window.visualViewport, tick = document.querySelector("#talk-ico").content.querySelectorAll("svg")[1]; | |
| 133 | let all = false, at = null, shut = () => {}, busy = false; | |
| 134 | const rows = [...sel.options].map((o, i) => { | |
| 135 | const r = Object.assign(document.createElement("div"), { id: "talk-m-" + i, className: "talk-m" }); | |
| 136 | const id = o.value.slice(o.value.indexOf(" ") + 1); | |
| 137 | r.setAttribute("role", "option"); | |
| 138 | if (o.disabled) r.setAttribute("aria-disabled", "true"); | |
| 139 | [[o.dataset.name, ""], [o.dataset.meta, "small muted"], [id, "small muted mono"]].forEach(([words, cls]) => { if (words) r.append(Object.assign(document.createElement("span"), { textContent: words, className: cls })); }); | |
| 140 | r.append(tick.cloneNode(true)); | |
| 141 | r.words = (o.dataset.name + " " + o.dataset.meta + " " + id).toLowerCase(); | |
| 142 | r.option = o; | |
| 143 | r.onclick = () => pick(r); | |
| 144 | return r; | |
| 145 | }); | |
| 146 | list.append(...rows); | |
| 147 | const shown = () => rows.filter((r) => !r.hidden); | |
| 148 | const mark = (r) => { | |
| 149 | at = r || null; | |
| 150 | rows.forEach((x) => x.toggleAttribute("data-at", x === at)); | |
| 151 | [find, list].forEach((e) => { if (at) e.setAttribute("aria-activedescendant", at.id); else e.removeAttribute("aria-activedescendant"); }); | |
| 152 | if (at) at.scrollIntoView({ block: "nearest" }); | |
| 153 | }; | |
| 154 | const paint = () => { | |
| 155 | const typed = find.value.trim().toLowerCase().split(" ").filter(Boolean); | |
| 156 | rows.forEach((r) => { | |
| 157 | r.setAttribute("aria-selected", String(r.option.selected)); | |
| 158 | r.hidden = typed.length ? !typed.every((w) => r.words.includes(w)) : !all && !r.option.selected && "more" in r.option.dataset; | |
| 159 | }); | |
| 160 | more.hidden = all || typed.length > 0 || !rows.some((r) => "more" in r.option.dataset && !r.option.selected); | |
| 161 | none.textContent = shown().length ? "" : "No model has that in its name."; | |
| 162 | mark(typed.length ? shown()[0] : rows.find((r) => r.option.selected)); | |
| 163 | }; | |
| 164 | const fit = () => { | |
| 165 | const r = btn.getBoundingClientRect(), say = (k, px) => d.style.setProperty(k, px + "px"); | |
| 166 | say("--open-right", r.right); | |
| 167 | say("--open-top", r.top); | |
| 168 | if (vv) { say("--lift", Math.max(0, innerHeight - vv.height - vv.offsetTop)); say("--room", vv.height); } | |
| 169 | }; | |
| 170 | async function pick(r) { | |
| 171 | if (!r || busy || r.option.disabled) return; | |
| 172 | const was = sel.value, done = () => { name.textContent = sel.value ? r.option.dataset.name : "Forge's model"; shut(); }; | |
| 173 | if (r.option.selected) { shut(); return; } | |
| 174 | sel.value = r.option.value; | |
| 175 | if (sel.form.id !== "talk-model") { done(); return; } | |
| 176 | busy = true; | |
| 177 | list.setAttribute("aria-busy", "true"); | |
| 178 | try { | |
| 179 | const res = await fetch(sel.form.action, { method: "POST", headers: { accept: "application/json" }, body: new URLSearchParams({ model: sel.value }) }), said = await res.json(); | |
| 180 | if (!said.ok) throw new Error(said.error); | |
| 181 | talk.querySelector(".talk-status").textContent = said.flash; | |
| 182 | done(); | |
| 183 | } catch (e) { | |
| 184 | sel.value = was; | |
| 185 | paint(); | |
| 186 | none.textContent = e instanceof TypeError || e instanceof SyntaxError ? "Not changed: the forge did not answer." : e.message; | |
| 187 | } | |
| 188 | busy = false; | |
| 189 | list.removeAttribute("aria-busy"); | |
| 190 | } | |
| 191 | btn.onclick = (e) => { | |
| 192 | if (!window.forgeOverlay) return; | |
| 193 | all = false; | |
| 194 | find.value = ""; | |
| 195 | d.toggleAttribute("data-still", e.detail === 0); | |
| 196 | fit(); | |
| 197 | shut = window.forgeOverlay.open(d, { opener: btn, name: "model" }); | |
| 198 | paint(); | |
| 199 | if (matchMedia("(pointer: fine)").matches) find.focus(); | |
| 200 | }; | |
| 201 | find.oninput = paint; | |
| 202 | more.onclick = () => { all = true; paint(); list.focus(); }; | |
| 203 | d.querySelector("[data-models-close]").onclick = () => shut(); | |
| 204 | if (vv) vv.addEventListener("resize", () => { if (d.open) fit(); }); | |
| 205 | d.addEventListener("keydown", (e) => { | |
| 206 | if (e.target !== find && e.target !== list) return; | |
| 207 | const rs = shown(), i = rs.indexOf(at), to = { ArrowDown: i + 1, ArrowUp: i - 1 }[e.key]; | |
| 208 | if (to !== undefined && rs.length) { e.preventDefault(); mark(rs[(to + rs.length) % rs.length]); } | |
| 209 | else if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); pick(at); } | |
| 210 | }); | |
| 211 | })(); | |
| 212 | `; | |
| 213 | ||
| 47 | 214 | /** The picker's own form, outside the composer's (a form cannot hold another). */ |
| 48 | export const modelForm = (here: string): Html => html`<form id="talk-model" method="post" action="${here}/model" hidden></form>`; | |
| 215 | const modelForm = (here: string): Html => html`<form id="talk-model" method="post" action="${here}/model" hidden></form>`; | |
| 49 | 216 | |
| 50 | 217 | // POST /talk/:id/model — the conversation's model, from the picker. |
| 51 | 218 | export async function talkModel(ctx: Ctx): Promise<Response> { |
| @@ -59,8 +226,8 @@ export async function talkModel(ctx: Ctx): Promise<Response> { | ||
| 59 | 226 | const value = field(form, "model"); |
| 60 | 227 | const now = choiceOf(ctx.app.db, user.id, conversation.id); |
| 61 | 228 | // Sending the choice it already has changes nothing, even when that model has stopped answering. |
| 62 | if (now !== undefined && value === choiceValue(now)) return flashTo(ctx, back, { message: "Kept." }); | |
| 229 | if (now !== undefined && value === choiceValue(now)) return flashOrJson(ctx, back, { message: "Kept." }); | |
| 63 | 230 | const set = setChoice(ctx.app.db, user, conversation.id, value); |
| 64 | if (!set.ok) return flashTo(ctx, back, { tone: "danger", message: "That model is not offered: its connection is not working, or not yours to use." }); | |
| 65 | return flashTo(ctx, back, { tone: "success", message: `${choiceWords(ctx.app.db, user.id, set.value)} answers here.` }); | |
| 231 | if (!set.ok) return flashOrJson(ctx, back, { tone: "danger", message: "That model is not offered: its connection is not working, or not yours to use." }); | |
| 232 | return flashOrJson(ctx, back, { tone: "success", message: `${choiceWords(ctx.app.db, user.id, set.value)} answers here.` }); | |
| 66 | 233 | } |
test/helpers/talk-phone.ts +36 −14
| @@ -230,15 +230,23 @@ export function widthTests(width: (typeof WIDTHS)[number]): void { | ||
| 230 | 230 | await frame(); |
| 231 | 231 | const box = (e) => { const r = e.getBoundingClientRect(); return { top: r.top, bottom: r.bottom, left: r.left, right: r.right, w: r.width, h: r.height, cls: String(e.className || e.tagName), text: (e.getAttribute("aria-label") || e.textContent || "").trim().slice(0, 20) }; }; |
| 232 | 232 | const shown = (e) => e.getBoundingClientRect().width > 0; |
| 233 | const d = dock.getBoundingClientRect(); | |
| 233 | const bar = dock.getBoundingClientRect(); | |
| 234 | 234 | const kids = [...dock.querySelectorAll(":scope > *")].filter(shown).map(box); |
| 235 | 235 | const targets = [...dock.querySelectorAll(":scope > a, :scope > form button, :scope > .talk-tabs a, :scope > .menu > summary")].filter(shown).map(box); |
| 236 | 236 | const headKids = [...head.querySelectorAll(":scope > *")].filter(shown).map((e) => String(e.className || e.tagName)); |
| 237 | // The model is in sight with no tap: the word Model and its select, between the dock and the box. | |
| 238 | const line = document.querySelector(".talk-compose .talk-model"), sel = line.querySelector("select"); | |
| 239 | const model = { sel: box(sel), label: box(line.querySelector("label")), line: box(line), shown: shown(sel), boxTop: document.querySelector(".talk-box").getBoundingClientRect().top }; | |
| 237 | // The model in use is in sight beside Send; its list is a sheet from the bottom edge, and the | |
| 238 | // filter does not take the focus, so the keyboard stays down until it is tapped. | |
| 239 | const open = document.querySelector("[data-model-open]"), send = document.querySelector(".talk-send"), talkBox = document.querySelector(".talk-box"); | |
| 240 | const model = { btn: box(open), name: open.textContent.trim(), border: getComputedStyle(open).borderTopWidth, send: box(send), box: box(talkBox), select: shown(document.querySelector("#talk-model-pick")) }; | |
| 241 | open.click(); | |
| 242 | await frame(); | |
| 243 | const d = document.querySelector("#talk-models"); | |
| 244 | model.sheet = { open: d.open, ...box(d), rows: [...d.querySelectorAll("[role=option]")].filter(shown).map(box), filter: box(d.querySelector("input")), at: document.activeElement.id }; | |
| 245 | document.activeElement.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true })); | |
| 246 | await frame(); | |
| 247 | model.after = { open: d.open, focus: document.activeElement === open }; | |
| 240 | 248 | const ids = [...document.querySelectorAll("[id]")].map((e) => e.id), dup = ids.filter((x, i) => ids.indexOf(x) !== i); |
| 241 | return JSON.stringify({ dock: { top: d.top, bottom: d.bottom, h: d.height }, kids, targets, headKids, model, dup, vh: innerHeight, sw: document.documentElement.scrollWidth }); | |
| 249 | return JSON.stringify({ dock: { top: bar.top, bottom: bar.bottom, h: bar.height }, kids, targets, headKids, model, dup, vh: innerHeight, sw: document.documentElement.scrollWidth }); | |
| 242 | 250 | })()`, |
| 243 | 251 | ); |
| 244 | 252 | const seen = JSON.stringify(s); |
| @@ -262,15 +270,29 @@ export function widthTests(width: (typeof WIDTHS)[number]): void { | ||
| 262 | 270 | } |
| 263 | 271 | // The head keeps the title and nothing else. |
| 264 | 272 | expect(s.headKids, seen).toEqual(["talk-title"]); |
| 265 | // 44 px tall, wide enough for a model's name, on screen, one row above the box. | |
| 266 | expect(s.model.shown, seen).toBe(true); | |
| 267 | expect(s.model.label.text, seen).toBe("Model"); | |
| 268 | expect(s.model.label.w, seen).toBeGreaterThan(20); | |
| 269 | expect(s.model.sel.h, seen).toBeGreaterThanOrEqual(44); | |
| 270 | expect(s.model.sel.w, seen).toBeGreaterThanOrEqual(200); | |
| 271 | expect(s.model.sel.right, seen).toBeLessThanOrEqual(width); | |
| 272 | expect(s.model.line.top, seen).toBeGreaterThanOrEqual(s.dock.bottom - 1); | |
| 273 | expect(s.model.line.bottom, seen).toBeLessThanOrEqual(s.model.boxTop + 1); | |
| 273 | // A button with a border that reads the model, 44 px tall, inside the box on Send's row; the | |
| 274 | // select is the script-less page's. | |
| 275 | expect(s.model.name, seen).toContain("Forge's model"); | |
| 276 | expect(s.model.border, seen).not.toBe("0px"); | |
| 277 | expect(s.model.btn.h, seen).toBeGreaterThanOrEqual(44); | |
| 278 | // The select is gone before the button's width is judged: drawn, it takes half the row. | |
| 279 | expect(s.model.select, seen).toBe(false); | |
| 280 | expect(s.model.btn.w, seen).toBeGreaterThanOrEqual(110); | |
| 281 | expect(s.model.btn.right, seen).toBeLessThanOrEqual(s.model.box.right); | |
| 282 | expect(s.model.btn.top, seen).toBeGreaterThanOrEqual(s.model.box.top); | |
| 283 | expect(s.model.btn.bottom, seen).toBeLessThanOrEqual(s.model.box.bottom); | |
| 284 | // The sheet: on the bottom edge, its filter on top and not focused, rows of 44 px or more, and | |
| 285 | // Esc gives the focus back. | |
| 286 | expect(s.model.sheet.open, seen).toBe(true); | |
| 287 | expect(Math.abs(s.model.sheet.bottom - s.vh), seen).toBeLessThanOrEqual(2); | |
| 288 | expect(s.model.sheet.w, seen).toBeLessThanOrEqual(width); | |
| 289 | expect(s.model.sheet.at, seen).toBe("talk-models-list"); | |
| 290 | expect(s.model.sheet.rows.length, seen).toBe(3); | |
| 291 | for (const r of s.model.sheet.rows) { | |
| 292 | expect(r.h, seen).toBeGreaterThanOrEqual(44); | |
| 293 | expect(r.top, seen).toBeGreaterThanOrEqual(s.model.sheet.filter.bottom); | |
| 294 | } | |
| 295 | expect(s.model.after, seen).toEqual({ open: false, focus: true }); | |
| 274 | 296 | expect(s.dup, seen).toEqual([]); |
| 275 | 297 | }, |
| 276 | 298 | 30_000, |
test/talk-model-choice.test.ts +6 −2
| @@ -383,13 +383,15 @@ describe("the page's picker", () => { | ||
| 383 | 383 | await fetch(`${servers.url}/talk/${c}`, { headers: { cookie } }) |
| 384 | 384 | ).text(); |
| 385 | 385 | expect(page).toContain('id="talk-model-pick"'); |
| 386 | // It is the composer's own line, over its box, so it is in sight at every width. | |
| 386 | // It is the composer's own, beside Send, so it is in sight at every width. | |
| 387 | 387 | const from = page.indexOf('<header class="talk-head">'); |
| 388 | 388 | const head = page.slice(from, page.indexOf("</header>", from)); |
| 389 | 389 | expect(head).not.toContain("talk-model"); |
| 390 | 390 | const compose = page.slice(page.indexOf('class="talk-compose"')); |
| 391 | 391 | expect(compose).toContain('<label for="talk-model-pick">Model</label>'); |
| 392 | expect(compose).toMatch(/<select [^>]*id="talk-model-pick"[^>]* form="talk-model" data-model-pick>/); | |
| 392 | expect(compose).toMatch(/<select [^>]*id="talk-model-pick"[^>]* form="talk-model">/); | |
| 393 | expect(compose).toMatch(/data-model-name>\s*Forge's model/); | |
| 394 | expect(compose).toContain('data-name="Large" data-meta="Spark · the forge's credit"'); | |
| 393 | 395 | expect(page).toContain( |
| 394 | 396 | '<form id="talk-model" method="post" action="/talk/' + |
| 395 | 397 | c + |
| @@ -524,6 +526,8 @@ describe("remembered, and in the build composer", () => { | ||
| 524 | 526 | try { |
| 525 | 527 | expect(offers(app.db, keeper).find((o) => o.connection.name === "Mixed")?.models).toEqual(["subq-1"]); |
| 526 | 528 | expect(setChoice(app.db, keeper, conversation(keeper), `${made.value.id} subq-snap-1`).ok).toBe(false); |
| 529 | // Shown with its reason, not to choose. | |
| 530 | expect(offers(app.db, keeper).find((o) => o.connection.name === "Mixed")?.held).toEqual(["subq-snap-1", "lab/subq-snap-2"]); | |
| 527 | 531 | expect(notForTalk("subq-snap-1")).toContain("cannot hold a conversation"); |
| 528 | 532 | expect(notForTalk("canned/large")).toBeUndefined(); |
| 529 | 533 | } finally { |
test/talk-model-sheet.test.ts added +108
| @@ -0,0 +1,108 @@ | ||
| 1 | /** | |
| 2 | * The model list's script (`src/web/talk_model.ts`) on a page of its own: the rows come from the | |
| 3 | * select's options, aliases and models not for Talk wait behind More models, the filter reads every | |
| 4 | * name, arrows and Enter choose, and a choice is posted with the list still open until it is answered. | |
| 5 | */ | |
| 6 | import { expect, test } from "bun:test"; | |
| 7 | import { Window } from "happy-dom"; | |
| 8 | import { isAlias, plainName } from "../src/core/model_choice.ts"; | |
| 9 | import { modelCss, modelJs } from "../src/web/talk_model.ts"; | |
| 10 | ||
| 11 | const option = (value: string, name: string, more = "") => `<option value="${value}" data-name="${name}" data-meta="Spark · your key"${more}>${value}</option>`; | |
| 12 | ||
| 13 | function setup(answer: () => Promise<{ ok: boolean; flash?: string; error?: string }>, builds = false) { | |
| 14 | const window = new Window({ url: "https://forge.test/talk/c1" }); | |
| 15 | const doc = window.document as any; | |
| 16 | const select = `<select id="talk-model-pick" name="model">${option("", "The forge's model")}${option("k lab/one-1", "One 1")}${option("k lab/one-latest", "One Latest", " data-more")}${option("held snap", "Snap", " data-more disabled")}</select>`; | |
| 17 | doc.body.innerHTML = `<div data-talk><button data-model-open><span data-model-name>Forge's model</span></button><p class="talk-status"></p></div> | |
| 18 | <form id="${builds ? "compose" : "talk-model"}" action="https://forge.test/talk/c1/model">${select}</form> | |
| 19 | <template id="talk-ico"><svg class="ico"></svg><svg class="ico"></svg></template> | |
| 20 | <dialog id="talk-models"><button data-models-close></button><input type="search"><div role="listbox" id="talk-models-list" tabindex="0"></div><p data-models-none></p><button data-models-more></button></dialog>`; | |
| 21 | (window as any).HTMLElement.prototype.scrollIntoView = () => {}; | |
| 22 | const sent: string[] = []; | |
| 23 | let open = false; | |
| 24 | const g: any = { forgeOverlay: { open: () => ((open = true), () => void (open = false)) } }; | |
| 25 | const fetched = async (_url: string, o: { body: URLSearchParams }) => { | |
| 26 | sent.push(String(o.body)); | |
| 27 | const body = await answer(); | |
| 28 | return { json: async () => body }; | |
| 29 | }; | |
| 30 | new Function("window", "document", "matchMedia", "fetch", "innerWidth", "innerHeight", modelJs)(g, doc, () => ({ matches: true }), fetched, 1280, 800); | |
| 31 | const d = doc.getElementById("talk-models"), find = d.querySelector("input"); | |
| 32 | return { | |
| 33 | doc, d, find, sent, isOpen: () => open, | |
| 34 | press: (key: string) => find.dispatchEvent(new (window as any).KeyboardEvent("keydown", { key, bubbles: true, cancelable: true })), | |
| 35 | type: (words: string) => { find.value = words; find.dispatchEvent(new (window as any).Event("input")); }, | |
| 36 | names: () => [...d.querySelectorAll("[role=option]")].filter((r: any) => !r.hidden).map((r: any) => r.querySelector("span").textContent), | |
| 37 | select: doc.getElementById("talk-model-pick"), | |
| 38 | name: () => doc.querySelector("[data-model-name]").textContent, | |
| 39 | start: () => doc.querySelector("[data-model-open]").click(), | |
| 40 | }; | |
| 41 | } | |
| 42 | ||
| 43 | test("rows, More models and the filter", () => { | |
| 44 | const t = setup(async () => ({ ok: true, flash: "" })); | |
| 45 | t.start(); | |
| 46 | expect(t.isOpen()).toBe(true); | |
| 47 | expect(t.names()).toEqual(["The forge's model", "One 1"]); | |
| 48 | t.type("latest"); | |
| 49 | expect(t.names()).toEqual(["One Latest"]); | |
| 50 | t.type("nothing like it"); | |
| 51 | expect([t.names(), t.d.querySelector("[data-models-none]").textContent]).toEqual([[], "No model has that in its name."]); | |
| 52 | t.type(""); | |
| 53 | t.d.querySelector("[data-models-more]").click(); | |
| 54 | expect(t.names()).toEqual(["The forge's model", "One 1", "One Latest", "Snap"]); | |
| 55 | }); | |
| 56 | ||
| 57 | test("the script says where the button is, and the width is the sheet's to answer", () => { | |
| 58 | const t = setup(async () => ({ ok: true, flash: "" })); | |
| 59 | t.start(); | |
| 60 | expect(["--open-right", "--open-top"].map((k) => t.d.style.getPropertyValue(k))).toEqual(["0px", "0px"]); | |
| 61 | expect(modelCss).toMatch(/@media \(min-width: 720px\) \{\s*\.talk-models \{[^}]*var\(--open-top/); | |
| 62 | expect(modelCss).toContain("@media (prefers-reduced-motion: reduce) { .talk-models { transition: none; } }"); | |
| 63 | }); | |
| 64 | ||
| 65 | test("the script-less select is laid out only without the script: no bare display beats the rule that hides it", () => { | |
| 66 | expect(modelCss).toContain("@layer components { .talk-model { display: flex;"); | |
| 67 | expect(modelCss.replace(/\/\*[\s\S]*?\*\//g, "")).not.toMatch(/(^|\})\s*\.talk-model \{[^}]*display/); | |
| 68 | }); | |
| 69 | ||
| 70 | test("arrows and Enter choose; the list stays open until the forge has answered", async () => { | |
| 71 | let answer = (_: { ok: boolean; flash: string }) => {}; | |
| 72 | const t = setup(() => new Promise((ok) => (answer = ok))); | |
| 73 | t.start(); | |
| 74 | t.press("ArrowDown"); | |
| 75 | t.press("Enter"); | |
| 76 | expect([t.sent, t.isOpen()]).toEqual([["model=k+lab%2Fone-1"], true]); | |
| 77 | answer({ ok: true, flash: "lab/one-1 · Spark answers here." }); | |
| 78 | await new Promise((done) => setImmediate(done)); | |
| 79 | expect([t.isOpen(), t.name(), t.doc.querySelector(".talk-status").textContent]).toEqual([false, "One 1", "lab/one-1 · Spark answers here."]); | |
| 80 | }); | |
| 81 | ||
| 82 | test("a refused choice changes nothing and says why; a model not for Talk cannot be chosen", async () => { | |
| 83 | const t = setup(async () => ({ ok: false, error: "That model is not offered." })); | |
| 84 | t.start(); | |
| 85 | t.press("ArrowDown"); | |
| 86 | t.press("Enter"); | |
| 87 | await new Promise((done) => setImmediate(done)); | |
| 88 | expect([t.isOpen(), t.name(), t.select.value, t.d.querySelector("[data-models-none]").textContent]).toEqual([true, "Forge's model", "", "That model is not offered."]); | |
| 89 | t.type("snap"); | |
| 90 | t.press("Enter"); | |
| 91 | expect(t.sent).toHaveLength(1); | |
| 92 | }); | |
| 93 | ||
| 94 | test("in the build composer the choice is the form's own field, and nothing is posted", () => { | |
| 95 | const t = setup(async () => ({ ok: true, flash: "" }), true); | |
| 96 | t.start(); | |
| 97 | t.press("ArrowDown"); | |
| 98 | t.press("Enter"); | |
| 99 | expect([t.sent, t.select.value, t.name(), t.isOpen()]).toEqual([[], "k lab/one-1", "One 1", false]); | |
| 100 | }); | |
| 101 | ||
| 102 | test("plain names and aliases come from the id alone", () => { | |
| 103 | // A first word that is the connection's own name goes; one that only starts like it stays. | |
| 104 | const names: [string, string, string][] = [["lab/one-mini-1.4", "One", "Mini 1.4"], ["one-mini-1.4", "work", "One Mini 1.4"], ["ones-mini", "one", "Ones Mini"], ["one", "one", "One"], ["llama3:8b", "", "Llama3 8b"], ["/", "", "/"]]; | |
| 105 | for (const [id, connection, says] of names) expect(plainName(id, connection)).toBe(says); | |
| 106 | const beside = ["one-1", "one-latest", "two-latest", "llama3:8b", "llama3:latest"]; | |
| 107 | expect(beside.filter((m) => isAlias(m, beside))).toEqual(["one-latest", "llama3:latest"]); | |
| 108 | }); |
test/talk-phone.test.ts +8 −3
| @@ -30,8 +30,8 @@ test("without a browser: the conversation's controls are in a dock beside the co | ||
| 30 | 30 | expect(dock).toContain('method="post" action="/talk/new"'); |
| 31 | 31 | expect(dock).toContain(`action="/talk/${shortId}/rename"`); |
| 32 | 32 | expect(dock).toContain(`/talk/${shortId}.md`); |
| 33 | // The dock and the composer share the sticky foot, the dock first; the model's line is the | |
| 34 | // composer's, over its box. | |
| 33 | // The dock and the composer share the sticky foot, the dock first; the model is the composer's, | |
| 34 | // in its tools beside Send. | |
| 35 | 35 | expect(dock).not.toContain("talk-model"); |
| 36 | 36 | const foot = page.indexOf('class="talk-base"'); |
| 37 | 37 | expect(foot).toBeGreaterThan(-1); |
| @@ -39,7 +39,12 @@ test("without a browser: the conversation's controls are in a dock beside the co | ||
| 39 | 39 | expect(page.indexOf('class="talk-dock"')).toBeLessThan(page.indexOf('class="talk-compose"')); |
| 40 | 40 | const compose = page.slice(page.indexOf('class="talk-compose"')); |
| 41 | 41 | expect(compose.indexOf('<label for="talk-model-pick">Model</label>')).toBeGreaterThan(-1); |
| 42 | expect(compose.indexOf('id="talk-model-pick"')).toBeLessThan(compose.indexOf('class="talk-box"')); | |
| 42 | const order = ['class="talk-input"', 'class="talk-tools"', "data-model-open", 'id="talk-model-pick"', "talk-send"].map((x) => compose.indexOf(x)); | |
| 43 | expect(order).not.toContain(-1); | |
| 44 | expect(order).toEqual([...order].sort((a, b) => a - b)); | |
| 45 | // The list is outside the composer's form, so Enter in its filter never sends a message. | |
| 46 | expect(compose.slice(0, compose.indexOf("</form>"))).not.toContain('id="talk-models"'); | |
| 47 | expect(compose).toContain('id="talk-models"'); | |
| 43 | 48 | const { talkCss } = await import("../src/web/pages/talk_client.ts"); |
| 44 | 49 | expect(talkCss).toContain(".talk-head > :not(.talk-title) { display: none; }"); |
| 45 | 50 | expect(talkCss).toMatch(/@media \(min-width: 56\.25rem\) \{ \.talk-dock \{ display: none; \} \}/); |
new above
offline