Public: anyone can read this; the crew can change it.

Talk: choose the model where you write, in the build composer too, and it is remembered #17789

opened this

Merged 7h 48m ago, live in production

talk-model-easy → main 0 commits

  • Merged. talk-model-easy was merged into main as 4b28afa.

Review

Sign in to review this change.
17 files changed +321 −116
docs/design/areas/talk.md +2 −2
@@ -95,9 +95,9 @@ The window is the thread's one scroller; the list and a side pane are sticky col
9595 - `.talk-send`, `.talk-stop` — the one round button at the end: Send (an arrow up), or Stop (a square) while an answer runs and the box is empty.
9696 - `.talk-steer` — the one secondary control, shown while an answer runs and words are typed: send them now.
9797 - `.talk-hint` — "Enter sends", only where there is a mouse.
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, which then also holds the model (#16586). `.talk-head` is the title alone there; from 56.25rem the dock is hidden.
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.
9999 - `.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 under the box: 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` — 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.
101101 - `.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.
102102 - `.talk-fold-list` — the steps inside it, on a hairline at the start edge.
103103 - `.talk-live` — the block being written; its running line shimmers (plain under reduced motion).
docs/features/talk.md +17 −5
@@ -20,7 +20,7 @@ The agent reaches the forge only through its MCP, as you. Its `tools/list` is th
2020
2121 Reached from the Talk icon in every page's top bar, "Talk to the forge" in the palette (`Ctrl/Cmd+K`), `g t`, and the Talk button beside the tell box on home. Signed out, it sends you to /signin and back. It shows your own conversation (the last 50 turns, oldest at the top, opened on the newest; "Earlier" puts the 50 before them above, in order, and keeps the turn being read where it was, or opens them as a page of their own without the script) and a composer; Enter sends and Shift+Enter breaks a line. `/` jumps to the composer from anywhere on the page except inside a field (and with no Ctrl, Cmd or Alt held); the composer carries `aria-keyshortcuts="/"`. It is a web shortcut only: the terminal door (`ssh <forge> talk`, `forge talk`) takes its words as typed and has no shortcut keys, so `/` there is just a character.
2222
23 On a phone the composer is sticky and lifts above the on-screen keyboard (the script sets `--kb` from `visualViewport`); the head is one row (Chats, a 44 px button named by its word that opens the chat list at its top on the newest chat, then the title, the model picker, Chat and Preview beside a preview, the menu and New) that never wraps, and a wide table scrolls inside its message, never the page. `test/talk-phone.test.ts` measures these at 360, 375 and 390 px in Chromium with touch; in the forge's own check a missing Chromium fails it rather than skipping; the log is a `role=log` (polite, additions only) and the status line `role=status`, each already a polite live region, so a reply is announced once.
23 On a phone the composer is sticky and lifts above the on-screen keyboard (the script sets `--kb` from `visualViewport`); the head is one row (Chats, a 44 px button named by its word that opens the chat list at its top on the newest chat, then the title, Chat and Preview beside a preview, the menu and New) that never wraps, and a wide table scrolls inside its message, never the page. `test/talk-phone.test.ts` measures these at 360, 375 and 390 px in Chromium with touch; in the forge's own check a missing Chromium fails it rather than skipping; the log is a `role=log` (polite, additions only) and the status line `role=status`, each already a polite live region, so a reply is announced once.
2424
2525 A reply streams in over `GET /talk/stream?after=<turn id>` (server-sent events, one `turn` frame per stored turn, each carrying the server-rendered markup, and `live` frames for the block being written, see "Live" below). The stream ends with the turn (`done`), or after 40 seconds (`more`), well inside the edge's timeout; the page then reconnects from the last turn id it saw (`Last-Event-ID` works too). Without the script the composer is a plain form and a reload shows the answer.
2626
@@ -131,13 +131,25 @@ Prior art read: Vercel AI Elements (Apache-2.0 React on shadcn; anatomy and beha
131131
132132 ## The model picker
133133
134 When a connection on Connect your AI offers models (docs/features/connections.md), the composer has a
135 Model line: the forge's model, then each model a working connection offers, by connection. The choice
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
136137 is the conversation's own and is kept with it; the line under each reply names the model it ran on
137138 (and its cost when the price table knows the model, never $0). It is a plain form, so it works with
138139 the script off; with the script it is sent as soon as it changes. In the terminal, `m` in an open
139140 conversation is the same picker.
140141
142 **Remembered.** A new conversation starts on the model you chose last, wherever you chose it, while it
143 is still offered to you; if it is not, it starts on the forge's model and says so. Choosing in one
144 conversation never changes another.
145
146 **In the build composer** (`?build=1`) the same line is part of the build's form, so the first turn
147 runs on it. `POST /api/v1/builds` takes it as `model`: the connection's id, a space and the model;
148 empty is the forge's own, and left out it is your last choice. In the terminal, `m` on Build an app.
149
150 **Not offered:** a model that cannot hold a conversation (a decision model, say), even one ticked on
151 Connect your AI. The rule and its reason are one table, `NOT_FOR_TALK` in `src/core/model_choice.ts`.
152
141153 Only working connections are offered: a person's own, and the forge's to an admin or to a person it
142154 is granted to. A turn whose model does not answer says so in one sentence, with Retry and the picker,
143155 and nothing else answers for it (a rate limit says the model is busy). A turn never changes the
@@ -182,9 +194,9 @@ An empty conversation offers Build an app among its starters (#15734); it opens
182194
183195 - **Versions** are the branch's commits past main, numbered v1, v2 from the oldest (`src/actions/build.ts`); nothing about them is stored twice. The first one opens the branch's pull, which is what gives it a preview: it opens when a turn ends, or on Restore or Publish; a read never writes. `?v=N` shows that version's files changed; **Restore** makes a new version holding exactly its tree, history kept.
184196 - **Publish** merges the pull to the default branch, which deploys production; the production URL then shows as a link. Only a person publishes.
185 - **API:** `POST /api/v1/builds {prompt, template?}`, `GET /api/v1/conversations/:id/build`, `GET …/build/versions/:n/diff`, `POST …/build/restore {version}`, `POST …/build/publish`. Web forms: `POST /talk/build`, `/talk/:id/build/restore`, `/talk/:id/build/publish`.
197 - **API:** `POST /api/v1/builds {prompt, template?, model?}`, `GET /api/v1/conversations/:id/build`, `GET …/build/versions/:n/diff`, `POST …/build/restore {version}`, `POST …/build/publish`. Web forms: `POST /talk/build`, `/talk/:id/build/restore`, `/talk/:id/build/publish`.
186198 - **Limits:** five builds an hour and ten unpublished at once, per person (`BUILDS_PER_HOUR`, `UNPUBLISHED_MAX`); a template must be one on offer to that person, on the API as on the page; a start that fails takes back the repository and conversation it made.
187 - **Terminal:** `:` then **Build an app**. `n` says what to build (`t` chooses the template), Enter opens a build and lists its versions newest first, Enter again shows the files that version changed, `U` restores the chosen version, `P` publishes, `R` reloads. The screen calls the same `actions/build.ts` functions as the page, so it is gated the same way (your own conversation, a writer of the repository) and what it does is what the page shows on its next read.
199 - **Terminal:** `:` then **Build an app**. `n` says what to build (`t` chooses the template, `m` the model), Enter opens a build and lists its versions newest first, Enter again shows the files that version changed, `U` restores the chosen version, `P` publishes, `R` reloads. The screen calls the same `actions/build.ts` functions as the page, so it is gated the same way (your own conversation, a writer of the repository) and what it does is what the page shows on its next read.
188200 - Proof: `test/talk-build.test.ts` runs prompt, repository, v1, v2, restore v1 and publish against a scratch forge; `test/tui-talk-build.test.ts` does the same from the terminal.
189201
190202 ## Your accounts elsewhere (`origins`)
src/actions/build.ts +8 −2
@@ -16,6 +16,7 @@ import { RateLimiter } from "../core/ratelimit.ts";
1616 import { commitIdentity } from "../core/commit_identity.ts";
1717 import { getAppByRepo } from "../core/apps.ts";
1818 import { createConversation, dropConversation, getConversation, renameConversation, TITLE_MAX } from "../core/conversations.ts";
19 import { choiceFrom, setChoice } from "../core/model_choice.ts";
1920 import { getPull, isDraft, type Pull } from "../core/pulls.ts";
2021 import { getRepoById, type Repo } from "../core/repos.ts";
2122 import type { User } from "../core/users.ts";
@@ -63,7 +64,7 @@ function takeBuild(app: App, user: User): boolean {
6364 return limiter.take(`build:${user.id}`, "rw").allowed;
6465 }
6566
66 export type BuildError = "unauthorized" | "not_found" | "no_name" | "no_version" | "nothing_to_publish" | "moved" | "bad_template" | "rate_limited" | "too_many_builds" | "pull_closed" | "failed";
67 export type BuildError = "unauthorized" | "not_found" | "no_name" | "no_version" | "nothing_to_publish" | "moved" | "bad_template" | "model_not_offered" | "rate_limited" | "too_many_builds" | "pull_closed" | "failed";
6768
6869 export const BUILD_WORDS: Readonly<Record<string, string>> = {
6970 unauthorized: "Sign in to build.",
@@ -73,6 +74,7 @@ export const BUILD_WORDS: Readonly<Record<string, string>> = {
7374 nothing_to_publish: "Nothing to publish yet: no version has changed the app.",
7475 moved: "The build changed while you did that. Try again.",
7576 bad_template: "That template is not on offer to you.",
77 model_not_offered: "That model is not offered to you now, so nothing was started. Pick another.",
7678 rate_limited: `At most ${BUILDS_PER_HOUR} builds an hour; try again later.`,
7779 too_many_builds: `You hold ${UNPUBLISHED_MAX} builds that are not published; publish one first.`,
7880 pull_closed: "This build's pull is closed or merged: reopen it, or start a new conversation.",
@@ -97,22 +99,26 @@ export const buildSaidWords = (said: BuildSaid): string => (said.kept ? `The app
9799 * Make the repository from the template, start the chat on its branch and
98100 * send the prompt. `said` is set when the agent did not start on it: kept with its line (resting,
99101 * busy, no account…; Retry sends it), or refused (rate limited…). The build exists either way.
102 * `model` is a picker's value (`core/model_choice.ts`) and the first turn runs on it; left out, the
103 * conversation starts on the person's last choice, as any new one does.
100104 */
101105 export async function startBuild(
102106 app: App,
103107 actor: User | undefined,
104 input: { readonly prompt: string; readonly template?: string },
108 input: { readonly prompt: string; readonly template?: string; readonly model?: string },
105109 ): Promise<Result<{ build: ChatBuild; repo: Repo; said: BuildSaid | undefined }, BuildError>> {
106110 const user = requireUser(actor);
107111 if (!user.ok) return user;
108112 const template = input.template === undefined || input.template === "" ? undefined : input.template;
109113 // The API reaches this too: a template is only ever one the person can see.
110114 if (template !== undefined && !offeredTemplates(app.db, user.value).includes(template)) return err("bad_template");
115 if (input.model !== undefined && !choiceFrom(app.db, user.value, input.model).ok) return err("model_not_offered");
111116 if (unpublishedBuilds(app.db, user.value.id) >= UNPUBLISHED_MAX) return err("too_many_builds");
112117 if (!takeBuild(app, user.value)) return err("rate_limited");
113118 // Cheapest step first, so a refusal there leaves nothing; later failures take back what was made.
114119 const conversation = createConversation(app.db, user.value.id);
115120 if (!conversation.ok) return err("failed");
121 if (input.model !== undefined) setChoice(app.db, user.value, conversation.value.id, input.model);
116122 const made = await newAppFromSentence(app, user.value, { sentence: input.prompt, ...(template === undefined ? {} : { template }) });
117123 if (!made.ok) {
118124 dropConversation(app.db, user.value.id, conversation.value.id);
src/actions/build_input.ts +4
@@ -16,5 +16,9 @@ export const promptRefusal = (prompt: unknown, field = "prompt"): string | undef
1616 export const templateRefusal = (template: unknown): string | undefined =>
1717 template === undefined || (typeof template === "string" && BUILD_TEMPLATE.test(template)) ? undefined : "template is owner/name";
1818
19 /** A picker's value (`core/model_choice.ts`); whether it is offered is `startBuild`'s to say. */
20 export const modelRefusal = (model: unknown): string | undefined =>
21 model === undefined || (typeof model === "string" && model.length <= 400) ? undefined : "model is a connection's id, a space and one of its models, or empty for the forge's own";
22
1923 export const versionRefusal = (n: unknown): string | undefined =>
2024 typeof n === "number" && Number.isInteger(n) && n >= 1 ? undefined : "version is the number of a version, from 1";
src/contract/openapi/routes/postApiV1Builds.ts +4 −2
@@ -4,15 +4,17 @@ export const route: Route = {
44 method: "post",
55 path: "/api/v1/builds",
66 summary: "Build an app from one prompt",
7 detail: "Build an app from one prompt (and optionally an offered template, owner/name): makes the repository, starts a conversation in it on its own branch and sends the prompt; the agent's turns that change code become versions v1, v2, …",
7 detail: "Build an app from one prompt (and optionally an offered template, owner/name): makes the repository, starts a conversation in it on its own branch and sends the prompt; `model` is a connection's id, a space and one of its models, as Talk's picker sends it (empty for the forge's own; left out, your last choice), and the first turn runs on it; the agent's turns that change code become versions v1, v2, …",
88 auth: true,
99 role: "member",
1010 status: 201,
11 body: { prompt: "string", template: "string" },
11 body: { prompt: "string", template: "string", model: "string" },
1212 reply: { conversation: "string", repo: "string", branch: "string" },
1313 refusals: {
1414 invalid_template: "the template is not owner/name (422)",
1515 bad_template: "the template is not one on offer to you (422)",
16 invalid_model: "the model is not a string of up to 400 characters (422)",
17 model_not_offered: "the model is not one Talk offers you now (422)",
1618 rate_limited: "at most 5 builds an hour (429)",
1719 too_many_builds: "you hold 10 builds that are not published (429)",
1820 unauthorized: "sign in (401)",
src/core/conversations.ts +3 −1
@@ -9,6 +9,7 @@
99 import type { Database } from "bun:sqlite";
1010 import { id } from "../kernel/id.ts";
1111 import { err, ok, type Result } from "../kernel/result.ts";
12 import { startOnLast } from "./model_choice.ts";
1213
1314 export const TURN_ROLES = ["person", "agent", "tool", "confirm"] as const;
1415 export type TurnRole = (typeof TURN_ROLES)[number];
@@ -108,13 +109,14 @@ export function dropConversation(db: Database, userId: string, conversationId: s
108109 db.query("DELETE FROM conversation WHERE id = ?1 AND user_id = ?2").run(conversationId, userId);
109110 }
110111
111 /** Start a new, empty conversation. */
112 /** Start a new, empty conversation, on the person's last chosen model while it is offered. */
112113 export function newConversation(db: Database, userId: string): Conversation {
113114 const now = new Date().toISOString();
114115 const row: ConversationRow = { id: id(), user_id: userId, claude_session_id: "", created_at: now, updated_at: now, title: "", archived_at: null, pinned_at: null };
115116 db.query(
116117 "INSERT INTO conversation (id, user_id, claude_session_id, created_at, updated_at) VALUES (?1,?2,'',?3,?3)",
117118 ).run(row.id, userId, now);
119 startOnLast(db, userId, row.id);
118120 return conversationOf(row);
119121 }
120122
src/core/model_choice.ts +81 −25
@@ -5,6 +5,8 @@
55 * that the person may use: their own, or the forge's when they are an admin or it is granted to them.
66 * Its models are the ones chosen on Connect your AI, else every one its test listed. A stored choice
77 * whose connection fails later is not quietly swapped: the turn says so (`crew/conversation.ts`).
8 * A person's last choice is theirs (`user_setting`), and a new conversation starts on it while it is
9 * offered; the conversations already there keep their own.
810 */
911 import type { Database } from "bun:sqlite";
1012 import { err, ok, type Result } from "../kernel/result.ts";
@@ -13,11 +15,26 @@ import {
1315 listConnections,
1416 type Connection,
1517 } from "./connections.ts";
16 import { EVERYONE } from "./subscriptions.ts";
18 import { getUserSetting, setUserSetting } from "./settings.ts";
19 import { anyTalkConnection, EVERYONE } from "./subscriptions.ts";
20 import { getUserById } from "./users.ts";
1721
1822 /** At most this many models of one connection are offered. */
1923 export const OFFERED_MAX = 100;
2024
25 /**
26 * Models a server lists that cannot hold a conversation, each with why: Talk never offers them,
27 * chosen on Connect your AI or not. A listing carries names and prices only, so a name is what
28 * there is to go by; a new kind is a line here and nowhere else.
29 */
30 const NOT_FOR_TALK: readonly { readonly name: RegExp; readonly why: string }[] = [
31 { name: /(^|\/)subq-snap-/, why: "it makes decisions and cannot hold a conversation" },
32 ];
33
34 /** Why Talk does not offer a model, or undefined when it may. */
35 export const notForTalk = (model: string): string | undefined =>
36 NOT_FOR_TALK.find((k) => k.name.test(model))?.why;
37
2138 export interface Offer {
2239 readonly connection: Connection;
2340 readonly models: readonly string[];
@@ -74,7 +91,9 @@ export function offers(
7491 models: (c.chosen.length > 0
7592 ? c.chosen
7693 : c.models.map((m) => m.id)
77 ).slice(0, OFFERED_MAX),
94 )
95 .filter((m) => notForTalk(m) === undefined)
96 .slice(0, OFFERED_MAX),
7897 }))
7998 .filter((o) => o.models.length > 0);
8099 }
@@ -96,9 +115,63 @@ export function choiceOf(
96115 : { connectionId: row.connection_id, model: row.model };
97116 }
98117
118 type Person = { readonly id: string; readonly isAdmin: boolean };
119
120 /** A picker's value read as a choice: undefined for "", the forge's own; refused when not offered now. */
121 export function choiceFrom(
122 db: Database,
123 user: Person,
124 value: string,
125 ): Result<Choice | undefined, "not_offered"> {
126 if (value === "") return ok(undefined);
127 const at = value.indexOf(" ");
128 const choice = { connectionId: value.slice(0, at), model: value.slice(at + 1) };
129 return at > 0 && offers(db, user).some((o) => o.connection.id === choice.connectionId && o.models.includes(choice.model))
130 ? ok(choice)
131 : err("not_offered");
132 }
133
134 /** The person's last choice, kept for their next conversation. */
135 const LAST_KEY = "talk.model";
136
137 /** What a new conversation starts on: the person's last choice while it is offered, else the forge's own. */
138 export function startingChoice(db: Database, user: Person): Choice | undefined {
139 if (!anyTalkConnection(db)) return undefined;
140 const last = choiceFrom(db, user, getUserSetting(db, user.id, LAST_KEY) ?? "");
141 return last.ok ? last.value : undefined;
142 }
143
144 /** Why a new conversation is not on the person's last model, in one sentence; undefined when it is. */
145 export function lostModelLine(db: Database, user: Person): string | undefined {
146 const last = getUserSetting(db, user.id, LAST_KEY) ?? "";
147 return choiceFrom(db, user, last).ok
148 ? undefined
149 : `Your last model, ${last.slice(last.indexOf(" ") + 1)}, is not offered now, so this starts on the forge's model.`;
150 }
151
152 /** Put a conversation just made on its person's last model (`conversations.ts`). */
153 export function startOnLast(db: Database, userId: string, conversationId: string): void {
154 if (!anyTalkConnection(db)) return;
155 const user = getUserById(db, userId);
156 const choice = user === undefined ? undefined : startingChoice(db, user);
157 if (choice !== undefined)
158 db.query("UPDATE conversation SET connection_id = ?2, model = ?3 WHERE id = ?1").run(conversationId, choice.connectionId, choice.model);
159 }
160
161 /** What a choice is called wherever it is said: the model and its connection, or the forge's own. */
162 export const choiceWords = (db: Database, userId: string, choice: Choice | undefined): string =>
163 choice === undefined ? FORGE_MODEL : choiceLabel(connectionFor(db, userId, choice.connectionId) ?? { name: "a removed connection" }, choice.model);
164
165 /** The terminal's list: the forge's own, then every model offered, as the page's select has them. */
166 export const pickList = (db: Database, user: Person): { id: string; label: string }[] => [
167 { id: "", label: FORGE_MODEL },
168 ...offers(db, user).flatMap((o) => o.models.map((m) => ({ id: choiceValue({ connectionId: o.connection.id, model: m }), label: choiceLabel(o.connection, m) }))),
169 ];
170
99171 /**
100172 * Set a conversation's model from a picker's value: "" for the forge's own, else one the picker
101 * offers this person now. Anything else is refused and nothing changes.
173 * offers this person now. Anything else is refused and nothing changes. The choice is also kept as
174 * the person's last, for the conversations they start after it.
102175 */
103176 export function setChoice(
104177 db: Database,
@@ -114,30 +187,13 @@ export function setChoice(
114187 >("SELECT COUNT(*) AS n FROM conversation WHERE id = ?1 AND user_id = ?2")
115188 .get(conversationId, user.id)!.n > 0;
116189 if (!exists) return err("not_found");
117 if (value === "") {
118 db.query(
119 "UPDATE conversation SET connection_id = '', model = '' WHERE id = ?1",
120 ).run(conversationId);
121 return ok(undefined);
122 }
123 const at = value.indexOf(" ");
124 const choice = {
125 connectionId: value.slice(0, at),
126 model: value.slice(at + 1),
127 };
128 if (
129 at <= 0 ||
130 !offers(db, user).some(
131 (o) =>
132 o.connection.id === choice.connectionId &&
133 o.models.includes(choice.model),
134 )
135 )
136 return err("not_offered");
190 const choice = choiceFrom(db, user, value);
191 if (!choice.ok) return choice;
137192 db.query(
138193 "UPDATE conversation SET connection_id = ?2, model = ?3 WHERE id = ?1",
139 ).run(conversationId, choice.connectionId, choice.model);
140 return ok(choice);
194 ).run(conversationId, choice.value?.connectionId ?? "", choice.value?.model ?? "");
195 setUserSetting(db, user.id, LAST_KEY, value);
196 return choice;
141197 }
142198
143199 /**
src/http/api/conversation_build.ts +6 −3
@@ -7,13 +7,13 @@
77 */
88
99 import { BUILD_WORDS, buildState, publishBuild, restoreVersion, startBuild, versionDiff, type BuildError } from "../../actions/build.ts";
10 import { BUILD_ID as ID, promptRefusal, templateRefusal, versionRefusal } from "../../actions/build_input.ts";
10 import { BUILD_ID as ID, modelRefusal, promptRefusal, templateRefusal, versionRefusal } from "../../actions/build_input.ts";
1111 import { apiError, boundedBody, json, tryAgain, unauthorized } from "../respond.ts";
1212 import type { Router } from "../router.ts";
1313 import type { Handler } from "../context.ts";
1414 import { mayChange } from "./conversation_talk.ts";
1515
16 const STATUS: Readonly<Record<BuildError, number>> = { unauthorized: 401, not_found: 404, no_name: 422, no_version: 404, nothing_to_publish: 409, moved: 409, bad_template: 422, rate_limited: 422, too_many_builds: 422, pull_closed: 409, failed: 422 };
16 const STATUS: Readonly<Record<BuildError, number>> = { unauthorized: 401, not_found: 404, no_name: 422, no_version: 404, nothing_to_publish: 409, moved: 409, bad_template: 422, model_not_offered: 422, rate_limited: 422, too_many_builds: 422, pull_closed: 409, failed: 422 };
1717
1818 /** Both build limits are per hour: say so with the 429 (#10762). */
1919 const BUILD_WAIT = 3600;
@@ -34,7 +34,10 @@ export function conversationBuildRoutes(router: Router<Handler>): void {
3434 const template = input["template"];
3535 const badTemplate = templateRefusal(template);
3636 if (badTemplate !== undefined || (template !== undefined && typeof template !== "string")) return apiError("invalid_template", 422, badTemplate ?? "");
37 const started = await startBuild(ctx.app, user, { prompt, ...(template === undefined ? {} : { template }) });
37 const model = input["model"];
38 const badModel = modelRefusal(model);
39 if (badModel !== undefined || (model !== undefined && typeof model !== "string")) return apiError("invalid_model", 422, badModel ?? "");
40 const started = await startBuild(ctx.app, user, { prompt, ...(template === undefined ? {} : { template }), ...(model === undefined ? {} : { model }) });
3841 if (!started.ok) return fail(started.error);
3942 const { build, repo, said } = started.value;
4043 return json({ conversation: build.conversationId, repo: `${repo.ownerName}/${repo.name}`, branch: build.branch, ...(said === undefined ? {} : { said: said.why, message: said.message, kept: said.kept }) }, 201);
src/tui/screens/talk_build.ts +31 −5
@@ -10,6 +10,7 @@ import { buildSaidWords, buildState, BUILD_WORDS, publishBuild, publishedWords,
1010 import { keyOf } from "../../web/keymap.ts";
1111 import { offeredTemplates } from "../../core/app_templates.ts";
1212 import { buildsOf } from "../../core/chat_build.ts";
13 import { choiceValue, offers, pickList, startingChoice } from "../../core/model_choice.ts";
1314 import { getRepoById } from "../../core/repos.ts";
1415 import type { Ctx, Screen } from "../app/app.ts";
1516 import { binding } from "../app/keys.ts";
@@ -17,7 +18,7 @@ import { style } from "../term/style.ts";
1718 import { truncate } from "../term/width.ts";
1819 import type { Session } from "../session.ts";
1920 import { fill, len, split } from "../ui/layout.ts";
20 import { ListState, Scroll, ago, confirmScreen, drawLines, drawList, promptScreen, runAsync, type ListRow } from "./common.ts";
21 import { ListState, Scroll, ago, confirmScreen, drawLines, drawList, pickerScreen, promptScreen, runAsync, type ListRow } from "./common.ts";
2122
2223 const words = (error: string): string => BUILD_WORDS[error] ?? "That did not go through.";
2324
@@ -143,20 +144,22 @@ function buildScreen(f: Session, ctx: Ctx, conversationId: string, title: string
143144 return screen;
144145 }
145146
146 /** The person's builds; `n` starts one from a prompt, `t` chooses the template it starts from. */
147 /** The person's builds; `n` starts one from a prompt, `t` chooses the template and `m` the model it starts on. */
147148 export function talkBuildScreen(f: Session, ctx: Ctx): Screen {
148149 const state = new ListState();
149150 let note = "";
150151 // "" is the forge's default template; the rest are those on offer to this person.
151152 let template = "";
153 // A picker's value (`core/model_choice.ts`); until one is picked, the person's last choice.
154 let model: string | undefined;
152155 const items = () => (f.user === undefined ? [] : buildsOf(f.app.db, f.user.id));
153156 const screen: Screen = {
154157 title: "Build an app",
155 keys: [binding(["j", "k"], "move"), binding(["enter"], "open"), binding(["n"], "new build"), binding(["t"], "template"), binding(["esc"], "back")],
158 keys: [binding(["j", "k"], "move"), binding(["enter"], "open"), binding(["n"], "new build"), binding(["t"], "template"), binding(["m"], "model"), binding(["esc"], "back")],
156159 render(area, s) {
157160 const c = ctx.theme.c;
158161 const [head, body] = split(area, "v", [len(1), fill(1)]);
159 const text = note !== "" ? note : `Starting from ${template === "" ? "the default template" : template}; n says what to build, t changes the template.`;
162 const text = note !== "" ? note : `Starting from ${template === "" ? "the default template" : template}; n says what to build, t changes the template.${model === undefined ? "" : ` On ${pickList(f.app.db, f.user!).find((i) => i.id === model)?.label ?? "a model no longer offered"}.`}`;
160163 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
161164 const rows: ListRow[] = items().map((b) => ({
162165 title: b.title === "" ? "Untitled build" : b.title,
@@ -183,6 +186,29 @@ export function talkBuildScreen(f: Session, ctx: Ctx): Screen {
183186 ctx.invalidate();
184187 return true;
185188 }
189 if (e.key === "m") {
190 // The page's picker in the build composer: the first turn runs on what is chosen.
191 if (offers(f.app.db, user).length === 0) {
192 note = "No connection offers a model: add one on Connect your AI (the Model budget screen).";
193 ctx.invalidate();
194 return true;
195 }
196 const last = startingChoice(f.app.db, user);
197 ctx.push(
198 pickerScreen(ctx, screen, {
199 title: "Model",
200 items: pickList(f.app.db, user),
201 chosen: [model ?? (last === undefined ? "" : choiceValue(last))],
202 onPick: ([value]) => {
203 if (value === undefined) return;
204 model = value;
205 note = "";
206 ctx.invalidate();
207 },
208 }),
209 );
210 return true;
211 }
186212 if (e.key === "n") {
187213 ctx.push(
188214 promptScreen(ctx, screen, {
@@ -191,7 +217,7 @@ export function talkBuildScreen(f: Session, ctx: Ctx): Screen {
191217 onSubmit: (prompt) => {
192218 if (prompt.trim() === "") return "Say what to build.";
193219 runAsync(ctx, async () => {
194 const started = await startBuild(f.app, user, { prompt, ...(template === "" ? {} : { template }) });
220 const started = await startBuild(f.app, user, { prompt, ...(template === "" ? {} : { template }), ...(model === undefined ? {} : { model }) });
195221 note = started.ok ? (started.value.said === undefined ? "Started; Enter opens it." : buildSaidWords(started.value.said)) : words(started.error);
196222 ctx.invalidate();
197223 });
src/tui/screens/talk_chats.ts +8 −9
@@ -64,7 +64,7 @@ import type { Session } from "../session.ts";
6464 import type { User } from "../../core/users.ts";
6565 import { agoWords, togetherOf } from "../../design/together.ts";
6666 import { fill, len, split } from "../ui/layout.ts";
67 import { choiceLabel, choiceOf, choiceValue, FORGE_MODEL, offers, setChoice } from "../../core/model_choice.ts";
67 import { choiceOf, choiceValue, choiceWords, lostModelLine, offers, pickList, setChoice } from "../../core/model_choice.ts";
6868 import { ListState, Scroll, ago, confirmScreen, drawLines, drawList, errorText, later, live, pickerScreen, promptScreen, runAsync, type ListRow, type PickItem } from "./common.ts";
6969 import { answerWall } from "../../actions/pulls.ts";
7070 import { fresh, mayAct, pressCard, PRESS_REFUSED } from "../../actions/talk_act.ts";
@@ -531,17 +531,13 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
531531 if (user === undefined || e.ctrl || e.alt) return false;
532532 if (e.key === "m" && !pane) {
533533 // The page's model picker (`core/model_choice.ts`): the forge's own and every model offered.
534 const offered = offers(f.app.db, user);
535 if (offered.length === 0) {
534 if (offers(f.app.db, user).length === 0) {
536535 note = "No connection offers a model: add one on Connect your AI (the Model budget screen).";
537536 ctx.invalidate();
538537 return true;
539538 }
540539 const now = choiceOf(f.app.db, user.id, chat.id);
541 const items: PickItem[] = [
542 { id: "", label: FORGE_MODEL },
543 ...offered.flatMap((o) => o.models.map((m) => ({ id: choiceValue({ connectionId: o.connection.id, model: m }), label: choiceLabel(o.connection, m) }))),
544 ];
540 const items: PickItem[] = pickList(f.app.db, user);
545541 ctx.push(
546542 pickerScreen(ctx, screen, {
547543 title: "Model",
@@ -550,7 +546,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
550546 onPick: ([value]) => {
551547 if (value === undefined) return;
552548 const set = setChoice(f.app.db, user, chat.id, value);
553 note = !set.ok ? "That model is not offered now." : `${items.find((i) => i.id === value)?.label ?? FORGE_MODEL} answers here.`;
549 note = !set.ok ? "That model is not offered now." : `${choiceWords(f.app.db, user.id, set.value)} answers here.`;
554550 ctx.invalidate();
555551 },
556552 }),
@@ -928,7 +924,10 @@ export function talkChatsScreen(f: Session, ctx: Ctx): Screen {
928924 if (title.trim() !== "" && !renameConversation(f.app.db, user.id, made.value.id, title).ok) return BAD_TITLE;
929925 archived = false;
930926 state.index = 0;
931 say(`Started /talk/${made.value.id}.`);
927 // Which model it starts on, when there is a choice to speak of.
928 const lost = lostModelLine(f.app.db, user);
929 const on = choiceOf(f.app.db, user.id, made.value.id);
930 say(`Started /talk/${made.value.id}.${lost !== undefined ? ` ${lost}` : on === undefined ? "" : ` ${choiceWords(f.app.db, user.id, on)} answers there.`}`);
932931 return undefined;
933932 },
934933 }),
src/web/pages/talk.ts +13 −16
@@ -515,13 +515,13 @@ function displayForm(display: TalkDisplay, back: string): Html {
515515 * The open conversation's head: on a phone the way to the list, then its name, what it has cost,
516516 * and one menu for Rename, Download, Pin and Archive, each a plain form or link.
517517 */
518 function hereBar(ctx: Ctx, conversation: Conversation, context: Context | undefined, display: TalkDisplay, tabs: Html | null, picker: Html | null = null): Html {
518 function hereBar(ctx: Ctx, conversation: Conversation, context: Context | undefined, display: TalkDisplay, tabs: Html | null): Html {
519519 const archived = conversation.archivedAt !== null;
520520 return html`<header class="talk-head">
521521 <a class="btn talk-back" data-variant="ghost" href="${urlOf(conversation)}?chats=1" title="All your chats, newest first">${icon("comment")}Chats</a>
522522 <h2 class="talk-title">${nameOf(conversation)}${archived ? " (archived)" : ""}</h2>
523 ${picker}${tabs}${context !== undefined && context.share >= CONTEXT_SHOWN ? html`<span class="talk-fill small muted" title="${contextText(context)}">${meter(context.share * 100, contextText(context))} context used</span>` : null}
524 ${conversationMenu(ctx, conversation, context, display, null)}
523 ${tabs}${context !== undefined && context.share >= CONTEXT_SHOWN ? html`<span class="talk-fill small muted" title="${contextText(context)}">${meter(context.share * 100, contextText(context))} context used</span>` : null}
524 ${conversationMenu(ctx, conversation, context, display)}
525525 <form method="post" action="${HERE}/new">${iconBtn("plus", "New conversation", { variant: "ghost" })}</form>
526526 </header>`;
527527 }
@@ -533,8 +533,8 @@ function totalOnce(ctx: Ctx, id: string): ReturnType<typeof conversationTotal> {
533533 return totals.get(ctx);
534534 }
535535
536 /** The conversation menu: Rename, Download, Pin, Archive, Display, and on a phone the model too. */
537 function conversationMenu(ctx: Ctx, conversation: Conversation, context: Context | undefined, display: TalkDisplay, picker: Html | null): Html {
536 /** The conversation menu: Rename, Download, Pin, Archive, Display. */
537 function conversationMenu(ctx: Ctx, conversation: Conversation, context: Context | undefined, display: TalkDisplay): Html {
538538 const archived = conversation.archivedAt !== null;
539539 const item = (action: string, field: string, value: string, label: string, ic: "pin" | "history" | "trash"): Html =>
540540 html`<form method="post" action="${urlOf(conversation)}/${action}"><input type="hidden" name="${field}" value="${value}" /><button class="menu-item" type="submit">${icon(ic)}<span class="grow">${label}</span></button></form>`;
@@ -544,7 +544,6 @@ function conversationMenu(ctx: Ctx, conversation: Conversation, context: Context
544544 triggerOptions: { variant: "ghost", extra: "btn-icon" },
545545 items: [
546546 html`<div class="talk-figures small muted">${totalLine(totalOnce(ctx, conversation.id))}${contextLine(context)}</div>`,
547 ...(picker === null ? [] : [picker]),
548547 html`<form class="talk-rename" method="post" action="${urlOf(conversation)}/rename">
549548 <input class="input" name="title" value="${conversation.title}" maxlength="${TITLE_MAX}" aria-label="Title" placeholder="Title" />
550549 ${btn("Rename", { size: "sm" })}
@@ -559,15 +558,15 @@ function conversationMenu(ctx: Ctx, conversation: Conversation, context: Context
559558
560559 /**
561560 * Below 900 px the controls ride with the composer, in thumb reach: the way to the chat list, New,
562 * Chat/Preview when a preview is live, and the menu, which holds the model. It is hidden at and
561 * Chat/Preview when a preview is live, and the menu. It is hidden at and
563562 * above 900 px, where the head carries them.
564563 */
565 function dockBar(ctx: Ctx, conversation: Conversation, context: Context | undefined, display: TalkDisplay, tabs: Html | null, picker: Html | null): Html {
564 function dockBar(ctx: Ctx, conversation: Conversation, context: Context | undefined, display: TalkDisplay, tabs: Html | null): Html {
566565 return html`<nav class="talk-dock" aria-label="Conversation controls">
567566 <a class="btn talk-back" data-variant="ghost" href="${urlOf(conversation)}?chats=1" title="All your chats, newest first">${icon("comment")}Chats</a>
568567 <form method="post" action="${HERE}/new">${iconBtn("plus", "New conversation", { variant: "ghost" })}</form>
569568 ${tabs}
570 ${conversationMenu(ctx, conversation, context, display, picker)}
569 ${conversationMenu(ctx, conversation, context, display)}
571570 </nav>`;
572571 }
573572
@@ -691,14 +690,12 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
691690 const crewRepo = paneRow?.name;
692691 const crew = crewRepo === undefined ? [] : crewOn(liveCrewRows(ctx, user), crewRepo);
693692 // The model picker (`talk_model.ts`), only where a connection offers a model.
694 const pickerAt = buildMode ? null : modelPicker(ctx, user, conversation.id);
695 const picker = pickerAt === null ? null : pickerAt();
693 const picker = modelPicker(ctx, user, conversation.id, { builds: buildMode, empty });
696694 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;
697 const dockPicker = pickerAt === null ? null : pickerAt("-dock");
698695 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>
699696 <div class="talk-side">${chats(ctx, conversation, showArchived, typed)}</div>
700697 <div class="talk" data-talk data-density="${display.density}" data-motion="${display.motion}" data-enter="${display.enter}" data-fold="${display.steps}" data-user="${user.id}" data-c="${conversation.id}" data-here="${here}" data-paged="${paged ? "1" : "0"}" data-running="${running && !paged ? "1" : "0"}">
701 ${hereBar(ctx, conversation, context, display, tabs, picker)}
698 ${hereBar(ctx, conversation, context, display, tabs)}
702699 ${pinnedPlan(conversation.id, conversationPlan(ctx.app.db, conversation.id))}
703700 ${turns.length === DEFAULT_PAGE && turns[0] !== undefined
704701 ? html`<p class="talk-more small"><a href="${here}?before=${turns[0].id}" data-earlier>Earlier</a></p>`
@@ -714,7 +711,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
714711 <div id="end"></div>
715712 <div class="talk-keys" data-keys role="region" aria-label="Keyboard shortcuts" hidden><dl>${TALK_KEYS.map((k) => html`<dt>${k.keys}</dt><dd>${k.does}</dd>`)}</dl></div>
716713 <div class="talk-base">
717 ${dockBar(ctx, conversation, context, display, tabs, dockPicker)}
714 ${dockBar(ctx, conversation, context, display, tabs)}
718715 <form class="talk-compose" id="compose" method="post" action="${buildMode ? "/talk/build" : editing === undefined ? here : `${here}/again/edit`}" ${editing === undefined ? null : html`data-edit`}${buildMode ? raw(" data-build") : null}>
719716 ${
720717 // The rare lines (archived, about) share one source line, so their empty slots cost the
@@ -722,7 +719,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
722719 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}
723720 ${chosen === undefined ? null : html`<input type="hidden" name="template" value="${chosen}" />`}
724721 ${confirmsDock(pendingConfirms)}
725 <p class="sr-only" role="status" data-confirms-said></p>
722 <p class="sr-only" role="status" data-confirms-said></p>${picker}
726723 <div class="talk-box">
727724 <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>
728725 <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>
@@ -742,7 +739,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
742739 <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>
743740 </form>
744741 </div>
745 ${picker === null ? null : modelForm(urlOf(conversation))}
742 ${picker === null || buildMode ? null : modelForm(urlOf(conversation))}
746743 <template id="talk-ico">${icon("copy")}${icon("check")}</template>
747744 <template id="talk-queued">${queuedHtml({ id: "", text: "" })}</template>
748745 </div>
src/web/pages/talk_client.ts +2 −4
@@ -122,8 +122,6 @@ body:has(.talk-page) .topbar { background: var(--bg); backdrop-filter: none; -we
122122 .talk-dock > .menu, .talk-dock > .talk-tabs { margin-inline-start: auto; }
123123 .talk-dock > .talk-tabs + .menu { margin-inline-start: 0; }
124124 .talk-dock .menu-panel { top: auto; bottom: calc(100% + 6px); transform-origin: bottom right; }
125 .talk-dock .talk-model { flex: none; padding: 4px; }
126 .talk-dock .talk-model select { min-width: 10rem; min-height: 2.75rem; }
127125 [data-split]:not([data-pane="chat"]) { display: flex; flex-direction: column; min-height: calc(100dvh - var(--topbar-h)); }
128126 [data-split]:not([data-pane="chat"]) > .talk { display: contents; }
129127 [data-split]:not([data-pane="chat"]) .talk-work { order: 1; }
@@ -260,8 +258,8 @@ html:has(.talk-page) { scroll-padding-bottom: 8rem; }
260258 .talk-steer { border-radius: 999px; }
261259 .talk-dictate[aria-pressed="true"] { background: var(--accent); color: var(--bg); }
262260 .talk-foot { margin: 6px 16px 0; }
263 .talk-model { flex: 0 1 7rem; min-width: 3.25rem; margin: 0; display: flex; align-items: center; gap: 4px; }
264 .talk-model select { width: 100%; min-width: 0; min-height: 2.5rem; font-size: 16px; text-overflow: ellipsis; }
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; }
265263 .talk-status { margin: 4px 16px 0; min-height: 1.25rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
266264 [data-answering] .talk-status { background: none; animation: none; color: transparent; }
267265 .talk-error { margin: 6px 4px 0; color: var(--danger); }
src/web/talk_build.ts +2 −1
@@ -109,7 +109,8 @@ export async function talkBuild(ctx: Ctx): Promise<Response> {
109109 if (typeof prompt !== "string" || prompt.trim() === "" || prompt.length > WORDS_MAX)
110110 return flashTo(ctx, "/talk", { tone: "danger", message: `Say what to build, up to ${WORDS_MAX} characters.` });
111111 const from = typeof template === "string" ? chosenTemplate(ctx.app.db, user, template) : undefined;
112 const started = await startBuild(ctx.app, user, { prompt, ...(from === undefined ? {} : { template: from }) });
112 const model = form.get("model");
113 const started = await startBuild(ctx.app, user, { prompt, ...(from === undefined ? {} : { template: from }), ...(typeof model === "string" ? { model } : {}) });
113114 if (!started.ok) return flashTo(ctx, "/talk", { tone: "danger", message: BUILD_WORDS[started.error] ?? "Not started." });
114115 const to = `/talk/${started.value.build.conversationId}`;
115116 return started.value.said === undefined ? redirect(to) : flashTo(ctx, to, { tone: started.value.said.kept ? "attn" : "danger", message: buildSaidWords(started.value.said) });
src/web/talk_model.ts +24 −22
@@ -1,43 +1,46 @@
11 /**
2 * Talk's model picker, in the conversation's head (`core/model_choice.ts`): a select of every model
3 * the person may use on a working connection, and the forge's own, saved for the conversation. A
4 * plain form post (`POST /talk/:id/model`), so it works with the script off; the script sends it on
5 * change. Absent when no connection offers a model, so a forge without connections looks as before.
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.
68 */
7 import { choiceLabel, choiceOf, choiceValue, FORGE_MODEL, offers, setChoice } from "../core/model_choice.ts";
8 import { connectionFor } from "../core/connections.ts";
9 import { choiceLabel, choiceOf, choiceValue, choiceWords, FORGE_MODEL, lostModelLine, notForTalk, offers, setChoice, startingChoice } from "../core/model_choice.ts";
910 import { anyTalkConnection } from "../core/subscriptions.ts";
1011 import { getConversation } from "../core/conversations.ts";
1112 import type { User } from "../core/users.ts";
1213 import type { Ctx } from "../http/context.ts";
1314 import { notFoundPage, signInFirst } from "./chrome.ts";
1415 import { field, readForm } from "./form.ts";
15 import { html, type Html } from "./html.ts";
16 import { html, raw, type Html } from "./html.ts";
1617 import { flashTo } from "./layout.ts";
1718
1819 /**
19 * The picker, in the conversation's head, its form outside it (`form=`), or null with nothing to
20 * offer.
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.
2122 */
22 export function modelPicker(ctx: Ctx, user: User, conversationId: string): ((idSuffix?: string) => Html) | null {
23 export function modelPicker(ctx: Ctx, user: User, conversationId: string, o: { readonly builds: boolean; readonly empty: boolean }): Html | null {
2324 // A forge with no connection Talk could run on draws no picker and reads nothing for it.
2425 if (!anyTalkConnection(ctx.app.db)) return null;
2526 const offered = offers(ctx.app.db, user);
26 const now = choiceOf(ctx.app.db, user.id, conversationId);
27 // A build makes a conversation of its own, which starts where any new one does.
28 const now = o.builds ? startingChoice(ctx.app.db, user) : choiceOf(ctx.app.db, user.id, conversationId);
29 const lost = o.empty && now === undefined ? lostModelLine(ctx.app.db, user) : undefined;
30 const note = lost === undefined ? null : html`<p class="talk-foot small muted">${lost}</p>`;
2731 // A conversation on a model that stopped answering keeps its picker: the way back to the forge's own.
28 if (offered.length === 0 && now === undefined) return null;
32 if (offered.length === 0 && now === undefined) return note;
2933 const current = now === undefined ? "" : choiceValue(now);
30 const listed = offered.some((o) => o.connection.id === now?.connectionId && o.models.includes(now.model));
34 const listed = offered.some((on) => on.connection.id === now?.connectionId && on.models.includes(now.model));
3135 // A choice whose connection stopped answering stays shown as the conversation's, never offered anew.
32 const stale = now === undefined || listed ? undefined : connectionFor(ctx.app.db, user.id, now.connectionId);
33 return (idSuffix = "") => html`<p class="talk-model small">
34 <label class="sr-only" for="talk-model-pick${idSuffix}">Model</label>
35 <select class="input" id="talk-model-pick${idSuffix}" name="model" form="talk-model" data-model-pick>
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')}>
3639 <option value=""${current === "" ? html` selected` : null}>${FORGE_MODEL}</option>
37 ${now !== undefined && !listed ? html`<option value="${current}" selected>${choiceLabel(stale ?? { name: "a removed connection" }, now.model)} (not answering)</option>` : null}
38 ${offered.map((o) => html`<optgroup label="${o.connection.name}">${o.models.map((m) => html`<option value="${choiceValue({ connectionId: o.connection.id, model: m })}"${choiceValue({ connectionId: o.connection.id, model: m }) === current ? html` selected` : null}>${choiceLabel(o.connection, m)}</option>`)}</optgroup>`)}
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>`)}
3942 </select>
40 <button type="submit" class="btn" data-size="sm" data-variant="ghost" form="talk-model" data-model-use>Use</button>
43 ${o.builds ? null : html`<button type="submit" class="btn" data-size="sm" data-variant="ghost" form="talk-model" data-model-use>Use</button>`}
4144 </p>`;
4245 }
4346
@@ -59,6 +62,5 @@ export async function talkModel(ctx: Ctx): Promise<Response> {
5962 if (now !== undefined && value === choiceValue(now)) return flashTo(ctx, back, { message: "Kept." });
6063 const set = setChoice(ctx.app.db, user, conversation.id, value);
6164 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." });
62 const on = set.value === undefined ? undefined : connectionFor(ctx.app.db, user.id, set.value.connectionId);
63 return flashTo(ctx, back, { tone: "success", message: on === undefined || set.value === undefined ? `${FORGE_MODEL} answers here.` : `${choiceLabel(on, set.value.model)} answers here.` });
65 return flashTo(ctx, back, { tone: "success", message: `${choiceWords(ctx.app.db, user.id, set.value)} answers here.` });
6466 }
test/helpers/talk-phone.ts +13 −11
@@ -5,7 +5,7 @@
55 *
66 * Talk on a phone (#16442, #16560), measured in a real Chromium at 360, 375 and 390 px with a
77 * finger:
8 * the head is one row (the list, the title, the model picker, the tabs, the menu and New) and
8 * the head is one row (the list, the title, the tabs, the menu and New) and
99 * nothing in it wraps; the composer does not move as the status line or the tool-call count change;
1010 * the chat list opens at its top on the newest chat; the "answering" line ends with the answer; a
1111 * long chat reads oldest to newest and opens on the newest; Earlier puts the older turns above in
@@ -96,7 +96,7 @@ beforeAll(async () => {
9696 promote(app.db, made.value);
9797 aliceId = made.value.id;
9898 token = createSession(app.db, aliceId).token;
99 // A connection that offers models, so the head carries the picker as it does for the owner.
99 // A connection that offers models, so the composer carries the picker as it does for the owner.
100100 const spark = saveConnection(app.db, app.config.dataDir, {
101101 name: "Spark",
102102 protocol: "openai",
@@ -234,11 +234,9 @@ export function widthTests(width: (typeof WIDTHS)[number]): void {
234234 const kids = [...dock.querySelectorAll(":scope > *")].filter(shown).map(box);
235235 const targets = [...dock.querySelectorAll(":scope > a, :scope > form button, :scope > .talk-tabs a, :scope > .menu > summary")].filter(shown).map(box);
236236 const headKids = [...head.querySelectorAll(":scope > *")].filter(shown).map((e) => String(e.className || e.tagName));
237 // The model picker is one tap into the menu, and fits above the dock.
238 dock.querySelector(".menu > summary").click();
239 await frame();
240 const sel = dock.querySelector(".talk-model select"), panel = dock.querySelector(".menu-panel");
241 const model = { sel: box(sel), panel: box(panel), tracked: shown(sel) };
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 };
242240 const ids = [...document.querySelectorAll("[id]")].map((e) => e.id), dup = ids.filter((x, i) => ids.indexOf(x) !== i);
243241 return JSON.stringify({ dock: { top: d.top, bottom: d.bottom, h: d.height }, kids, targets, headKids, model, dup, vh: innerHeight, sw: document.documentElement.scrollWidth });
244242 })()`,
@@ -264,11 +262,15 @@ export function widthTests(width: (typeof WIDTHS)[number]): void {
264262 }
265263 // The head keeps the title and nothing else.
266264 expect(s.headKids, seen).toEqual(["talk-title"]);
267 // The model: in the menu, in the lower half, 44 px tall, on screen, above the bar.
268 expect(s.model.tracked, seen).toBe(true);
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);
269269 expect(s.model.sel.h, seen).toBeGreaterThanOrEqual(44);
270 expect(s.model.sel.w, seen).toBeGreaterThanOrEqual(200);
270271 expect(s.model.sel.right, seen).toBeLessThanOrEqual(width);
271 expect(s.model.panel.bottom, seen).toBeLessThanOrEqual(s.dock.top + 8);
272 expect(s.model.line.top, seen).toBeGreaterThanOrEqual(s.dock.bottom - 1);
273 expect(s.model.line.bottom, seen).toBeLessThanOrEqual(s.model.boxTop + 1);
272274 expect(s.dup, seen).toEqual([]);
273275 },
274276 30_000,
@@ -405,7 +407,7 @@ export function widthTests(width: (typeof WIDTHS)[number]): void {
405407 const bar = document.querySelector(".topbar"), head = document.querySelector(".talk-head"), box = document.querySelector(".talk-box");
406408 const cs = getComputedStyle(bar);
407409 // A chat beside a live preview: the head carries Chat and Preview, the tallest thing in it.
408 head.querySelector(".talk-model")?.insertAdjacentHTML("afterend", '<nav class="seg talk-tabs" aria-label="Chat or preview"><a href="?pane=chat" aria-current="page">Chat</a><a href="?pane=preview">Preview</a></nav>');
410 head.querySelector(".talk-title").insertAdjacentHTML("afterend", '<nav class="seg talk-tabs" aria-label="Chat or preview"><a href="?pane=chat" aria-current="page">Chat</a><a href="?pane=preview">Preview</a></nav>');
409411 const kids = () => Math.min(...[...head.children].filter((e) => e.getBoundingClientRect().width > 0).map((e) => e.getBoundingClientRect().top));
410412 const at = (where) => ({ where, barBottom: bar.getBoundingClientRect().bottom, headTop: head.getBoundingClientRect().top, kidsTop: kids(), boxTop: box.getBoundingClientRect().top, boxBottom: box.getBoundingClientRect().bottom, vh: innerHeight });
411413 const end = at("end");
test/talk-model-choice.test.ts +96 −3
@@ -28,6 +28,7 @@ import {
2828 import { spendWords, turnSpend } from "../src/core/conversation_cost.ts";
2929 import {
3030 createConversation,
31 listConversations,
3132 listTurns,
3233 type Turn,
3334 } from "../src/core/conversations.ts";
@@ -36,6 +37,7 @@ import {
3637 busyOnLine,
3738 failedOnLine,
3839 GONE_LINE,
40 notForTalk,
3941 offers,
4042 setChoice,
4143 } from "../src/core/model_choice.ts";
@@ -381,11 +383,13 @@ describe("the page's picker", () => {
381383 await fetch(`${servers.url}/talk/${c}`, { headers: { cookie } })
382384 ).text();
383385 expect(page).toContain('id="talk-model-pick"');
384 // On a phone it is in the head's one row (#16442), not under the composer.
386 // It is the composer's own line, over its box, so it is in sight at every width.
385387 const from = page.indexOf('<header class="talk-head">');
386388 const head = page.slice(from, page.indexOf("</header>", from));
387 expect(head).toContain('id="talk-model-pick"');
388 expect(page.slice(page.indexOf('class="talk-compose"'))).not.toContain('id="talk-model-pick"');
389 expect(head).not.toContain("talk-model");
390 const compose = page.slice(page.indexOf('class="talk-compose"'));
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>/);
389393 expect(page).toContain(
390394 '<form id="talk-model" method="post" action="/talk/' +
391395 c +
@@ -439,6 +443,95 @@ describe("the page's picker", () => {
439443 });
440444 });
441445
446 describe("remembered, and in the build composer", () => {
447 const spoken = (id: string) => choiceOf(app.db, keeper.id, id)?.model;
448
449 test("a new conversation starts on the last choice; a choice changes no other conversation", () => {
450 const first = conversation(keeper);
451 expect(setChoice(app.db, keeper, first, `${spark().id} canned/large`).ok).toBe(true);
452 const second = conversation(keeper);
453 expect(spoken(second)).toBe("canned/large");
454 expect(setChoice(app.db, keeper, second, `${spark().id} canned/small`).ok).toBe(true);
455 expect(spoken(first)).toBe("canned/large");
456 // Bob's are his own, and the forge's own is a choice that is remembered too.
457 expect(choiceOf(app.db, bob.id, conversation(bob))).toBeUndefined();
458 expect(setChoice(app.db, keeper, second, "").ok).toBe(true);
459 expect(spoken(conversation(keeper))).toBeUndefined();
460 expect(spoken(first)).toBe("canned/large");
461 });
462
463 test("a last model that stopped working: the new conversation starts on the forge's and says so", async () => {
464 const cookie = `forge_session=${createSession(app.db, keeper.id).token}`;
465 expect(setChoice(app.db, keeper, conversation(keeper), `${spark().id} canned/large`).ok).toBe(true);
466 recordTest(app.db, spark().id, { working: false, said: "it answered 500" });
467 try {
468 const c = conversation(keeper);
469 expect(spoken(c)).toBeUndefined();
470 const page = await (await fetch(`${servers.url}/talk/${c}`, { headers: { cookie } })).text();
471 expect(page).toContain("Your last model, canned/large, is not offered now, so this starts on the forge&#39;s model.");
472 } finally {
473 recordTest(app.db, spark().id, { working: true, said: "2 models listed" });
474 }
475 expect(spoken(conversation(keeper))).toBe("canned/large");
476 expect(setChoice(app.db, keeper, conversation(keeper), "").ok).toBe(true);
477 });
478
479 test("the build composer's picker is a field of its own form, and the first turn runs on it, by form and by API", async () => {
480 const cookie = `forge_session=${createSession(app.db, keeper.id).token}`;
481 const page = await (await fetch(`${servers.url}/talk/${conversation(keeper)}?build=1`, { headers: { cookie } })).text();
482 const form = page.slice(page.indexOf('action="/talk/build"'), page.indexOf("</form>", page.indexOf('class="talk-box"')));
483 expect(form).toContain('id="talk-model-pick" name="model">');
484 expect(page).not.toContain('form="talk-model"');
485 const value = `${spark().id} canned/large`;
486 const heads = { cookie, origin: servers.url };
487 const model = (id: string) => app.db.query<{ model: string }, [string]>("SELECT model FROM conversation_run WHERE conversation_id = ?1 ORDER BY started_at LIMIT 1").get(id)?.model;
488 const sent = await fetch(`${servers.url}/talk/build`, { method: "POST", redirect: "manual", headers: heads, body: new URLSearchParams({ prompt: "a tea timer", model: value }) });
489 const byForm = /^\/talk\/([0-9a-z]+)$/.exec(sent.headers.get("location") ?? "")?.[1] ?? "";
490 expect(spoken(byForm)).toBe("canned/large");
491 const api = (body: object) => fetch(`${servers.url}/api/v1/builds`, { method: "POST", headers: { ...heads, "content-type": "application/json" }, body: JSON.stringify(body) });
492 const made = await api({ prompt: "a plant diary", model: `${spark().id} canned/small` });
493 expect(made.status).toBe(201);
494 const byApi = ((await made.json()) as { conversation: string }).conversation;
495 expect(spoken(byApi)).toBe("canned/small");
496 expect(spoken(byForm)).toBe("canned/large");
497 const held = listConversations(app.db, keeper.id).length;
498 const refused = await api({ prompt: "a third thing", model: `${spark().id} canned/huge` });
499 expect([refused.status, ((await refused.json()) as { error: string }).error]).toEqual([422, "model_not_offered"]);
500 expect((await api({ prompt: "a third thing", model: 7 })).status).toBe(422);
501 expect(listConversations(app.db, keeper.id).length).toBe(held);
502 // This forge runs no turns by itself, so the build's first turn is the one said here.
503 for (const [id, name] of [[byForm, "canned/large"], [byApi, "canned/small"]] as const) {
504 answers = [() => reply("On it.")];
505 await turn(keeper, id, "go on");
506 expect(model(id)).toBe(name);
507 }
508 expect(defaults).toHaveLength(0);
509 expect(setChoice(app.db, keeper, conversation(keeper), "").ok).toBe(true);
510 });
511
512 test("a model that cannot hold a conversation is never offered, ticked or not, and says why", () => {
513 const made = saveConnection(app.db, app.config.dataDir, {
514 name: "Mixed",
515 protocol: "openai",
516 base: "http://127.0.0.1:9/v1",
517 key: "",
518 scope: "forge",
519 userId: keeper.id,
520 models: [{ id: "subq-snap-1" }, { id: "lab/subq-snap-2" }, { id: "subq-1" }],
521 said: "3 models listed",
522 });
523 if (!made.ok) throw new Error(made.error);
524 try {
525 expect(offers(app.db, keeper).find((o) => o.connection.name === "Mixed")?.models).toEqual(["subq-1"]);
526 expect(setChoice(app.db, keeper, conversation(keeper), `${made.value.id} subq-snap-1`).ok).toBe(false);
527 expect(notForTalk("subq-snap-1")).toContain("cannot hold a conversation");
528 expect(notForTalk("canned/large")).toBeUndefined();
529 } finally {
530 removeConnection(app.db, keeper, made.value.id);
531 }
532 });
533 });
534
442535 describe("the picker after a fall", () => {
443536 test("a conversation whose model stopped answering keeps its picker: that model, marked, and the forge's own", async () => {
444537 const c = conversation(keeper);
test/talk-phone.test.ts +7 −5
@@ -1,7 +1,7 @@
11 /**
22 * Talk on a phone (#16442, #16560), measured in a real Chromium at 360, 375 and 390 px with a
33 * finger:
4 * the head is one row (the list, the title, the model picker, the tabs, the menu and New) and
4 * the head is one row (the list, the title, the tabs, the menu and New) and
55 * nothing in it wraps; the composer does not move as the status line or the tool-call count change;
66 * the chat list opens at its top on the newest chat; the "answering" line ends with the answer; a
77 * long chat reads oldest to newest and opens on the newest; Earlier puts the older turns above in
@@ -30,14 +30,16 @@ test("without a browser: the conversation's controls are in a dock beside the co
3030 expect(dock).toContain('method="post" action="/talk/new"');
3131 expect(dock).toContain(`action="/talk/${shortId}/rename"`);
3232 expect(dock).toContain(`/talk/${shortId}.md`);
33 expect(dock).toContain('id="talk-model-pick-dock"');
34 // The dock and the composer share the sticky foot, the dock first; the head's own picker keeps
35 // its id.
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.
35 expect(dock).not.toContain("talk-model");
3636 const foot = page.indexOf('class="talk-base"');
3737 expect(foot).toBeGreaterThan(-1);
3838 expect(page.indexOf('class="talk-dock"')).toBeGreaterThan(foot);
3939 expect(page.indexOf('class="talk-dock"')).toBeLessThan(page.indexOf('class="talk-compose"'));
40 expect(page).toContain('id="talk-model-pick"');
40 const compose = page.slice(page.indexOf('class="talk-compose"'));
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"'));
4143 const { talkCss } = await import("../src/web/pages/talk_client.ts");
4244 expect(talkCss).toContain(".talk-head > :not(.talk-title) { display: none; }");
4345 expect(talkCss).toMatch(/@media \(min-width: 56\.25rem\) \{ \.talk-dock \{ display: none; \} \}/);

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs