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

Pick the model in Talk: a model line under the box, kept per conversation (#16428) #16473

opened this

Check · Review · Land · Live — No review yet. Next: reviewer, no review yet.

Ready to land

talk-connections-b → main 1 commit

Review

Sign in to review this change.
19 files changed +934 −30
docs/design/areas/talk.md +1
@@ -97,6 +97,7 @@ The window is the thread's one scroller; the list and a side pane are sticky col
9797 - `.talk-steer` — the one secondary control, shown while an answer runs and words are typed: send them now.
9898 - `.talk-hint` — "Enter sends", only where there is a mouse.
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.
100101 - `.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.
101102 - `.talk-fold-list` — the steps inside it, on a hairline at the start edge.
102103 - `.talk-live` — the block being written; its running line shimmers (plain under reduced motion).
docs/features/connections.md +2 −2
@@ -68,5 +68,5 @@ and `x` removes one with its name typed exactly.
6868 ## What is unchanged
6969
7070 Every subscription from before connections is the Anthropic connection it was: the migration only adds
71 columns, and a crew run still picks only Anthropic accounts. Choosing a connection's model in Talk is
72 the next step.
71 columns, and a crew run still picks only Anthropic accounts. Talk's model picker
72 (docs/features/talk.md, "The model picker") offers each working connection's models.
docs/features/talk.md +14
@@ -128,6 +128,20 @@ Prior art read: Vercel AI Elements (Apache-2.0 React on shadcn; anatomy and beha
128128
129129 **The terminal** (`ssh <forge> talk <words>`, `forge talk`) sends one line and prints the answer; it has no log, so who/when, copy, tool cards, starters and the jump button do not apply to it. `forge talk` prints a thought as one `thinking:` line, then the reply, the steps line and the links as paths (the API's agent turns carry `work: {steps, links}`). The steps line says "opened" for a read issue or pull and "changed" for a tool that writes one (`CHANGES` in `core/talk_work.ts`, held to the MCP tools' `writes` by a test); numbers carry their repo when a turn touched more than one. A reply first on an older page, or first in a stream batch, reads its calls from the turns before the page (`worksOf`), so it says the same on every door. The conversation's whole history is read through `GET /api/v1/conversation/turns`, where every turn carries its role and time.
130130
131 ## The model picker
132
133 When a connection on Connect your AI offers models (docs/features/connections.md), the composer has a
134 Model line: the forge's model, then each model a working connection offers, by connection. The choice
135 is the conversation's own and is kept with it; the line under each reply names the model it ran on
136 (and its cost when the price table knows the model, never $0). It is a plain form, so it works with
137 the script off; with the script it is sent as soon as it changes. In the terminal, `m` in an open
138 conversation is the same picker.
139
140 Only working connections are offered: a person's own, and the forge's to an admin or to a person it
141 is granted to. A turn whose model does not answer says so in one sentence, with Retry and the picker,
142 and nothing else answers for it; its connection is then not offered until a test or a turn on it
143 passes. A conversation whose connection was removed runs nothing and says to pick another model.
144
131145 ## Every link in a reply clicks
132146
133147 A reply is drawn by the README renderer and then, for Talk alone, by `linkTalk` (`src/text/talk_link_words.ts`): a Markdown link stays a link only if it goes somewhere (an `http(s)` address with no user part, or a path rooted on this forge: one leading slash, never `//` or `/\\`, no encoded control character), and a relative path, which would resolve against the conversation's own address, is set back to its words. A bare `http(s)` address in the words is a link, its trailing punctuation left out. A forge path written as words (`owner/repo`, `owner/repo#12`, `owner/repo/pulls/4`, `owner/repo/src/a.ts`) is a link when you may read that repository and, for a number, when it is there; anything else stays words, so a private repository's existence is never shown. Each repository a page of replies names is read once. An address of one of this forge's apps you may read goes to it while it runs, and to its page on the forge, said "not running yet", while it does not. READMEs keep their rules (no bare-address or path links); both now refuse a `/\\host` link, which a browser reads as `//host`.
src/core/conversation_cost.ts +17 −6
@@ -16,10 +16,17 @@ export const FULL_AT = 0.8;
1616 export interface Spend {
1717 readonly usd: number;
1818 readonly stopped: boolean;
19 /** The model the conversation chose for the run (`core/model_choice.ts`); absent for the forge's own. */
20 readonly model?: string | undefined;
1921 }
2022
2123 /** The words under a reply, one wording for the page, its stream and the terminal. */
22 export const spendWords = (spend: Spend): string => (spend.stopped ? `Stopped: ${dollars(spend.usd)} spent so far` : `${dollars(spend.usd)} this turn`);
24 export const spendWords = (spend: Spend): string => {
25 // A chosen model the price table does not know has no cost to state: its name alone, never $0.
26 const on = spend.model === undefined ? "" : spend.usd > 0 ? ` · ${spend.model}` : spend.model;
27 if (spend.usd <= 0) return spend.stopped ? `Stopped · ${on}` : `${on} this turn`;
28 return spend.stopped ? `Stopped: ${dollars(spend.usd)} spent so far${on}` : `${dollars(spend.usd)} this turn${on}`;
29 };
2330
2431 /**
2532 * The spend of the run that wrote each agent turn, by turn id: on the last agent turn inside the
@@ -27,23 +34,27 @@ export const spendWords = (spend: Spend): string => (spend.stopped ? `Stopped: $
2734 */
2835 export function turnSpend(db: Database, conversationId: string): Map<string, Spend> {
2936 const rows = db
30 .query<{ id: string | null; cost: number; stopped: number }, [string]>(
37 .query<{ id: string | null; cost: number; stopped: number; model: string }, [string]>(
3138 `SELECT (SELECT t.id FROM conversation_turn t
3239 WHERE t.conversation_id = r.conversation_id AND t.role = 'agent'
3340 AND t.created_at >= r.started_at AND t.created_at <= r.finished_at
34 ORDER BY t.rowid DESC LIMIT 1) AS id, r.cost_usd AS cost, r.stopped AS stopped
41 ORDER BY t.rowid DESC LIMIT 1) AS id, r.cost_usd AS cost, r.stopped AS stopped, r.model AS model
3542 FROM conversation_run r
36 WHERE r.conversation_id = ?1 AND r.finished_at IS NOT NULL AND r.cost_usd > 0`,
43 WHERE r.conversation_id = ?1 AND r.finished_at IS NOT NULL AND (r.cost_usd > 0 OR r.model <> '')`,
3744 )
3845 .all(conversationId);
3946 const spent = new Map<string, Spend>();
40 for (const r of rows) if (r.id !== null) spent.set(r.id, { usd: (spent.get(r.id)?.usd ?? 0) + r.cost, stopped: (spent.get(r.id)?.stopped ?? false) || r.stopped === 1 });
47 for (const r of rows)
48 if (r.id !== null) {
49 const model = r.model === "" ? spent.get(r.id)?.model : r.model;
50 spent.set(r.id, { usd: (spent.get(r.id)?.usd ?? 0) + r.cost, stopped: (spent.get(r.id)?.stopped ?? false) || r.stopped === 1, ...(model === undefined ? {} : { model }) });
51 }
4152 return spent;
4253 }
4354
4455 /** The dollars of the run that wrote each agent turn, by turn id. */
4556 export function turnCosts(db: Database, conversationId: string): Map<string, number> {
46 return new Map([...turnSpend(db, conversationId)].map(([id, s]) => [id, s.usd]));
57 return new Map([...turnSpend(db, conversationId)].filter(([, s]) => s.usd > 0).map(([id, s]) => [id, s.usd]));
4758 }
4859
4960 /**
src/core/migration-pins/20261125183000-talk-model-choice.pin added +1
@@ -0,0 +1,1 @@
1 7f3d382ed64270db73a597b5546438b95be01277038e536158929954d9cbc29c
src/core/migrations/20261125183000-talk-model-choice.ts added +8
@@ -0,0 +1,8 @@
1 // Talk's model picker (core/model_choice.ts): the connection and model a conversation answers on,
2 // chosen in its composer ('' for the forge's own, as every conversation before this), and the model
3 // each turn ran on, for the line under its reply. Additive.
4 export default `
5 ALTER TABLE conversation ADD COLUMN connection_id TEXT NOT NULL DEFAULT '';
6 ALTER TABLE conversation ADD COLUMN model TEXT NOT NULL DEFAULT '';
7 ALTER TABLE conversation_run ADD COLUMN model TEXT NOT NULL DEFAULT '';
8 `;
src/core/model_choice.ts added +164
@@ -0,0 +1,164 @@
1 /**
2 * Talk's model picker: which connection and model a conversation answers on (`core/connections.ts`).
3 * Empty is the forge's own, as every conversation before the picker. The picker offers a model only
4 * on a connection whose last test passed, that speaks the OpenAI-compatible protocol Talk drives, and
5 * that the person may use: their own, or the forge's when they are an admin or it is granted to them.
6 * Its models are the ones chosen on Connect your AI, else every one its test listed. A stored choice
7 * whose connection fails later is not quietly swapped: the turn says so (`crew/conversation.ts`).
8 */
9 import type { Database } from "bun:sqlite";
10 import { err, ok, type Result } from "../kernel/result.ts";
11 import {
12 connectionFor,
13 listConnections,
14 type Connection,
15 } from "./connections.ts";
16 import { EVERYONE } from "./subscriptions.ts";
17
18 /** At most this many models of one connection are offered. */
19 export const OFFERED_MAX = 100;
20
21 export interface Offer {
22 readonly connection: Connection;
23 readonly models: readonly string[];
24 }
25
26 /** A conversation's choice: a connection and one of its models. */
27 export interface Choice {
28 readonly connectionId: string;
29 readonly model: string;
30 }
31
32 /** The value a picker's option carries: the connection's id, a space, the model. */
33 export const choiceValue = (c: Choice): string =>
34 `${c.connectionId} ${c.model}`;
35
36 /** What the picker, the turn's line and the terminal call a choice. */
37 export const choiceLabel = (
38 connection: Pick<Connection, "name">,
39 model: string,
40 ): string => `${model} · ${connection.name}`;
41
42 /** What the picker calls the forge's own, the choice of every conversation that made none. */
43 export const FORGE_MODEL = "The forge's model";
44
45 const granted = (db: Database, userId: string, connectionId: string): boolean =>
46 db
47 .query<
48 { n: number },
49 [string, string, string]
50 >("SELECT COUNT(*) AS n FROM subscription_grant WHERE scope_id = ?1 AND agent_id = ?2 AND subscription_id = ?3")
51 .get(userId, EVERYONE, connectionId)!.n > 0;
52
53 /** Whether a person may run Talk on a connection at all, whatever its last test said. */
54 export function mayUse(
55 db: Database,
56 user: { readonly id: string; readonly isAdmin: boolean },
57 c: Connection,
58 ): boolean {
59 return (
60 c.protocol === "openai" &&
61 (c.scope === "yours" || user.isAdmin || granted(db, user.id, c.id))
62 );
63 }
64
65 /** Every connection and model the picker offers this person: usable, and working at its last test. */
66 export function offers(
67 db: Database,
68 user: { readonly id: string; readonly isAdmin: boolean },
69 ): Offer[] {
70 return listConnections(db, user.id)
71 .filter((c) => c.working === true && mayUse(db, user, c))
72 .map((c) => ({
73 connection: c,
74 models: (c.chosen.length > 0
75 ? c.chosen
76 : c.models.map((m) => m.id)
77 ).slice(0, OFFERED_MAX),
78 }))
79 .filter((o) => o.models.length > 0);
80 }
81
82 /** The conversation's choice, or undefined for the forge's own. */
83 export function choiceOf(
84 db: Database,
85 userId: string,
86 conversationId: string,
87 ): Choice | undefined {
88 const row = db
89 .query<
90 { connection_id: string; model: string },
91 [string, string]
92 >("SELECT connection_id, model FROM conversation WHERE id = ?1 AND user_id = ?2")
93 .get(conversationId, userId);
94 return row === null || row.connection_id === ""
95 ? undefined
96 : { connectionId: row.connection_id, model: row.model };
97 }
98
99 /**
100 * 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.
102 */
103 export function setChoice(
104 db: Database,
105 user: { readonly id: string; readonly isAdmin: boolean },
106 conversationId: string,
107 value: string,
108 ): Result<Choice | undefined, "not_offered" | "not_found"> {
109 const exists =
110 db
111 .query<
112 { n: number },
113 [string, string]
114 >("SELECT COUNT(*) AS n FROM conversation WHERE id = ?1 AND user_id = ?2")
115 .get(conversationId, user.id)!.n > 0;
116 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");
137 db.query(
138 "UPDATE conversation SET connection_id = ?2, model = ?3 WHERE id = ?1",
139 ).run(conversationId, choice.connectionId, choice.model);
140 return ok(choice);
141 }
142
143 /**
144 * What a turn on a choice runs on: the connection, when the person may still use it; undefined
145 * when it was removed or is no longer theirs to use (the turn then says so and runs nothing).
146 */
147 export function choiceConnection(
148 db: Database,
149 user: { readonly id: string; readonly isAdmin: boolean },
150 choice: Choice,
151 ): Connection | undefined {
152 const c = connectionFor(db, user.id, choice.connectionId);
153 return c === undefined || !mayUse(db, user, c) || c.base === null
154 ? undefined
155 : c;
156 }
157
158 /** The one sentence a turn says when its model's connection did not answer: never a fallback. */
159 export const failedOnLine = (name: string, model: string): string =>
160 `${model} on ${name} did not answer, so nothing else answered for it: Retry, or pick another model below.`;
161
162 /** The one sentence a turn says when its model is no longer offered. */
163 export const GONE_LINE =
164 "This conversation's model is no longer offered, so nothing answered: pick another model below.";
src/crew/agent_runner.ts +6
@@ -130,6 +130,12 @@ export interface RunAccount {
130130 readonly token: string;
131131 /** The gateway's base as the run reaches it; absent for an account on its provider itself. */
132132 readonly base?: string | undefined;
133 /**
134 * A connection's own (`core/connections.ts`): `base` is the OpenAI-compatible base itself, its
135 * calls go to `<base>/chat/completions`, and `guarded` sends them through the outbound guard (a
136 * person's own: public https, the vetted address pinned, no redirect).
137 */
138 readonly connection?: { readonly guarded: boolean; readonly effort?: string | undefined } | undefined;
133139 }
134140
135141 export interface Spent {
src/crew/conversation.ts +63 −15
@@ -33,7 +33,13 @@ import { answeredNote, answerFor, FOLLOW_UP, type Outcome } from "./conversation
3333 import { thinkingOf } from "../core/talk_work.ts";
3434 import { contextOf } from "../core/conversation_cost.ts";
3535 import { memoryBrief } from "../core/talk_memory.ts";
36 import { PLATFORM, pickSubscription, type Pick } from "../core/subscriptions.ts";
36 import { getSubscription, PLATFORM, pickSubscription, type Pick } from "../core/subscriptions.ts";
37 import { connectionKey, recordTest, type Connection } from "../core/connections.ts";
38 import { choiceConnection, choiceOf, failedOnLine, GONE_LINE } from "../core/model_choice.ts";
39 import { openaiRunner } from "./openai_runner.ts";
40 import { modelHostBlocked } from "../actions/blocked_words.ts";
41 import { blockedText } from "../kernel/blocked.ts";
42 import { GateRefusedError } from "../kernel/outbound.ts";
3743 import { getUserById } from "../core/users.ts";
3844 import { mintViaToken, VIA_TOKEN_MAX_MS } from "../core/via_token.ts";
3945 import { id } from "../kernel/id.ts";
@@ -625,6 +631,17 @@ export function heldLine(why: { readonly code: HeldRefusal; readonly until?: str
625631 }
626632 }
627633
634 /**
635 * A chosen connection as the account a turn spends: its key and base, and on a budgeted account of
636 * the forge's, the rest of its budget as the turn's cap.
637 */
638 function connectionPick(app: App, on: Connection, key: string): Pick {
639 const subscription = getSubscription(app.db, on.id)!;
640 const left = app.db.query<{ budget_usd: number | null; spent_usd: number }, [string]>("SELECT budget_usd, spent_usd FROM subscription WHERE id = ?1").get(on.id);
641 const cap = left?.budget_usd == null ? undefined : Math.max(0, left.budget_usd - left.spent_usd);
642 return { kind: "ready", subscription, envName: "OPENAI_API_KEY", token: key, apiBase: on.base, ...(cap === undefined || on.scope === "yours" ? {} : { capUsd: cap }) };
643 }
644
628645 /** What a run that did not end well says to the person: what happened, never the raw error. */
629646 export function failureLine(reason: string): string {
630647 if (reason === "timeout") return "That took longer than a turn may, so I stopped.";
@@ -653,13 +670,27 @@ function begin(
653670 const userId = conversation.userId;
654671 const runId = id();
655672 const now = new Date();
656 // The person's account, as any run's: a grant to them, else the forge's own for an admin.
657 const picked = pickSubscription(app.db, app.config.dataDir, { repoId: "", ownerId: userId, agentId: "" }, now, {
658 runId,
659 usd: options.budgetUsd,
660 });
673 // The model the conversation chose (`core/model_choice.ts`): its connection and nothing else. One
674 // that was removed, or is no longer the person's to use, runs nothing and says so (`gone`).
675 const choice = choiceOf(app.db, userId, conversation.id);
676 const person = choice === undefined ? undefined : getUserById(app.db, userId);
677 const chosenOn = choice === undefined || person === undefined ? undefined : choiceConnection(app.db, person, choice);
678 const chosenKey = chosenOn === undefined ? undefined : connectionKey(app.db, app.config.dataDir, chosenOn.id);
679 const on = chosenKey === undefined ? undefined : chosenOn;
680 const gone = choice !== undefined && on === undefined;
681 // The person's account, as any run's: a grant to them, else the forge's own for an admin. A chosen
682 // connection is its own account: a person's own spends their key; the forge's keeps its budgets.
683 const picked: Pick =
684 on !== undefined
685 ? connectionPick(app, on, chosenKey!)
686 : gone
687 ? { kind: "none" }
688 : pickSubscription(app.db, app.config.dataDir, { repoId: "", ownerId: userId, agentId: "" }, now, {
689 runId,
690 usd: options.budgetUsd,
691 });
661692 if (picked.kind === "resting") return err({ code: "resting", until: picked.until });
662 const spend = turnBudget(app, picked, userId, options.budgetUsd, now);
693 const spend = gone || on?.scope === "yours" ? { ok: true as const, budget: options.budgetUsd } : turnBudget(app, picked, userId, options.budgetUsd, now);
663694 if (!spend.ok) return err({ code: spend.refusal, ...(spend.refusal === "resting" ? { said: spend.said } : {}) });
664695 const budget = spend.budget;
665696 const subscriptionId = picked.kind === "ready" ? picked.subscription.id : PLATFORM;
@@ -683,6 +714,8 @@ function begin(
683714 "INSERT INTO conversation_run (id, conversation_id, user_id, subscription_id, prompt, resumes, session_id, started_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8)",
684715 )
685716 .run(runId, conversation.id, userId, subscriptionId, prompt, resumes, resumeSession ?? "", now.toISOString());
717 // The model the turn ran on, for the line under its reply.
718 if (on !== undefined) app.db.query("UPDATE conversation_run SET model = ?2 WHERE id = ?1").run(runId, choice!.model);
686719 live.set(conversation.id, runId);
687720 const stopper = new AbortController();
688721 stoppers.set(conversation.id, { runId, userId, stop: () => stopper.abort() });
@@ -715,30 +748,32 @@ function begin(
715748 try {
716749 const cwd = turnDir(app.config.dataDir);
717750 const configDir = sessionsDir(app.config.dataDir, options.configDir);
718 const modelEnv = credentialEnv(picked, app.config.dataDir);
719 holdModelCredential(modelHold, modelEnv);
751 // A connection's key goes to its runner as its account, never into the turn's environment.
752 const modelEnv = on !== undefined || gone ? {} : credentialEnv(picked, app.config.dataDir);
753 holdModelCredential(modelHold, on !== undefined && chosenKey !== "" ? { OPENAI_API_KEY: chosenKey! } : modelEnv);
720754 // A stored session that cannot be resumed (its file went with a release,
721755 // or it was made under another cwd) is not the person's to see: that one
722756 // message starts fresh, once, with the stored turns as its context.
723757 let fresh = prompt;
724758 // A runner that keeps no session (an OpenAI-compatible endpoint) is handed the stored turns
725759 // with every message instead of a session to resume.
726 const keepsSession = currentRunner().resumes === true;
727 for (let session = keepsSession ? resumeSession : undefined; ; session = undefined) {
760 const keepsSession = on === undefined && currentRunner().resumes === true;
761 for (let session = keepsSession ? resumeSession : undefined; !gone; session = undefined) {
728762 let named = false;
729763 liveReset(app.db, conversation.id);
730764 if (session !== undefined) appendRunLog(app.config.dataDir, runId, `resuming session ${session}`);
731765 // Whatever the run does (ends, throws, is stopped), the calls it made are stored.
732 outcome = await runAgent({
766 // A chosen connection runs on the OpenAI-compatible runner, whatever the forge's default is.
767 outcome = await (on !== undefined ? openaiRunner.run : runAgent)({
733768 binary: options.binary,
734769 cwd,
735770 // Attachments go with the message itself, never with a resume.
736771 prompt: resumes > 0 && session !== undefined ? RESUME_PROMPT : told.text + lead + fresh + attached.text,
737772 images: resumes > 0 && session !== undefined ? [] : attached.images,
738773 appendSystemPrompt: [CONVERSATION_BRIEF, memoryBrief(app.db, userId)].filter((p) => p !== "").join(" "),
739 model: options.model,
774 model: on !== undefined ? choice!.model : options.model,
740775 budgetUsd: budget,
741 account: runAccount(picked, modelEnv),
776 account: on !== undefined ? { token: chosenKey!, base: on.base!, connection: { guarded: on.scope === "yours", effort: on.effort } } : runAccount(picked, modelEnv),
742777 resume: session,
743778 ...(keepsSession ? {} : { history: priorTurns(app, conversation, prompt) }),
744779 // The session's running total before this turn, so the turn is charged its own cost
@@ -851,7 +886,19 @@ function begin(
851886 for (const turn of streamed) if (raw(turn.text)) removeTurn(app.db, userId, conversation.id, turn.id);
852887 appendTurn(app.db, userId, conversation.id, { role: "agent", text, failed: true });
853888 };
854 if (toolless.signal.aborted) couldNot(NO_TOOLS_LINE, () => true);
889 // A chosen model that did not answer says so, with Retry and the picker: nothing else answers
890 // for it. Its connection is marked not working, so the picker stops offering it until a test
891 // or a turn on it passes.
892 const fellOver = on !== undefined && !toolless.signal.aborted && (outcome === undefined || (!outcome.ok && (outcome.reason === "error" || outcome.reason === "rate_limited")));
893 if (gone) couldNot(GONE_LINE, () => false);
894 else if (fellOver) {
895 // The forge's own egress gate refused its host (its egress changed since the test): said as
896 // the add form says it, with the hosts it reaches and the ask to allow this one.
897 const gated = new URL(on.base!).hostname;
898 const refusedByGate = (outcome?.result ?? "").includes(new GateRefusedError(gated).message);
899 couldNot(refusedByGate ? blockedText(modelHostBlocked(app, person, gated)) : failedOnLine(on.name, choice!.model), (said) => said === outcome?.result);
900 recordTest(app.db, on.id, { working: false, said: `A Talk turn on ${choice!.model} got no answer: ${(outcome?.result ?? "").slice(0, 160)}` });
901 } else if (toolless.signal.aborted) couldNot(NO_TOOLS_LINE, () => true);
855902 else if (outcome === undefined) couldNot(failureLine("error"), () => false);
856903 else if (isRateLimited(outcome)) {
857904 const first = outcome.result.split("\n").find((l) => l.trim() !== "")?.trim() ?? "";
@@ -861,6 +908,7 @@ function begin(
861908 else if (answer.trim() === "" && lastText === "") couldNot(failureLine("error"), () => false);
862909 // Where the line went (#13942): each issue a tell opened, on every outcome; the plain word
863910 // that none was only when the turn answered.
911 if (on !== undefined && outcome?.ok === true && on.working === false) recordTest(app.db, on.id, { working: true, said: `A Talk turn on ${choice!.model} answered after its last test failed.` });
864912 for (const text of filedTurns(app.db, via, prompt, outcome?.ok === true && !toolless.signal.aborted)) put("tool", text);
865913 app.db
866914 .query(
src/crew/openai_runner.ts +14 −4
@@ -36,6 +36,7 @@ import { closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readd
3636 import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3737 import { BUDGET_REACHED, type AgentDetection, type AgentOutcome, type AgentRun, type AgentRunner, type HistoryTurn } from "./agent_runner.ts";
3838 import { openMcp } from "./openai_mcp.ts";
39 import { outboundFetch, type OutboundOptions } from "../kernel/outbound.ts";
3940 import { costOf, priceOf } from "./openai_price.ts";
4041 import { stopGroup, type GroupStop } from "./stop_group.ts";
4142 import { childEnv } from "../apps/process.ts";
@@ -391,7 +392,10 @@ export function settings(run: AgentRun, config: Record<string, string | undefine
391392 const base = baseUrl(() => account.base ?? "");
392393 if (base === "") return { refused: NO_GATEWAY };
393394 if (model === "") return { refused: "a model name is required" };
394 return { base: `${base}/v1`, key: account.token, model, ...effort };
395 // A connection's base is the OpenAI-compatible one itself; a gateway's is its root.
396 // A connection's own effort (`core/connections.ts`) is its own, over the operator's.
397 const own = account.connection?.effort ?? "";
398 return { base: account.connection === undefined ? `${base}/v1` : base, key: account.token, model, ...(own === "" ? effort : { reasoningEffort: own }) };
395399 }
396400 const base = baseUrl(get);
397401 if (base === "" || model === "") return { refused: "OPENAI_BASE_URL (http/https) and a model name are required" };
@@ -434,7 +438,11 @@ export function callAsText(text: string): boolean {
434438 }
435439 }
436440
437 export async function runOpenAI(run: AgentRun, config: Record<string, string | undefined> = process.env): Promise<AgentOutcome> {
441 /**
442 * One run on an OpenAI-compatible endpoint. `guard` is the outbound guard's options for a person's
443 * own connection (a test hands it a resolver); the forge's own endpoints never read it.
444 */
445 export async function runOpenAI(run: AgentRun, config: Record<string, string | undefined> = process.env, guard: OutboundOptions = {}): Promise<AgentOutcome> {
438446 const sessionId = run.resume ?? crypto.randomUUID();
439447 let tokensIn = 0, tokensOut = 0, turns = 0, contextTokens = 0, costUsd = 0, result = "";
440448 const done = (ok: boolean, reason: string): AgentOutcome => ({
@@ -467,13 +475,15 @@ export async function runOpenAI(run: AgentRun, config: Record<string, string | u
467475 const root = link === undefined ? realpathSync(run.cwd) : "";
468476 const tools = link?.tools ?? TOOL_SPECS;
469477 while (turns < MAX_TURNS) {
470 const res = await fetch(`${cfg.base}/chat/completions`, {
478 const ask: RequestInit = {
471479 method: "POST",
472480 headers: { "content-type": "application/json", ...(cfg.key ? { authorization: `Bearer ${cfg.key}` } : {}) },
473481 body: JSON.stringify({ model: cfg.model, messages, tools, stream: true, stream_options: { include_usage: true }, ...(cfg.reasoningEffort === undefined ? {} : { reasoning_effort: cfg.reasoningEffort }) }),
474482 redirect: "error",
475483 signal,
476 });
484 };
485 // A person's own connection is reached only through the guard, which follows no redirect.
486 const res = run.account?.connection?.guarded === true ? await outboundFetch(`${cfg.base}/chat/completions`, { ...ask, signal }, guard) : await fetch(`${cfg.base}/chat/completions`, { ...ask, signal });
477487 if (!res.ok) {
478488 result = `endpoint answered ${res.status}: ${(await readCapped(res.body, 2000)).text.slice(0, 300)}`;
479489 run.log(`! ${result}`);
src/http/server.ts +2
@@ -174,6 +174,7 @@ import {
174174 themeSubmit,
175175 } from "../web/pages/site.ts";
176176 import { talkBuild, talkPublish, talkRestore } from "../web/talk_build.ts";
177 import { talkModel } from "../web/talk_model.ts";
177178 import { talkAct, talkAgainSend, talkArchive, talkConfirm, talkDisplaySave, talkDownload, talkNew, talkPin, talkQueueCancel, talkRename, talkSend, talkUndo, talkStream, talkView, talkWall } from "../web/pages/talk.ts";
178179 import { liveTalkCrew, liveTalkWork, talkPeek } from "../web/talk_peek.ts";
179180 import {
@@ -1280,6 +1281,7 @@ export function buildRouter(): Router<Handler> {
12801281 router.add("GET", "/talk/:id/download", talkDownload);
12811282 router.add("POST", "/talk/:id", talkSend);
12821283 router.add("POST", "/talk/:id/rename", talkRename);
1284 router.add("POST", "/talk/:id/model", talkModel);
12831285 router.add("POST", "/talk/:id/archive", talkArchive);
12841286 router.add("POST", "/talk/:id/pin", talkPin);
12851287 router.add("POST", "/talk/:id/build/restore", talkRestore);
src/tui/screens/talk_chats.ts +30
@@ -53,6 +53,7 @@ import type { Session } from "../session.ts";
5353 import type { User } from "../../core/users.ts";
5454 import { agoWords, togetherOf } from "../../design/together.ts";
5555 import { fill, len, split } from "../ui/layout.ts";
56 import { choiceLabel, choiceOf, choiceValue, FORGE_MODEL, offers, setChoice } from "../../core/model_choice.ts";
5657 import { ListState, Scroll, ago, confirmScreen, drawLines, drawList, errorText, later, pickerScreen, promptScreen, runAsync, type ListRow, type PickItem } from "./common.ts";
5758 import { answerWall } from "../../actions/pulls.ts";
5859 import { fresh, mayAct, pressCard, PRESS_REFUSED } from "../../actions/talk_act.ts";
@@ -349,6 +350,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
349350 keys: [
350351 binding(["j", "k"], "scroll"),
351352 binding(["s"], "say"),
353 binding(["m"], "model"),
352354 binding(["1", "2", "3"], "starter"),
353355 binding(["r"], "reload"),
354356 binding(["p"], "pane"),
@@ -383,6 +385,34 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
383385 }
384386 const user = f.user;
385387 if (user === undefined || e.ctrl || e.alt) return false;
388 if (e.key === "m" && !pane) {
389 // The page's model picker (`core/model_choice.ts`): the forge's own and every model offered.
390 const offered = offers(f.app.db, user);
391 if (offered.length === 0) {
392 note = "No connection offers a model: add one on Connect your AI (the Model budget screen).";
393 ctx.invalidate();
394 return true;
395 }
396 const now = choiceOf(f.app.db, user.id, chat.id);
397 const items: PickItem[] = [
398 { id: "", label: FORGE_MODEL },
399 ...offered.flatMap((o) => o.models.map((m) => ({ id: choiceValue({ connectionId: o.connection.id, model: m }), label: choiceLabel(o.connection, m) }))),
400 ];
401 ctx.push(
402 pickerScreen(ctx, screen, {
403 title: "Model",
404 items,
405 chosen: [now === undefined ? "" : choiceValue(now)],
406 onPick: ([value]) => {
407 if (value === undefined) return;
408 const set = setChoice(f.app.db, user, chat.id, value);
409 note = !set.ok ? "That model is not offered now." : `${items.find((i) => i.id === value)?.label ?? FORGE_MODEL} answers here.`;
410 ctx.invalidate();
411 },
412 }),
413 );
414 return true;
415 }
386416 if (e.key === "p" || (pane && e.key === "esc")) {
387417 pane = !pane;
388418 if (pane)
src/tui/ssh-talk.ts +1 −1
@@ -200,7 +200,7 @@ export function serveTalk(app: App, session: SshSession, user: User | undefined,
200200 /**
201201 * The line the terminal prints for the turn before: the page's Stopped wording when it was stopped.
202202 */
203 export const lastTurnWords = (spend: Spend): string => (spend.stopped ? spendWords(spend) : `last turn ${dollars(spend.usd)}`);
203 export const lastTurnWords = (spend: Spend): string => (spend.stopped || spend.usd <= 0 ? spendWords(spend) : `last turn ${dollars(spend.usd)}${spend.model === undefined ? "" : ` · ${spend.model}`}`);
204204
205205 /** `talk-again <edit words | regenerate | retry>`; undefined when the command is not one. */
206206 export function parseTalkAgain(command: string | undefined): { how: RedoHow; words: string } | undefined {
src/web/pages/talk.ts +5 −1
@@ -85,6 +85,7 @@ import { chatBuildOf } from "../../core/chat_build.ts";
8585 import { receiptIssues, runningStep, stepOf, repoOf, steerOf, type Step } from "../../core/talk_steps.ts";
8686 import { paneCss, VIEWS, talkPane, type View } from "./talk_preview.ts";
8787 import { TALK_KEYS, talkCss, talkJs } from "./talk_client.ts";
88 import { modelForm, modelPicker } from "../talk_model.ts";
8889 import { liveRegionsJs } from "../client.ts";
8990
9091 /** A stream lasts this long at most; the client reconnects from its last turn id. */
@@ -636,6 +637,8 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
636637 const lines = receiptLines(ctx.app.db, ctx.app.config.dataDir, user, turns);
637638 // The crew's line says something only while a run is live: idle is silence.
638639 const crew = liveCrewRows(ctx, user);
640 // The model picker (`talk_model.ts`), only where a connection offers a model.
641 const picker = buildMode ? null : modelPicker(ctx, user, conversation.id);
639642 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>
640643 <div class="talk-side">${chats(ctx, conversation, showArchived, typed)}</div>
641644 <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"}">
@@ -673,11 +676,12 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
673676 <button type="submit" class="btn btn-icon talk-send" data-variant="primary" aria-label="${buildMode ? "Build it" : editing === undefined ? "Send" : "Resend"}" title="${buildMode ? "Build it" : editing === undefined ? "Send" : "Resend"}">${icon("arrowUp")}</button>
674677 </div>
675678 </div>
676 ${buildMode ? html`<p class="talk-foot small"><a href="${here}">Talk instead</a></p>` : null}
679 ${buildMode ? html`<p class="talk-foot small"><a href="${here}">Talk instead</a></p>` : picker}
677680 <p class="talk-error small" id="talk-error" data-error hidden></p>
678681 <p class="talk-status small muted" role="status">${running ? "The forge is answering…" : ""}</p>
679682 <button type="button" class="btn talk-jump" data-jump hidden>${icon("pause")}${icon("arrowDown")}<span data-word></span><i class="talk-dot"></i></button>
680683 </form>
684 ${picker === null ? null : modelForm(urlOf(conversation))}
681685 <template id="talk-ico">${icon("copy")}${icon("check")}</template>
682686 </div>
683687 ${split ? html`<div class="talk-work">${panel}${pane.html}</div>` : null}
src/web/pages/talk_client.ts +5 −1
@@ -234,7 +234,9 @@ body:has(.talk-page) .foot { display: none; }
234234 .talk-send[hidden], .talk-stop[hidden], .talk-steer[hidden], .talk-dictate[hidden], [data-attach][hidden], .talk-jump[hidden] { display: none; }
235235 .talk-steer { border-radius: 999px; }
236236 .talk-dictate[aria-pressed="true"] { background: var(--accent); color: var(--bg); }
237 .talk-foot { margin: 6px 16px 0; }
237 .talk-foot, .talk-model { margin: 6px 16px 0; }
238 .talk-model { display: flex; align-items: center; gap: 8px; }
239 .talk-model select { width: auto; }
238240 .talk-status { margin: 6px 16px 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
239241 .talk-status:empty { display: none; }
240242 [data-answering] .talk-status { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
@@ -419,6 +421,8 @@ if (root) {
419421 if (head) head.addEventListener("focusin", () => head.removeAttribute("data-away"));
420422 const jump = form.querySelector("[data-jump]");
421423 const err = form.querySelector("[data-error]");
424 const pick = form.querySelector("[data-model-pick]");
425 if (pick) { form.querySelector("[data-model-use]").hidden = true; pick.onchange = () => pick.form.requestSubmit(); }
422426 box.required = false;
423427 const fail = (words) => { say(""); err.textContent = words; err.hidden = false; box.setAttribute("aria-invalid", "true"); };
424428 // The keyboard covers the layout viewport on phones: lift the composer by what it hides.
src/web/talk_model.ts added +58
@@ -0,0 +1,58 @@
1 /**
2 * Talk's model picker, in the composer (`core/model_choice.ts`): a select of every model the person
3 * may use on a working connection, and the forge's own, saved for the conversation. A plain form
4 * post (`POST /talk/:id/model`), so it works with the script off; the script sends it on change.
5 * Absent when no connection offers a model, so a forge without connections looks as before.
6 */
7 import { choiceLabel, choiceOf, choiceValue, FORGE_MODEL, offers, setChoice } from "../core/model_choice.ts";
8 import { connectionFor } from "../core/connections.ts";
9 import { getConversation } from "../core/conversations.ts";
10 import type { User } from "../core/users.ts";
11 import type { Ctx } from "../http/context.ts";
12 import { notFoundPage, signInFirst } from "./chrome.ts";
13 import { field, readForm } from "./form.ts";
14 import { html, type Html } from "./html.ts";
15 import { flashTo } from "./layout.ts";
16
17 /** The picker's line under the composer, its form outside it (`form=`), or null with nothing to offer. */
18 export function modelPicker(ctx: Ctx, user: User, conversationId: string): Html | null {
19 const offered = offers(ctx.app.db, user);
20 const now = choiceOf(ctx.app.db, user.id, conversationId);
21 // A conversation on a model that stopped answering keeps its picker: the way back to the forge's own.
22 if (offered.length === 0 && now === undefined) return null;
23 const current = now === undefined ? "" : choiceValue(now);
24 const listed = offered.some((o) => o.connection.id === now?.connectionId && o.models.includes(now.model));
25 // A choice whose connection stopped answering stays shown as the conversation's, never offered anew.
26 const stale = now === undefined || listed ? undefined : connectionFor(ctx.app.db, user.id, now.connectionId);
27 return html`<p class="talk-model small">
28 <label for="talk-model-pick">Model</label>
29 <select class="input" id="talk-model-pick" name="model" form="talk-model" data-model-pick>
30 <option value=""${current === "" ? html` selected` : null}>${FORGE_MODEL}</option>
31 ${now !== undefined && !listed ? html`<option value="${current}" selected>${choiceLabel(stale ?? { name: "a removed connection" }, now.model)} (not answering)</option>` : null}
32 ${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>`)}
33 </select>
34 <button type="submit" class="btn" data-size="sm" data-variant="ghost" form="talk-model" data-model-use>Use</button>
35 </p>`;
36 }
37
38 /** The picker's own form, outside the composer's (a form cannot hold another). */
39 export const modelForm = (here: string): Html => html`<form id="talk-model" method="post" action="${here}/model" hidden></form>`;
40
41 // POST /talk/:id/model — the conversation's model, from the picker.
42 export async function talkModel(ctx: Ctx): Promise<Response> {
43 const user = ctx.auth.user;
44 if (user === undefined) return signInFirst(ctx);
45 const form = await readForm(ctx, "rw");
46 if (form instanceof Response) return form;
47 const conversation = getConversation(ctx.app.db, user.id, ctx.params["id"] ?? "");
48 if (conversation === undefined) return notFoundPage(ctx);
49 const back = `/talk/${encodeURIComponent(conversation.id)}#end`;
50 const value = field(form, "model");
51 const now = choiceOf(ctx.app.db, user.id, conversation.id);
52 // Sending the choice it already has changes nothing, even when that model has stopped answering.
53 if (now !== undefined && value === choiceValue(now)) return flashTo(ctx, back, { message: "Kept." });
54 const set = setChoice(ctx.app.db, user, conversation.id, value);
55 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." });
56 const on = set.value === undefined ? undefined : connectionFor(ctx.app.db, user.id, set.value.connectionId);
57 return flashTo(ctx, back, { tone: "success", message: on === undefined || set.value === undefined ? `${FORGE_MODEL} answers here.` : `${choiceLabel(on, set.value.model)} answers here.` });
58 }
test/outbound-guard.test.ts +16
@@ -26,6 +26,8 @@ import { join } from "node:path";
2626 import { TLSSocket } from "node:tls";
2727 import { createApp, type App } from "../src/app.ts";
2828 import { vetClone } from "../src/actions/migrate.ts";
29 import { runOpenAI } from "../src/crew/openai_runner.ts";
30 import { sandboxPolicy } from "../src/crew/sandbox.ts";
2931 import { testConnection } from "../src/actions/connections.ts";
3032 import { probeCertificate } from "../src/apps/certificate.ts";
3133 import { statusOf } from "../src/apps/parity_probe.ts";
@@ -108,6 +110,20 @@ let repoId = "";
108110 let hooks = 0;
109111
110112 const SITES: readonly Site[] = [
113 {
114 file: "src/crew/openai_runner.ts",
115 what: "a Talk turn on a person's own model connection (core/model_choice.ts)",
116 fetches: true,
117 names: true,
118 refused: async (t) =>
119 (
120 await runOpenAI(
121 { binary: "", cwd: dir, prompt: "hi", appendSystemPrompt: "", model: "m", budgetUsd: 1, env: {}, sandbox: sandboxPolicy({ dataDir: dir, agentName: "guard", urls: [], enforced: false, runId: "guard" }), timeoutMs: 10_000, log: () => {}, signal: new AbortController().signal, account: { token: "k", base: `https://${t.host}/v1`, connection: { guarded: true } } },
122 {},
123 { resolve: t.resolve },
124 )
125 ).result.includes(REFUSED_SENTENCE),
126 },
111127 {
112128 file: "src/actions/connections.ts",
113129 what: "a person's own model connection, tested before it is saved",
test/talk-model-choice.test.ts added +446
@@ -0,0 +1,446 @@
1 /**
2 * Talk's model picker (`core/model_choice.ts`), against a canned OpenAI-compatible server and a
3 * fake default runner that stands for the forge's own. A conversation with no choice runs as before,
4 * on a subscription from before connections too. The picker offers only working connections the
5 * person may use; a chosen model answers on its connection and the line under the reply names it; a
6 * connection that fails mid-way says so in one sentence, flagged for Retry, is no longer offered,
7 * and nothing else answers for it; a removed one runs nothing; a person's own goes only through the
8 * outbound guard; and the page's picker is a plain form that works with the script off.
9 */
10 import {
11 afterAll,
12 beforeAll,
13 beforeEach,
14 describe,
15 expect,
16 test,
17 } from "bun:test";
18 import { mkdtemp, rm } from "node:fs/promises";
19 import { tmpdir } from "node:os";
20 import { join } from "node:path";
21 import { createApp, type App } from "../src/app.ts";
22 import {
23 listConnections,
24 recordTest,
25 removeConnection,
26 saveConnection,
27 } from "../src/core/connections.ts";
28 import { spendWords, turnSpend } from "../src/core/conversation_cost.ts";
29 import {
30 createConversation,
31 listTurns,
32 type Turn,
33 } from "../src/core/conversations.ts";
34 import {
35 choiceOf,
36 failedOnLine,
37 GONE_LINE,
38 offers,
39 setChoice,
40 } from "../src/core/model_choice.ts";
41 import { createSession } from "../src/core/sessions.ts";
42 import {
43 addSubscription,
44 EVERYONE,
45 setGrants,
46 } from "../src/core/subscriptions.ts";
47 import { createUser, type User } from "../src/core/users.ts";
48 import {
49 useRunner,
50 type AgentOutcome,
51 type AgentRun,
52 } from "../src/crew/agent_runner.ts";
53 import { say, type ConversationOptions } from "../src/crew/conversation.ts";
54 import { serve, type Servers } from "../src/http/server.ts";
55 import { modelHostBlocked } from "../src/actions/blocked_words.ts";
56 import { runOpenAI } from "../src/crew/openai_runner.ts";
57 import { sandboxPolicy } from "../src/crew/sandbox.ts";
58 import { blockedText } from "../src/kernel/blocked.ts";
59 import { GateRefusedError } from "../src/kernel/outbound.ts";
60 import { promote } from "./helpers/members.ts";
61
62 let dir: string;
63 let app: App;
64 let servers: Servers;
65 let canned: ReturnType<typeof Bun.serve>;
66 let keeper: User;
67 let bob: User;
68 /** What the canned server answers next (a plain body is read as a stream is), and what it heard. */
69 let answers: (() => Response)[] = [];
70 const heard: { model: unknown; auth: string | null }[] = [];
71 /** The reasoning effort each call asked for, when it asked one. */
72 const efforts: unknown[] = [];
73 /** Every run the forge's own (the fake default runner) was handed. */
74 const defaults: AgentRun[] = [];
75
76 const reply = (words: string): Response =>
77 Response.json({
78 choices: [{ message: { role: "assistant", content: words } }],
79 usage: { prompt_tokens: 10, completion_tokens: 3 },
80 });
81
82 const options = (): ConversationOptions => ({
83 binary: "unused",
84 localUrl: servers.url,
85 budgetUsd: 1,
86 timeoutMs: 30_000,
87 signal: new AbortController().signal,
88 });
89
90 /** Say `words` in `conversationId` as `user`, wait for the turn, and return the conversation's turns. */
91 const turn = async (
92 user: User,
93 conversationId: string,
94 words: string,
95 ): Promise<Turn[]> => {
96 const said = say(app, options(), user.id, words, [], "queue", conversationId);
97 if (!said.ok) throw new Error(said.error);
98 if (said.value.how === "started") await said.value.done;
99 const turns = listTurns(app.db, user.id, conversationId, { limit: 200 });
100 if (!turns.ok) throw new Error("turns");
101 return turns.value;
102 };
103 const conversation = (user: User): string => {
104 const made = createConversation(app.db, user.id);
105 if (!made.ok) throw new Error(made.error);
106 return made.value.id;
107 };
108
109 beforeAll(async () => {
110 dir = await mkdtemp(join(tmpdir(), "forge-model-choice-"));
111 canned = Bun.serve({
112 port: 0,
113 hostname: "127.0.0.1",
114 async fetch(req) {
115 const body = (await req.json().catch(() => ({}))) as { model?: unknown; reasoning_effort?: unknown };
116 efforts.push(body.reasoning_effort);
117 heard.push({ model: body.model, auth: req.headers.get("authorization") });
118 return (answers.shift() ?? (() => reply("(nothing more)")))();
119 },
120 });
121 useRunner({
122 run: async (input): Promise<AgentOutcome> => {
123 defaults.push(input);
124 input.onSaid?.({ kind: "text", text: "The forge's own answered." });
125 return {
126 ok: true,
127 sessionId: "s1",
128 result: "The forge's own answered.",
129 costUsd: 0.02,
130 turns: 1,
131 tokensIn: 5,
132 tokensOut: 5,
133 contextTokens: 5,
134 contextWindow: 0,
135 reason: "completed",
136 };
137 },
138 detect: async () => ({ ok: true, version: "fake" }),
139 resumes: true,
140 });
141 app = createApp({ dataDir: dir, port: 0 });
142 servers = await serve(app);
143 const person = async (username: string, first = false) => {
144 const made = await createUser(app.db, {
145 origin: "seed",
146 trusted: true,
147 username,
148 email: `${username}@forge.local`,
149 password: "a-good-passphrase",
150 adminIfFirst: first,
151 });
152 if (!made.ok) throw new Error(made.error);
153 promote(app.db, made.value);
154 return made.value;
155 };
156 keeper = await person("keeper", true);
157 bob = await person("bob");
158 // The forge's own, on this machine: saved as a passed test would save it.
159 const spark = saveConnection(app.db, app.config.dataDir, {
160 name: "Spark",
161 protocol: "openai",
162 base: `http://127.0.0.1:${String(canned.port)}/v1`,
163 key: "sk-spark",
164 scope: "forge",
165 userId: keeper.id,
166 models: [{ id: "canned/small" }, { id: "canned/large" }],
167 said: "2 models listed",
168 });
169 if (!spark.ok) throw new Error(spark.error);
170 });
171 afterAll(async () => {
172 useRunner(undefined);
173 canned.stop(true);
174 servers.stop();
175 app.close();
176 await rm(dir, { recursive: true, force: true });
177 });
178 beforeEach(() => {
179 answers = [];
180 heard.length = 0;
181 defaults.length = 0;
182 });
183
184 const spark = () =>
185 listConnections(app.db, keeper.id).find((c) => c.name === "Spark")!;
186
187 describe("no choice: as before", () => {
188 test("a subscription from before connections still runs a turn on the forge's own runner, with its own token", async () => {
189 const old = addSubscription(app.db, app.config.dataDir, {
190 name: "bobs-plan",
191 token: "sk-ant-api03-from-before",
192 createdBy: keeper.id,
193 });
194 if (!old.ok) throw new Error(old.error);
195 setGrants(app.db, bob.id, EVERYONE, [old.value.id]);
196 const turns = await turn(bob, conversation(bob), "hello");
197 expect(turns.at(-1)?.text).toBe("The forge's own answered.");
198 expect(defaults).toHaveLength(1);
199 expect(defaults[0]!.account?.token).toBe("sk-ant-api03-from-before");
200 expect(defaults[0]!.env["ANTHROPIC_API_KEY"]).toBe(
201 "sk-ant-api03-from-before",
202 );
203 expect(heard).toHaveLength(0);
204 setGrants(app.db, bob.id, EVERYONE, []);
205 });
206 });
207
208 describe("what the picker offers", () => {
209 test("only working connections the person may use: the forge's to an admin or a grantee, never a failed one", () => {
210 expect(
211 offers(app.db, keeper).map((o) => [o.connection.name, o.models]),
212 ).toEqual([["Spark", ["canned/small", "canned/large"]]]);
213 expect(offers(app.db, bob)).toEqual([]);
214 const c = conversation(bob);
215 expect(setChoice(app.db, bob, c, `${spark().id} canned/small`)).toEqual({
216 ok: false,
217 error: "not_offered",
218 });
219 setGrants(app.db, bob.id, EVERYONE, [spark().id]);
220 expect(offers(app.db, bob).map((o) => o.connection.name)).toEqual([
221 "Spark",
222 ]);
223 expect(setChoice(app.db, bob, c, `${spark().id} canned/huge`)).toEqual({
224 ok: false,
225 error: "not_offered",
226 });
227 expect(setChoice(app.db, bob, c, `${spark().id} canned/small`).ok).toBe(
228 true,
229 );
230 expect(setChoice(app.db, keeper, c, "")).toEqual({
231 ok: false,
232 error: "not_found",
233 });
234 recordTest(app.db, spark().id, { working: false, said: "it answered 500" });
235 expect(offers(app.db, bob)).toEqual([]);
236 recordTest(app.db, spark().id, { working: true, said: "2 models listed" });
237 setGrants(app.db, bob.id, EVERYONE, []);
238 });
239 });
240
241 describe("a turn on a chosen model", () => {
242 test("answers on its connection with its key, never the forge's own, and the line under the reply names the model", async () => {
243 const c = conversation(keeper);
244 expect(setChoice(app.db, keeper, c, `${spark().id} canned/large`).ok).toBe(
245 true,
246 );
247 answers = [() => reply("Spark here.")];
248 const turns = await turn(keeper, c, "who answers?");
249 expect(turns.at(-1)?.text).toBe("Spark here.");
250 expect(heard).toEqual([{ model: "canned/large", auth: "Bearer sk-spark" }]);
251 expect(defaults).toHaveLength(0);
252 const last = [...turnSpend(app.db, c).values()].at(-1)!;
253 // A model the price table does not know states no cost: its name alone, never $0.
254 expect(spendWords(last)).toBe("canned/large this turn");
255 });
256
257 test("the connection's reasoning effort goes with its turn", async () => {
258 app.db.query("UPDATE subscription SET effort = 'low' WHERE id = ?1").run(spark().id);
259 const c = conversation(keeper);
260 expect(setChoice(app.db, keeper, c, `${spark().id} canned/small`).ok).toBe(true);
261 efforts.length = 0;
262 answers = [() => reply("Low effort.")];
263 expect((await turn(keeper, c, "quick one")).at(-1)?.text).toBe("Low effort.");
264 expect(efforts).toEqual(["low"]);
265 app.db.query("UPDATE subscription SET effort = '' WHERE id = ?1").run(spark().id);
266 });
267
268 test("a connection that fails mid-way: one sentence flagged for Retry, no other model answers, and the picker stops offering it", async () => {
269 const c = conversation(keeper);
270 expect(setChoice(app.db, keeper, c, `${spark().id} canned/small`).ok).toBe(
271 true,
272 );
273 answers = [() => new Response("upstream down", { status: 502 })];
274 const turns = await turn(keeper, c, "still there?");
275 expect(turns.at(-1)).toMatchObject({
276 role: "agent",
277 text: failedOnLine("Spark", "canned/small"),
278 failed: true,
279 });
280 expect(turns.filter((t) => t.role === "agent")).toHaveLength(1);
281 expect(defaults).toHaveLength(0);
282 expect(spark().working).toBe(false);
283 expect(offers(app.db, keeper)).toEqual([]);
284 // The choice stays the conversation's: Retry runs on it again, and an answer brings it back.
285 expect(choiceOf(app.db, keeper.id, c)?.model).toBe("canned/small");
286 answers = [() => reply("Back again.")];
287 expect((await turn(keeper, c, "and now?")).at(-1)?.text).toBe(
288 "Back again.",
289 );
290 expect(spark().working).toBe(true);
291 });
292
293 test("a person's own goes only through the outbound guard: on a private address nothing is sent, and it says so", async () => {
294 setGrants(app.db, bob.id, EVERYONE, []);
295 const own = saveConnection(app.db, app.config.dataDir, {
296 name: "Bobs",
297 protocol: "openai",
298 base: "https://bobs.example.com/v1",
299 key: "sk-bob",
300 scope: "yours",
301 userId: bob.id,
302 models: [{ id: "m1" }],
303 said: "1 models listed",
304 });
305 if (!own.ok) throw new Error(own.error);
306 const c = conversation(bob);
307 expect(setChoice(app.db, bob, c, `${own.value.id} m1`).ok).toBe(true);
308 // Moved under the guard's feet to this machine: the guard refuses it before any byte goes.
309 app.db
310 .query("UPDATE subscription SET api_base = ?2 WHERE id = ?1")
311 .run(own.value.id, `https://127.0.0.1:${String(canned.port)}/v1`);
312 const turns = await turn(bob, c, "hi");
313 expect(turns.at(-1)).toMatchObject({
314 text: failedOnLine("Bobs", "m1"),
315 failed: true,
316 });
317 expect(heard).toHaveLength(0);
318 expect(defaults).toHaveLength(0);
319 });
320
321 test("a removed connection runs nothing, and says to pick another", async () => {
322 const extra = saveConnection(app.db, app.config.dataDir, {
323 name: "Brief",
324 protocol: "openai",
325 base: `http://127.0.0.1:${String(canned.port)}/v1`,
326 key: "",
327 scope: "forge",
328 userId: keeper.id,
329 models: [{ id: "tiny" }],
330 said: "1 models listed",
331 });
332 if (!extra.ok) throw new Error(extra.error);
333 const c = conversation(keeper);
334 expect(setChoice(app.db, keeper, c, `${extra.value.id} tiny`).ok).toBe(
335 true,
336 );
337 expect(removeConnection(app.db, keeper, extra.value.id)).toBe(true);
338 const turns = await turn(keeper, c, "anyone?");
339 expect(turns.at(-1)).toMatchObject({ text: GONE_LINE, failed: true });
340 expect(heard).toHaveLength(0);
341 expect(defaults).toHaveLength(0);
342 });
343 });
344
345 describe("the page's picker", () => {
346 test("a select in the composer, posted as a plain form: it sets the conversation's model and the page shows it chosen", async () => {
347 const c = conversation(keeper);
348 const cookie = `forge_session=${createSession(app.db, keeper.id).token}`;
349 const page = await (
350 await fetch(`${servers.url}/talk/${c}`, { headers: { cookie } })
351 ).text();
352 expect(page).toContain('id="talk-model-pick"');
353 expect(page).toContain(
354 '<form id="talk-model" method="post" action="/talk/' +
355 c +
356 '/model" hidden>',
357 );
358 expect(page).toContain("canned/large · Spark");
359 const post = (model: string) =>
360 fetch(`${servers.url}/talk/${c}/model`, {
361 method: "POST",
362 redirect: "manual",
363 headers: {
364 cookie,
365 origin: servers.url,
366 "content-type": "application/x-www-form-urlencoded",
367 },
368 body: new URLSearchParams({ model }),
369 });
370 expect((await post(`${spark().id} canned/large`)).status).toBe(303);
371 expect(choiceOf(app.db, keeper.id, c)?.model).toBe("canned/large");
372 const after = await (
373 await fetch(`${servers.url}/talk/${c}`, { headers: { cookie } })
374 ).text();
375 expect(after).toMatch(/<option value="[0-9a-z]+ canned\/large"\s+selected/);
376 // A model not offered changes nothing; another person's conversation is not found.
377 await post(`${spark().id} canned/huge`);
378 expect(choiceOf(app.db, keeper.id, c)?.model).toBe("canned/large");
379 const theirs = await fetch(`${servers.url}/talk/${c}/model`, {
380 method: "POST",
381 redirect: "manual",
382 headers: {
383 cookie: `forge_session=${createSession(app.db, bob.id).token}`,
384 origin: servers.url,
385 "content-type": "application/x-www-form-urlencoded",
386 },
387 body: new URLSearchParams({ model: "" }),
388 });
389 expect(theirs.status).toBe(404);
390 expect((await post("")).status).toBe(303);
391 expect(choiceOf(app.db, keeper.id, c)).toBeUndefined();
392 });
393
394 test("with nothing to offer there is no picker at all", async () => {
395 const page = await (
396 await fetch(`${servers.url}/talk/${conversation(bob)}`, {
397 headers: {
398 cookie: `forge_session=${createSession(app.db, bob.id).token}`,
399 },
400 })
401 ).text();
402 expect(page).not.toContain("talk-model-pick");
403 });
404 });
405
406 describe("the picker after a fall", () => {
407 test("a conversation whose model stopped answering keeps its picker: that model, marked, and the forge's own", async () => {
408 const c = conversation(keeper);
409 expect(setChoice(app.db, keeper, c, `${spark().id} canned/small`).ok).toBe(true);
410 recordTest(app.db, spark().id, { working: false, said: "it answered 502" });
411 const cookie = `forge_session=${createSession(app.db, keeper.id).token}`;
412 const page = await (await fetch(`${servers.url}/talk/${c}`, { headers: { cookie } })).text();
413 expect(page).toContain("canned/small · Spark (not answering)");
414 expect(page).toContain("The forge&#39;s model");
415 // Sending the same choice keeps it; the forge's own is one choice away.
416 const post = (model: string) => fetch(`${servers.url}/talk/${c}/model`, { method: "POST", redirect: "manual", headers: { cookie, origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ model }) });
417 await post(`${spark().id} canned/small`);
418 expect(choiceOf(app.db, keeper.id, c)?.model).toBe("canned/small");
419 await post("");
420 expect(choiceOf(app.db, keeper.id, c)).toBeUndefined();
421 recordTest(app.db, spark().id, { working: true, said: "2 models listed" });
422 });
423 });
424
425 describe("the forge's egress gate, at a turn", () => {
426 test("a refusal reaches the turn in the gate's own words, which the turn says as the add form does", async () => {
427 const words = "refused by this forge: models.example.com:443 is not in this app's forge.json egress";
428 const gate = Bun.listen<undefined>({
429 hostname: "127.0.0.1",
430 port: 0,
431 socket: { data: (s) => void s.end(`HTTP/1.1 403 ${words}\r\nX-Forge-Egress: refused\r\nContent-Length: ${String(words.length)}\r\n\r\n${words}`), open() {}, close() {} },
432 });
433 try {
434 const out = await runOpenAI(
435 { binary: "", cwd: dir, prompt: "hi", appendSystemPrompt: "", model: "m1", budgetUsd: 1, env: {}, sandbox: sandboxPolicy({ dataDir: dir, agentName: "gate", urls: [], enforced: false, runId: "gate" }), timeoutMs: 10_000, log: () => {}, signal: new AbortController().signal, account: { token: "sk-bob", base: "https://models.example.com/v1", connection: { guarded: true } } },
436 {},
437 { proxy: `http://127.0.0.1:${String(gate.port)}` },
438 );
439 expect(out.ok).toBe(false);
440 expect(out.result).toContain(new GateRefusedError("models.example.com").message);
441 expect(blockedText(modelHostBlocked(app, bob, "models.example.com"))).toStartWith("This forge can reach openrouter.ai, api.openai.com and api.anthropic.com for your own connections, not models.example.com.");
442 } finally {
443 gate.stop(true);
444 }
445 });
446 });
test/tui-talk-model.test.ts added +81
@@ -0,0 +1,81 @@
1 /**
2 * `m` in an open terminal Talk conversation is the page's model picker (`core/model_choice.ts`): the
3 * forge's own and every model a working connection offers; choosing one sets the conversation's
4 * model and says so. With nothing offered, it says where to add a connection.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { saveConnection } from "../src/core/connections.ts";
12 import { createConversation, renameConversation } from "../src/core/conversations.ts";
13 import { choiceOf } from "../src/core/model_choice.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { createForgeApp } from "../src/tui/forge.ts";
16 import { headlessTerminal } from "../src/tui/term/terminal.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18 import { settleApp } from "./helpers/tui.ts";
19
20 quietLogs();
21
22 let dir: string;
23 let app: App;
24 let alice: User;
25 let bob: User;
26 const convo: Record<string, string> = {};
27
28 async function drive(user: User, keys: string[]): Promise<string> {
29 const terminal = headlessTerminal(140, 50);
30 const { app: tui } = createForgeApp(app, { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user }, { terminal, exitHooks: false });
31 tui.start();
32 await settleApp(tui);
33 for (const k of keys) {
34 terminal.feed(k);
35 await settleApp(tui);
36 }
37 const text = tui.screen.toText();
38 tui.stop?.();
39 return text;
40 }
41
42 beforeAll(async () => {
43 dir = await mkdtemp(join(tmpdir(), "forge-tui-model-pick-"));
44 app = createApp({ dataDir: dir, port: 0, host: "forge.test" });
45 const mk = async (username: string, first = false) => {
46 const r = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first });
47 if (!r.ok) throw new Error(r.error);
48 return r.value;
49 };
50 alice = await mk("alice", true);
51 bob = await mk("bob");
52 const spark = saveConnection(app.db, app.config.dataDir, { name: "Spark", protocol: "openai", base: "http://127.0.0.1:9/v1", key: "", scope: "forge", userId: alice.id, models: [{ id: "canned/small" }], said: "1 models listed" });
53 if (!spark.ok) throw new Error(spark.error);
54 for (const u of [alice, bob]) {
55 const c = createConversation(app.db, u.id);
56 if (!c.ok) throw new Error("conversation");
57 renameConversation(app.db, u.id, c.value.id, "Pick a model");
58 convo[u.id] = c.value.id;
59 }
60 });
61 afterAll(async () => {
62 app.db.close();
63 await rm(dir, { recursive: true, force: true });
64 });
65
66 const open = [":", "Conversations", "\r", "\r"];
67
68 test("m lists the forge's own and the offered models; choosing one sets the conversation's model", async () => {
69 const shown = await drive(alice, [...open, "m"]);
70 expect(shown).toContain("The forge's model");
71 expect(shown).toContain("canned/small · Spark");
72 const picked = await drive(alice, [...open, "m", "j", "\r"]);
73 expect(choiceOf(app.db, alice.id, convo[alice.id]!)?.model).toBe("canned/small");
74 expect(picked).toContain("canned/small · Spark answers here.");
75 });
76
77 test("with nothing offered, m says where to add a connection and changes nothing", async () => {
78 const shown = await drive(bob, [...open, "m"]);
79 expect(shown).toContain("No connection offers a model");
80 expect(choiceOf(app.db, bob.id, convo[bob.id]!)).toBeUndefined();
81 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs