Files
archie/internal/channels/telegram/model_test.go
T
sam 4750ac097b feat(workflow): post line-anchored review comments with suggested fixes (#891)
* feat(workflow): post line-anchored review comments with suggested fixes

Bead archie-core-q9au (docs/prds/inline-review.md). A review's findings reached
the operator only as a flat list in the PR body, so the author had to map every
finding back to its line by hand and apply mechanical fixes by hand. Now the
line-anchored findings are also posted as inline review comments, carrying a
one-click suggestion when the reviewer could state the fix.

Domain (internal/domain/workflow):
- ReviewFinding gains Suggestion; Validate rejects one on anything but a
  confirmed finding, so the agent's record_finding call is refused with
  something it can act on. Validate splits into validateAnchor /
  validateClassification / validateDisposition, which also brings it back under
  the cyclop limit the gate enforces.
- StagePostReviewComments runs after StageOpenPR in the implement workflow. It
  posts only line-anchored findings (Line > 0); a whole-file finding has no line
  to attach to and stays in the body list, which remains the complete record.
  It is best-effort: the PR is open and the body already lists every finding, so
  a failed comment is logged, never a park -- the same reasoning as OpenPR's
  existing best-effort LinkBranch call.
- The suggestion fence is gated on Verdict == confirmed where the fence is
  written, because it is a one-click apply: a wrong suggestion breaks the code
  and the author has to notice.

Forge (internal/forge): ReviewCommentWriter + GitHub/Gitea implementations,
type-asserted like PullRequestReader so a forge that cannot is skipped rather
than faked (NoopForge is pinned as not satisfying it). GitHub loops one
CreateComment per comment and joins the failures, so one refused anchor cannot
drop the rest; Gitea carries them on a single COMMENT-state review.

Two deliberate departures from the PRD's sketch, both recorded in it:
- The interface is batch (CreateReviewComments), not one call per comment:
  Gitea's only inline shape is one submitted review, and the set then crosses
  NATS once instead of once per finding.
- The head SHA is resolved inside each forge implementation rather than by the
  caller. The stage runs in archie-agent, which holds no forge credentials and
  has no PullRequestReader; the daemon-side forgerpc handler is the only place
  that does.

Transport (internal/forgerpc): workflow.Forger gains the method, so the agent
reaches the daemon over the new create_review_comments subject; the server
type-asserts the writer and answers an incapable forge with an error the stage
logs. This is the one proxied method whose absence on an image skew does not
park a task.

The reviewer prompt and record_finding schema ask for a suggestion on a
confirmed, mechanically fixable defect only.

Regenerating the wfextract symbol table -- the documented way a new exported
workflow symbol reaches interpreted stage plugins -- also picked up symbols that
were missing from the committed table (the Status* and Source* constants,
ReviewCheck, Store, Task, and the _Store wrapper). Nil-guards were re-applied to
every wrapper afterwards, as that file's header requires.

Evidence: task check exit 0 (incl. 229 UI tests). Three mutations of the new
stage logic each fail a test that names the behaviour -- dropping the
confirmed-only gate, dropping the Line > 0 filter, and letting a posting failure
escape -- so the tests discriminate rather than passing vacuously.

* fix(build): drop the Dockerfile pin assertion

The guard fetched golangci-lint's go.mod at image build time to fail the build
when GOLANGCI_LINT_VERSION and GOFUMPT_VERSION disagreed. It only ever tripped
on self-inflicted pin drift, but it added a network fetch and a new failure
mode to the release build, which is not where that belongs.

The pins stay correct (golangci-lint 2.13.2, whose vendored gofumpt v0.11.0
equals GOFUMPT_VERSION) and the comment above them still states the invariant,
so the reasoning survives without the build-time machinery. The pin change
itself reaches the agent image through the normal release path: CI rebuilds
and pushes archie-agent on an archie/vX.Y.Z release, and a gateway-only
release deliberately does not.

* feat(workflow): add the remediate workflow for PR review remediation

Implements step 5 of docs/prds/pr-review-remediation.md: a remediate
workflow that resumes the task's existing worktree onto its PR branch
(worktree.Manager.Resume, not Prepare's refresh), runs a builder agent
against the review's actionable comments, commits and pushes to the
same branch, and replies via the forge's ReplyToReview. Task.RetryCount
doubles as the remediation round counter, capped by the repo's
max_retries; the round-cap stage parks the task and posts one comment
when it's hit.

Task gains a ReviewPayload field (JSON-encoded review unit) with full
store/proto/staterpc plumbing. workflow.Forger gains Comment and
ReplyToReview, proxied to archie-agent via a new forgerpc RPC. Resume
and its Dir lookup are added as an unexported optional Trees capability
rather than widening the exported interface, which is already at
golangci-lint's interfacebloat cap and is projected into wfextract's
Yaegi symbol table for repository-authored stage plugins.

The daemon-side reaction consumer that dispatches into this workflow
(subscribing ARCHIE_REACTIONS, grouping comments by review, enforcing
per-task serialization) is tracked separately in archie-core-8li9.4.

* feat(messaging): extract standalone messaging service binary and process composition

* feat(messaging): adapt channel frontends to consume Gateway ChatContract

* feat(messaging): remove in-process channels and Router from daemon bootstrap

Telegram, email and webhook now run only in the Messaging Service, which
reaches this process through the Gateway's ChatContract. The daemon builds
no channel and no gateway.Router, so the wiring that existed only to serve
them goes with it: setupGateways, setupEmailGateway, setupWebhookGateway,
setupTelegramGateway, buildTelegramRouter, makeTelegramReload and the
release-announcement path helper.

The seams those paths owned move to where they can still be honoured:

- Channel ValidateConfig runs in archiemessaging.compose, which now returns
  an error, so a configured-but-invalid front-end fails the service rather
  than being dropped silently.
- The inbound rate limiter moves to the Gateway process, which owns the only
  Router and therefore the only place a per-sender budget applies to every
  channel's turns.
- The daemon's gateway readiness probe becomes a ContractProbe against the
  Gateway. It cannot observe a channel lifecycle it no longer runs, and a
  channel-count probe would have reported every daemon degraded.
- telegramSetup is now chatSetup (in chat_setup.go), trimmed to the fields a
  chat turn runner actually reads.

Telegram operator features that were wired only in the daemon (/update,
release announcements, version reporting, SIGHUP reload) are not yet wired
in the Messaging Service: archie-core-8cda.6.6. Channel lifecycle reporting:
archie-core-8cda.6.8. The Gateway process builds no worktree manager, so
review_pr is unadvertised on every channel: archie-core-8cda.6.7.

* feat(messaging): re-wire the Telegram operator surface in the Messaging Service

setupTelegramGateway satisfied eight telegram.Gateway seams from the daemon's
own process. Each is resolved by where the fact it needs is owned, not by
where it used to be built; the decision table is in
docs/architecture/migration-decisions.md.

Wired here: /update (built from this service's own [chat.telegram] check and
install commands), the update-report relay (same sha256(bot_user)[:8] path the
daemon wrote, so a pending report is found rather than written afresh),
show_tool_calls, and /restart's config reload, which re-resolves the token and
allowlist from this service's own file and refuses a reload that resolves to
an empty token.

/version is sourced from the Gateway: ChatSnapshot gains a Version field
carrying the Gateway's rendered build block, read per call and bounded by the
dependency timeout. cmd/archie-messaging deliberately takes no version
ldflags, so it cannot report a partial upgrade as a matched one.

RunningVersions and ReleaseAnnouncements stay nil. Both need a component's
real running version, and the only versions this process can obtain are a
different binary's stamps -- reporting them would manufacture exactly the
false success the update check exists to catch, and the announcer without
parseable versions is a no-op that reads as configured. archie-core-8cda.6.9
carries the contract that unblocks them. Dangerous stays nil: no composition
has ever supplied a command authority.

Enrich is dropped from the update service: componentInstallTypeEnricher read
[nats], which this service must not decode, so the check command's own
reported install type stands.

* fix(workflow): guard inline review comments against head drift

Two findings from the review of q9au.

A comment's line numbers describe exactly one revision of the branch, but the
forge resolved the pull request's head at posting time -- after the review had
already read the worktree. A push in that window (a collaborator, a retry) meant
the findings were anchored to whatever now occupied those lines, mislabelling
instead of failing. The revision the review measured now travels with the
comment set: OpenPR records it from the same worktree read it already performs
(TaskContext.ReviewedHeadSHA), StagePostReviewComments threads it through
Forger to forgerpc, and the forge refuses the whole set once the head it reads
has moved off it -- which the best-effort stage logs, the PR body remaining the
record. An unmeasured revision posts unverified rather than dropping every
finding, so a worktree that cannot report one degrades instead of regressing.

Suggestion was documented single-line only, because GitHub applies a suggestion
fence up to its first line and a multi-line replacement would silently corrupt
the file. Only the verdict was validated, so a multi-line suggestion reached the
renderer and posted as that truncated fence. Validate now rejects an embedded
newline, which makes record_finding refuse it with feedback the model can act on
instead of the reviewer discovering the corruption later.
2026-09-19 23:37:23 +10:00

690 lines
22 KiB
Go

package telegram
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
type modelManagerStub struct {
models []string
active string
}
type detailedModelManagerStub struct {
*modelManagerStub
details map[string]messaging.ModelDetails
}
func (m *detailedModelManagerStub) ModelDetails(ref string) (messaging.ModelDetails, bool) {
details, ok := m.details[ref]
return details, ok
}
func newTestChatFromManager(m *modelManagerStub) *fakeChatContract {
if m == nil {
return &fakeChatContract{}
}
modelsByProvider := make(map[string][]string)
for _, p := range m.Providers() {
modelsByProvider[p] = m.ModelsForProvider(p)
}
return &fakeChatContract{
snapshot: messaging.ChatSnapshot{
Models: m.Models(),
ActiveModel: m.ActiveModel(),
Providers: m.Providers(),
ActiveProvider: m.ActiveProvider(),
ModelsByProvider: modelsByProvider,
},
routeFunc: func(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error) {
text := in.Message.Text
if after, ok := strings.CutPrefix(text, "/model "); ok {
ref := after
if err := m.SetActiveModel(ctx, ref); err != nil {
return messaging.ChatReply{Text: fmt.Sprintf("Cannot switch: %v", err)}, nil
}
return messaging.ChatReply{Text: fmt.Sprintf("Active model set to %s.", ref)}, nil
}
return messaging.ChatReply{Text: "ok"}, nil
},
}
}
func newTestChatFromDetailed(m *detailedModelManagerStub) *fakeChatContract {
chat := newTestChatFromManager(m.modelManagerStub)
chat.details = m.details
return chat
}
func (m *modelManagerStub) Models() []string {
return append([]string(nil), m.models...)
}
func (m *modelManagerStub) ActiveModel() string {
return m.active
}
func (m *modelManagerStub) SetActiveModel(_ context.Context, ref string) error {
if slices.Contains(m.models, ref) {
m.active = ref
return nil
}
return fmt.Errorf("unknown model: %s", ref)
}
func (m *modelManagerStub) Providers() []string {
seen := make(map[string]bool)
var providers []string
for _, model := range m.models {
provider, _, ok := strings.Cut(model, "/")
if ok && !seen[provider] {
seen[provider] = true
providers = append(providers, provider)
}
}
return providers
}
func (m *modelManagerStub) ActiveProvider() string {
provider, _, _ := strings.Cut(m.active, "/")
return provider
}
func (m *modelManagerStub) ModelsForProvider(provider string) []string {
var models []string
for _, model := range m.models {
if strings.HasPrefix(model, provider+"/") {
models = append(models, model)
}
}
return models
}
func (m *modelManagerStub) SetActiveProvider(_ context.Context, provider string) error {
models := m.ModelsForProvider(provider)
if len(models) == 0 {
return fmt.Errorf("unknown provider: %s", provider)
}
m.active = models[0]
return nil
}
type telegramRequest struct {
method string
form map[string]string
}
func newTelegramTestBot(t *testing.T) (*bot.Bot, *[]telegramRequest) {
t.Helper()
var requests []telegramRequest
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(1 << 20); err != nil {
t.Errorf("parse Telegram request: %v", err)
}
form := make(map[string]string, len(r.MultipartForm.Value))
for key, values := range r.MultipartForm.Value {
if len(values) > 0 {
form[key] = values[0]
}
}
requests = append(requests, telegramRequest{
method: r.URL.Path[strings.LastIndexByte(r.URL.Path, '/')+1:],
form: form,
})
w.Header().Set("Content-Type", "application/json")
switch requests[len(requests)-1].method {
case "answerCallbackQuery", "sendChatAction":
_, _ = w.Write([]byte(`{"ok":true,"result":true}`))
default:
_, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":9,"date":1,"chat":{"id":7,"type":"private"}}}`))
}
}))
t.Cleanup(api.Close)
b, err := bot.New(
"1:test",
bot.WithServerURL(api.URL),
bot.WithSkipGetMe(),
bot.WithNotAsyncHandlers(),
)
if err != nil {
t.Fatalf("new test bot: %v", err)
}
return b, &requests
}
func TestModelCommandShowsInlineSelector(t *testing.T) {
const allowedUserID = int64(42)
manager := &modelManagerStub{
models: []string{"provider/alpha", "provider/beta", "other/gamma"},
active: "provider/beta",
}
chat := newTestChatFromManager(manager)
g := New("1:test", []int64{allowedUserID}, slog.Default())
b, requests := newTelegramTestBot(t)
g.defaultHandler(chat)(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/model",
},
})
var markup models.InlineKeyboardMarkup
found := false
for _, request := range *requests {
raw, ok := request.form["reply_markup"]
if request.method != "sendMessage" || !ok {
continue
}
if err := json.Unmarshal([]byte(raw), &markup); err != nil {
t.Fatalf("decode reply markup: %v", err)
}
found = true
}
if !found {
t.Fatalf("/model did not send an inline keyboard; requests: %#v", *requests)
}
if got := len(markup.InlineKeyboard); got != 2 {
t.Fatalf("provider keyboard rows = %d, want provider row and cancel row", got)
}
if got := len(markup.InlineKeyboard[0]); got != 2 {
t.Fatalf("provider buttons = %d, want 2", got)
}
if !strings.Contains(markup.InlineKeyboard[0][0].Text, "(2)") {
t.Errorf("provider button lacks model count: %q", markup.InlineKeyboard[0][0].Text)
}
if !strings.HasPrefix(markup.InlineKeyboard[0][0].Text, "✓ ") {
t.Errorf("active provider button is not marked: %q", markup.InlineKeyboard[0][0].Text)
}
if got := markup.InlineKeyboard[1][0].CallbackData; got != modelCancelCallback {
t.Errorf("provider cancel callback = %q", got)
}
}
func TestModelCommandDrillsFromProviderIntoFilteredModels(t *testing.T) {
const allowedUserID = int64(42)
manager := &modelManagerStub{
models: []string{
"openrouter/openai/gpt-5.6",
"openai/gpt-5.6",
"openai/o3",
},
active: "openrouter/openai/gpt-5.6",
}
chat := newTestChatFromManager(manager)
g := New("1:test", []int64{allowedUserID}, slog.Default())
b, requests := newTelegramTestBot(t)
g.defaultHandler(chat)(context.Background(), b, &models.Update{
Message: &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/model",
},
})
var providerMarkup models.InlineKeyboardMarkup
if err := json.Unmarshal([]byte((*requests)[0].form["reply_markup"]), &providerMarkup); err != nil {
t.Fatal(err)
}
if len(providerMarkup.InlineKeyboard) != 2 || len(providerMarkup.InlineKeyboard[0]) != 2 {
t.Fatalf("provider grid = %#v, want two-column row and cancel", providerMarkup.InlineKeyboard)
}
*requests = nil
providerCallback := providerMarkup.InlineKeyboard[0][1].CallbackData
g.defaultHandler(chat)(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "provider-callback",
From: models.User{ID: allowedUserID},
Data: providerCallback,
Message: models.MaybeInaccessibleMessage{
Type: models.MaybeInaccessibleMessageTypeMessage,
Message: &models.Message{ID: 9, Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}},
},
},
})
if manager.ActiveProvider() != "openrouter" {
t.Fatalf("provider selection changed active model prematurely: %q", manager.ActiveProvider())
}
var modelMarkup models.InlineKeyboardMarkup
for _, request := range *requests {
if raw := request.form["reply_markup"]; raw != "" {
if err := json.Unmarshal([]byte(raw), &modelMarkup); err != nil {
t.Fatal(err)
}
}
}
if len(modelMarkup.InlineKeyboard) != 2 {
t.Fatalf("filtered model rows = %d, want one two-column model row plus navigation", len(modelMarkup.InlineKeyboard))
}
for _, button := range modelMarkup.InlineKeyboard[0] {
model, ok := g.modelForCallback(button.CallbackData)
if !ok {
continue
}
if strings.HasPrefix(model, "openrouter/") {
t.Fatalf("OpenRouter model leaked into OpenAI selection: %q", model)
}
}
}
// TestModelSelectorKeyboardPageAcrossModelCounts covers the sizes that
// actually stress pageBounds and the nav-row logic: none, one (no pairing,
// no nav), exactly one page size (no nav), one over a page (nav appears),
// and enough to need many pages (nav survives past double digits).
func TestModelSelectorKeyboardPageAcrossModelCounts(t *testing.T) {
tests := []struct {
name string
count int
wantPages int
}{
{"zero models", 0, 1},
{"one model", 1, 1},
{"exactly one page", modelPageSize, 1},
{"one over a page", modelPageSize + 1, 2},
{"many pages", 100, (100 + modelPageSize - 1) / modelPageSize},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
manager := &modelManagerStub{}
for i := 0; i < tt.count; i++ {
manager.models = append(manager.models, fmt.Sprintf("provider/model-%02d", i))
}
g := New("1:test", []int64{42}, slog.Default())
page := g.modelSelectorKeyboardPage(manager.ActiveModel(), manager.ModelsForProvider("provider"), "provider", 0)
rows := page.InlineKeyboard
if len(rows) == 0 {
t.Fatalf("no rows returned for %d models", tt.count)
}
actions := rows[len(rows)-1]
if len(actions) != 2 || actions[0].CallbackData != modelBackCallback ||
actions[1].CallbackData != modelCancelCallback {
t.Fatalf("actions row = %#v, want back+cancel", actions)
}
modelButtons := 0
for _, row := range rows[:len(rows)-1] {
for _, button := range row {
if button.CallbackData == modelNoopCallback {
continue
}
if _, isPageLink := g.modelPageForCallback(button.CallbackData); isPageLink {
continue
}
modelButtons++
}
}
if modelButtons != min(tt.count, modelPageSize) {
t.Fatalf("model buttons on first page = %d, want %d", modelButtons, min(tt.count, modelPageSize))
}
hasNav := tt.wantPages > 1
navRowPresent := false
for _, row := range rows[:len(rows)-1] {
for _, button := range row {
if button.CallbackData == modelNoopCallback {
navRowPresent = true
}
}
}
if navRowPresent != hasNav {
t.Fatalf("nav row present = %v, want %v for %d models", navRowPresent, hasNav, tt.count)
}
})
}
}
func TestModelSelectorPageCallbackAdvancesToNextPage(t *testing.T) {
manager := &modelManagerStub{active: "provider/model-09"}
for i := 1; i <= 9; i++ {
manager.models = append(manager.models, fmt.Sprintf("provider/model-%02d", i))
}
g := New("1:test", []int64{42}, slog.Default())
first := g.modelSelectorKeyboardPage(manager.ActiveModel(), manager.ModelsForProvider("provider"), "provider", 0)
nav := first.InlineKeyboard[4]
next, ok := g.modelPageForCallback(nav[1].CallbackData)
if !ok {
t.Fatal("next page callback was not recorded")
}
second := g.modelSelectorKeyboardPage(manager.ActiveModel(), manager.ModelsForProvider(next.Provider), next.Provider, next.Page)
if got := len(second.InlineKeyboard[0]); got != 1 {
t.Fatalf("second page model row = %d buttons, want 1 (nine models, page size eight)", got)
}
if got := second.InlineKeyboard[0][0].Text; got != "✓ model-09" {
t.Fatalf("second page model = %q", got)
}
}
func TestModelSelectionConfirmationIncludesCatalogMetadata(t *testing.T) {
const ref = "google/gemini-3.6-flash"
manager := &detailedModelManagerStub{
modelManagerStub: &modelManagerStub{models: []string{ref}, active: ref},
details: map[string]messaging.ModelDetails{
ref: {
Ref: ref, ContextWindow: 1_048_576, MaxOutputTokens: 65_536,
Reasoning: true, Tools: true, Structured: true,
InputModalities: []string{"text", "image", "audio"},
},
},
}
got := modelSelectionConfirmation(newTestChatFromDetailed(manager), ref)
for _, want := range []string{
"Model switched to gemini-3.6-flash",
"Provider: Google",
"Context: 1048576 tokens",
"Max output: 65536 tokens",
"Capabilities: reasoning, tools, image, audio, structured output",
"active for this daemon process; resets on restart",
} {
if !strings.Contains(got, want) {
t.Errorf("confirmation missing %q:\n%s", want, got)
}
}
}
func TestProviderCallbackHonoursTheProviderRenderedInTheSelector(t *testing.T) {
const allowedUserID = int64(42)
manager := &modelManagerStub{
models: []string{"openai/gpt-5.6", "openrouter/openai/gpt-5.6"},
active: "openai/gpt-5.6",
}
chat := newTestChatFromManager(manager)
g := New("1:test", []int64{allowedUserID}, slog.Default())
b, _ := newTelegramTestBot(t)
markup := g.providerSelectorKeyboard(chat.snapshot.ActiveProvider, chat.snapshot.Providers, chat.snapshot.ModelsByProvider)
renderedCallback := markup.InlineKeyboard[0][0].CallbackData
manager.models = []string{"deepseek/deepseek-v4-pro", "openai/gpt-5.6", "openrouter/openai/gpt-5.6"}
g.handleProviderCallback(context.Background(), b, &models.Update{CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: allowedUserID},
Data: renderedCallback,
}}, chat)
if got := manager.ActiveProvider(); got != "openai" {
t.Errorf("opening a provider page changed active provider to %q", got)
}
}
func TestModelCallbackSwitchesAndUpdatesSelector(t *testing.T) {
const allowedUserID = int64(42)
manager := &modelManagerStub{
models: []string{"provider/alpha", "provider/beta"},
active: "provider/alpha",
}
chat := newTestChatFromManager(manager)
g := New("1:test", []int64{allowedUserID}, slog.Default())
b, requests := newTelegramTestBot(t)
g.defaultHandler(chat)(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: allowedUserID},
Data: g.modelCallbackToken("provider/beta"),
Message: models.MaybeInaccessibleMessage{
Type: models.MaybeInaccessibleMessageTypeMessage,
Message: &models.Message{ID: 9, Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}},
},
},
})
if manager.active != "provider/beta" {
t.Fatalf("active model = %q, want provider/beta", manager.active)
}
var answered, edited bool
for _, request := range *requests {
if request.method == "answerCallbackQuery" {
answered = true
if got := request.form["text"]; got != "The model has been changed to: beta" {
t.Errorf("selection acknowledgement = %q", got)
}
}
if request.method == "editMessageText" {
edited = true
if markup, present := request.form["reply_markup"]; present {
t.Errorf("confirmation edit sent reply_markup=%q, want field omitted", markup)
}
}
}
if !answered || !edited {
t.Fatalf("callback answered=%t edited=%t, requests: %#v", answered, edited, *requests)
}
}
func TestDirectModelSelectionWithProviderIsAtomicOnFailure(t *testing.T) {
const allowedUserID = int64(42)
manager := &modelManagerStub{
models: []string{"openai/gpt-5.6", "anthropic/claude"},
active: "openai/gpt-5.6",
}
chat := newTestChatFromManager(manager)
g := New("1:test", []int64{allowedUserID}, slog.Default())
b, _ := newTelegramTestBot(t)
g.handleModelCommand(context.Background(), b, &models.Message{
From: &models.User{ID: allowedUserID},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
Text: "/model missing --provider anthropic",
}, chat)
if manager.active != "openai/gpt-5.6" {
t.Fatalf("failed selection changed active model to %q", manager.active)
}
}
func TestModelPageIndicatorCallbackIsAnswered(t *testing.T) {
const allowedUserID = int64(42)
g := New("1:test", []int64{allowedUserID}, slog.Default())
b, requests := newTelegramTestBot(t)
g.defaultHandler(&fakeChatContract{})(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "noop-id", From: models.User{ID: allowedUserID}, Data: modelNoopCallback,
},
})
if len(*requests) != 1 || (*requests)[0].method != "answerCallbackQuery" {
t.Fatalf("page indicator requests = %#v, want callback acknowledgement", *requests)
}
}
func TestModelCallbackHonoursTheModelRenderedInTheSelector(t *testing.T) {
const allowedUserID = int64(42)
manager := &modelManagerStub{
models: []string{"openai/gpt-5.6", "openrouter/openai/gpt-5.6"},
active: "openai/gpt-5.6",
}
chat := newTestChatFromManager(manager)
g := New("1:test", []int64{allowedUserID}, slog.Default())
b, _ := newTelegramTestBot(t)
markup := g.modelSelectorKeyboard(chat.snapshot.ActiveModel, chat.snapshot.Models, chat.snapshot.ActiveProvider, chat.snapshot.ModelsByProvider)
renderedCallback := markup.InlineKeyboard[0][0].CallbackData
if err := manager.SetActiveProvider(context.Background(), "openrouter"); err != nil {
t.Fatal(err)
}
g.handleModelCallback(context.Background(), b, &models.Update{CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: allowedUserID},
Data: renderedCallback,
}}, chat)
if got := manager.ActiveModel(); got != "openai/gpt-5.6" {
t.Errorf("stale selector chose %q, want the originally rendered model", got)
}
}
func TestModelCallbackRejectsUnauthorizedAndMalformedSelections(t *testing.T) {
const allowedUserID = int64(42)
tests := []struct {
name string
userID int64
data string
}{
{name: "unauthorized sender", userID: 99, data: "model:1"},
{name: "malformed index", userID: allowedUserID, data: "model:not-an-index"},
{name: "out of range", userID: allowedUserID, data: "model:99"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
manager := &modelManagerStub{
models: []string{"provider/alpha", "provider/beta"},
active: "provider/alpha",
}
chat := newTestChatFromManager(manager)
g := New("1:test", []int64{allowedUserID}, slog.Default())
b, requests := newTelegramTestBot(t)
g.defaultHandler(chat)(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: tt.userID},
Data: tt.data,
},
})
if manager.active != "provider/alpha" {
t.Fatalf("active model changed to %q", manager.active)
}
var answer *telegramRequest
for index := range *requests {
if (*requests)[index].method == "answerCallbackQuery" {
answer = &(*requests)[index]
}
}
if answer == nil || answer.form["show_alert"] != "true" {
t.Fatalf("rejection did not answer with an alert; requests: %#v", *requests)
}
})
}
}
func TestProviderCallbackRejectsUnauthorizedAndMalformedSelections(t *testing.T) {
const allowedUserID = int64(42)
tests := []struct {
name string
userID int64
data string
}{
{name: "unauthorized sender", userID: 99, data: "provider:1"},
{name: "malformed index", userID: allowedUserID, data: "provider:not-an-index"},
{name: "out of range", userID: allowedUserID, data: "provider:99"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
manager := &modelManagerStub{
models: []string{"openrouter/openai/gpt-5.6", "openai/gpt-5.6"},
active: "openrouter/openai/gpt-5.6",
}
chat := newTestChatFromManager(manager)
g := New("1:test", []int64{allowedUserID}, slog.Default())
b, requests := newTelegramTestBot(t)
g.defaultHandler(chat)(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: tt.userID},
Data: tt.data,
},
})
if manager.active != "openrouter/openai/gpt-5.6" {
t.Fatalf("active provider/model changed to %q", manager.active)
}
var answer *telegramRequest
for index := range *requests {
if (*requests)[index].method == "answerCallbackQuery" {
answer = &(*requests)[index]
}
}
if answer == nil || answer.form["show_alert"] != "true" {
t.Fatalf("rejection did not answer with an alert; requests: %#v", *requests)
}
})
}
}
// TestParseModelRestReturnsDeclaredValuesInOrder covers the naked return that a
// nakedret autofix expanded in 6d4e0be. Every result shares a type with at
// least one other -- two strings, three bools -- so a transposed pair compiles
// silently and would surface only as /model switching the wrong scope. Each
// case sets exactly one flag so no pair of bools can swap undetected.
func TestParseModelRestReturnsDeclaredValuesInOrder(t *testing.T) {
tests := []struct {
name string
rest string
model string
provider string
global bool
session bool
refresh bool
}{
{name: "model only", rest: "gpt-5.6", model: "gpt-5.6"},
{name: "inline provider", rest: "gpt-5.6 --provider=openai", model: "gpt-5.6", provider: "openai"},
{name: "separated provider", rest: "gpt-5.6 --provider openai", model: "gpt-5.6", provider: "openai"},
{name: "global scope", rest: "gpt-5.6 --global", model: "gpt-5.6", global: true},
{name: "session scope", rest: "gpt-5.6 --session", model: "gpt-5.6", session: true},
{name: "refresh", rest: "--refresh", refresh: true},
{name: "provider without model", rest: "--provider=openai --global", provider: "openai", global: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
model, provider, global, session, refresh := parseModelRest(tt.rest)
if model != tt.model || provider != tt.provider {
t.Fatalf("parseModelRest(%q) = model %q, provider %q; want %q, %q",
tt.rest, model, provider, tt.model, tt.provider)
}
if global != tt.global || session != tt.session || refresh != tt.refresh {
t.Fatalf("parseModelRest(%q) = global %v, session %v, refresh %v; want %v, %v, %v",
tt.rest, global, session, refresh, tt.global, tt.session, tt.refresh)
}
})
}
}
// TestParseModelRestDoesNotDoubleTheModelName guards the regression introduced
// by the nestif extraction in 651de0a: the extracted helper appended surviving
// fields to a slice the caller then appended to again, so "/model gpt-5.6"
// asked the router for "gpt-5.6 gpt-5.6" and every direct model switch failed
// as an unknown model. A separated provider value was doubled into the name
// too. The assertion is on field count rather than equality so that a future
// re-extraction cannot pass by doubling a different part of the string.
func TestParseModelRestDoesNotDoubleTheModelName(t *testing.T) {
for _, rest := range []string{
"gpt-5.6",
"gpt-5.6 --global",
"gpt-5.6 --provider openai",
"gpt-5.6 --provider=openai --session",
} {
model, _, _, _, _ := parseModelRest(rest)
if fields := strings.Fields(model); len(fields) != 1 {
t.Fatalf("parseModelRest(%q) model = %q; want a single field", rest, model)
}
}
}