diff --git a/internal/app/archied/telegram_setup.go b/internal/app/archied/telegram_setup.go index 7fa8a1169..f8b020a6f 100644 --- a/internal/app/archied/telegram_setup.go +++ b/internal/app/archied/telegram_setup.go @@ -102,7 +102,7 @@ func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), o s.Log.Warn("chat.telegram has no allowed_user_ids: every sender will be rejected. " + "Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.") } - tg := telegram.New(tgToken, "", "", cfg.Chat.Telegram.AllowedUserIDs, s.Log) + tg := telegram.New(tgToken, cfg.Chat.Telegram.AllowedUserIDs, s.Log) if s.RegisterRestart != nil { s.RegisterRestart(tg.RequestRestart) } diff --git a/internal/channels/telegram/approval_test.go b/internal/channels/telegram/approval_test.go index 8a5b2ae2f..1233a4aba 100644 --- a/internal/channels/telegram/approval_test.go +++ b/internal/channels/telegram/approval_test.go @@ -21,7 +21,7 @@ const ( func newApprovalTestGateway(t *testing.T) (*Gateway, *bot.Bot, *[]telegramRequest) { t.Helper() - g := New("1:test", "", "", []int64{approvalTestRecipient}, slog.Default()) + g := New("1:test", []int64{approvalTestRecipient}, slog.Default()) b, requests := newTelegramTestBot(t) return g, b, requests } @@ -266,7 +266,7 @@ func TestApprovalCallbackExpiredTokenRejected(t *testing.T) { func TestApprovalCallbackWrongRecipientRejected(t *testing.T) { const otherUserID = int64(43) - g := New("1:test", "", "", []int64{approvalTestRecipient, otherUserID}, slog.Default()) + g := New("1:test", []int64{approvalTestRecipient, otherUserID}, slog.Default()) b, requests := newTelegramTestBot(t) token := makeDangerousToken() @@ -369,7 +369,7 @@ func TestApprovalPromptText(t *testing.T) { } func TestApprovalKeyboardUsesApprovalPrefix(t *testing.T) { - g := New("1:test", "", "", []int64{approvalTestRecipient}, slog.Default()) + g := New("1:test", []int64{approvalTestRecipient}, slog.Default()) markup := g.approvalKeyboard("token123") if len(markup.InlineKeyboard) != 3 { diff --git a/internal/channels/telegram/dangerous_test.go b/internal/channels/telegram/dangerous_test.go index e7fb60975..894f13c08 100644 --- a/internal/channels/telegram/dangerous_test.go +++ b/internal/channels/telegram/dangerous_test.go @@ -77,7 +77,7 @@ func TestRollbackListsCheckpoints(t *testing.T) { {Number: 1, Timestamp: now.Add(-2 * time.Hour), Label: "Initial checkout", Size: "8 MB"}, }, } - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -103,7 +103,7 @@ func TestRollbackListsCheckpoints(t *testing.T) { func TestRollbackEmptyCheckpoints(t *testing.T) { const allowedUserID = int64(42) stub := &dangerousStub{} // no checkpoints - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -124,7 +124,7 @@ func TestRollbackEmptyCheckpoints(t *testing.T) { func TestRollbackCheckpointError(t *testing.T) { const allowedUserID = int64(42) stub := &dangerousStub{checkpointsErr: fmt.Errorf("storage offline")} - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -147,7 +147,7 @@ func TestRollbackWithNumberRequiresApproval(t *testing.T) { stub := &dangerousStub{ rollbackResult: "Restored to checkpoint 2: 15 files changed, 3 removed.", } - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -213,7 +213,7 @@ func TestRollbackApprovalExecutes(t *testing.T) { stub := &dangerousStub{ rollbackResult: "Restored to checkpoint 2: 15 files changed.", } - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -277,7 +277,7 @@ func TestRollbackApprovalExecutes(t *testing.T) { func TestRollbackWithBadNumber(t *testing.T) { const allowedUserID = int64(42) stub := &dangerousStub{} - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -301,7 +301,7 @@ func TestRollbackWithBadNumber(t *testing.T) { func TestStopRequiresApproval(t *testing.T) { const allowedUserID = int64(42) stub := &dangerousStub{} - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -330,7 +330,7 @@ func TestStopRequiresApproval(t *testing.T) { func TestStopApprovalExecutes(t *testing.T) { const allowedUserID = int64(42) stub := &dangerousStub{} - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -376,7 +376,7 @@ func TestStopApprovalExecutes(t *testing.T) { func TestStopWithNoArgumentDoesNotRequireApproval(t *testing.T) { const allowedUserID = int64(42) stub := &dangerousStub{} - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -404,7 +404,7 @@ func TestStopWithNoArgumentDoesNotRequireApproval(t *testing.T) { // a turn in flight is cancelled, and the queue behind it is discarded. func TestStopCancelsRunningChatTurn(t *testing.T) { const allowedUserID = int64(42) - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) ctx := t.Context() g.turns = gateway.NewTurns(slog.Default()) @@ -441,7 +441,7 @@ func TestDangerousCallbackRejectsUnauthorizedSender(t *testing.T) { stub := &dangerousStub{ rollbackResult: "ok", } - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -483,7 +483,7 @@ func TestDangerousCallbackRejectsUnauthorizedSender(t *testing.T) { func TestDangerousCallbackExpiredToken(t *testing.T) { const allowedUserID = int64(42) stub := &dangerousStub{rollbackResult: "ok"} - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -521,7 +521,7 @@ func TestDangerousCallbackExpiredToken(t *testing.T) { func TestDangerousCallbackSingleUse(t *testing.T) { const allowedUserID = int64(42) stub := &dangerousStub{rollbackResult: "ok"} - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -572,7 +572,7 @@ func TestDangerousCallbackSingleUse(t *testing.T) { func TestDangerousCallbackDeny(t *testing.T) { const allowedUserID = int64(42) stub := &dangerousStub{rollbackResult: "ok"} - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -610,7 +610,7 @@ func TestDangerousCallbackDeny(t *testing.T) { func TestDangerousCallbackExecutionFailure(t *testing.T) { const allowedUserID = int64(42) stub := &dangerousStub{rollbackErr: fmt.Errorf("checkpoint corrupted")} - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -649,7 +649,7 @@ func TestPermanentApprovalSkipsInlineKeyboard(t *testing.T) { stub := &dangerousStub{ rollbackResult: "Restored (permanent approval).", } - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub // Grant permanent approval for rollback. @@ -690,7 +690,7 @@ func TestPermanentApprovalSkipsInlineKeyboard(t *testing.T) { func TestPermanentApprovalExpired(t *testing.T) { const allowedUserID = int64(42) stub := &dangerousStub{rollbackResult: "ok"} - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub // Grant expired permanent approval. @@ -729,7 +729,7 @@ func TestPermanentApprovalButtonGrantsApproval(t *testing.T) { stub := &dangerousStub{ rollbackResult: "Restored after permanent approval grant.", } - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -790,7 +790,7 @@ func TestPermanentApprovalScopedToRecipient(t *testing.T) { const allowedUserID = int64(42) const otherUserID = int64(99) stub := &dangerousStub{rollbackResult: "ok"} - g := New("1:test", "", "", []int64{allowedUserID, otherUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID, otherUserID}, slog.Default()) g.Dangerous = stub // Grant permanent approval for user 42. @@ -824,7 +824,7 @@ func TestPermanentApprovalScopedToRecipient(t *testing.T) { func TestApproveHandlerShowsPendingCommands(t *testing.T) { const allowedUserID = int64(42) stub := &dangerousStub{} - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub // Register a pending command. @@ -854,7 +854,7 @@ func TestApproveHandlerShowsPendingCommands(t *testing.T) { func TestApproveHandlerNoPendingCommands(t *testing.T) { const allowedUserID = int64(42) stub := &dangerousStub{} - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) @@ -875,7 +875,7 @@ func TestApproveHandlerNoPendingCommands(t *testing.T) { func TestRollbackNotConfigured(t *testing.T) { const allowedUserID = int64(42) - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) // Dangerous is nil. b, requests := newTelegramTestBot(t) @@ -895,7 +895,7 @@ func TestRollbackNotConfigured(t *testing.T) { func TestStopNotConfigured(t *testing.T) { const allowedUserID = int64(42) - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) // Dangerous is nil. b, requests := newTelegramTestBot(t) @@ -917,7 +917,7 @@ func TestDangerousCommandHelpContainsNewCommands(t *testing.T) { const allowedUserID = int64(42) var sentText string - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) b, requests := newTelegramTestBot(t) g.helpHandler()(context.Background(), b, &models.Update{ @@ -994,7 +994,7 @@ func TestDangerousCallbackRejectsWrongRecipient(t *testing.T) { const allowedUserID = int64(42) const otherUserID = int64(43) stub := &dangerousStub{rollbackResult: "ok"} - g := New("1:test", "", "", []int64{allowedUserID, otherUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID, otherUserID}, slog.Default()) g.Dangerous = stub b, _ := newTelegramTestBot(t) @@ -1019,7 +1019,7 @@ func TestDangerousCallbackRejectsWrongRecipient(t *testing.T) { func TestMalformedDangerousCallback(t *testing.T) { const allowedUserID = int64(42) stub := &dangerousStub{} - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Dangerous = stub b, requests := newTelegramTestBot(t) diff --git a/internal/channels/telegram/live_test.go b/internal/channels/telegram/live_test.go index 7fce387f0..575b8b0fd 100644 --- a/internal/channels/telegram/live_test.go +++ b/internal/channels/telegram/live_test.go @@ -97,7 +97,7 @@ func fakeAPI(t *testing.T) (*bot.Bot, *[]apiCall) { func newTestLiveReply(t *testing.T, showToolCalls bool) (*liveReply, *[]apiCall) { t.Helper() b, calls := fakeAPI(t) - g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler)) g.SetShowToolCalls(showToolCalls) live := g.newLiveReply(context.Background(), b, 7, 0, g.ShowToolCalls()) t.Cleanup(live.stopRendering) @@ -393,7 +393,7 @@ func TestLiveReplyOpenFallsBackToPlainText(t *testing.T) { if err != nil { t.Fatalf("new test bot: %v", err) } - g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler)) live := g.newLiveReply(context.Background(), b, 7, 0, false) t.Cleanup(live.stopRendering) live.interval = 0 @@ -431,7 +431,7 @@ func TestLiveReplyEditFallsBackToPlainText(t *testing.T) { if err != nil { t.Fatalf("new test bot: %v", err) } - g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler)) live := g.newLiveReply(context.Background(), b, 7, 0, g.ShowToolCalls()) t.Cleanup(live.stopRendering) live.interval = 0 @@ -472,7 +472,7 @@ func TestLiveReplyCallbacksDoNotWaitForTelegram(t *testing.T) { if err != nil { t.Fatalf("new test bot: %v", err) } - g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler)) g.SetShowToolCalls(true) live := g.newLiveReply(context.Background(), b, 7, 0, g.ShowToolCalls()) t.Cleanup(live.stopRendering) @@ -514,7 +514,7 @@ func TestLiveReplyStopCancelsInFlightRendering(t *testing.T) { if err != nil { t.Fatalf("new test bot: %v", err) } - g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler)) ctx, cancel := context.WithCancel(context.Background()) live := g.newLiveReply(ctx, b, 7, 0, false) t.Cleanup(live.stopRendering) @@ -555,7 +555,7 @@ func TestLiveReplyFinalEditFailureSendsAuthoritativeReplyNormally(t *testing.T) if err != nil { t.Fatalf("new test bot: %v", err) } - g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler)) live := g.newLiveReply(context.Background(), b, 7, 0, g.ShowToolCalls()) t.Cleanup(live.stopRendering) live.interval = 0 @@ -865,7 +865,7 @@ func TestGatewayAbandonAllLiveDoesNotBlockOnAHungReply(t *testing.T) { if err != nil { t.Fatalf("new test bot: %v", err) } - g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler)) g.liveDrainTimeout = 50 * time.Millisecond live := g.newLiveReply(context.Background(), b, 7, 0, false) @@ -910,7 +910,7 @@ func TestGatewayRegisterLiveAfterStopAbandonsImmediately(t *testing.T) { t.Fatalf("new test bot: %v", err) } - g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler)) g.liveMu.Lock() g.liveStopped = true g.liveMu.Unlock() @@ -980,7 +980,7 @@ func TestLiveReplyMediaFallsBackToALinkOnFailure(t *testing.T) { t.Fatalf("new test bot: %v", err) } - g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler)) live := g.newLiveReply(context.Background(), b, 7, 0, false) t.Cleanup(live.stopRendering) live.interval = 0 diff --git a/internal/channels/telegram/media_test.go b/internal/channels/telegram/media_test.go index 18ffbb7b7..b3c6b9bde 100644 --- a/internal/channels/telegram/media_test.go +++ b/internal/channels/telegram/media_test.go @@ -102,7 +102,7 @@ func newTestMediaSender(t *testing.T, serverURL string, chatID int64, threadID i if err != nil { t.Fatalf("new test bot: %v", err) } - g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler)) return g.NewMediaSender(b, chatID, threadID) } diff --git a/internal/channels/telegram/model_test.go b/internal/channels/telegram/model_test.go index dd4fca872..6480b22d6 100644 --- a/internal/channels/telegram/model_test.go +++ b/internal/channels/telegram/model_test.go @@ -139,7 +139,7 @@ func TestModelCommandShowsInlineSelector(t *testing.T) { } router := gateway.NewRouter(nil, nil, "telegram") router.Models = manager - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) b, requests := newTelegramTestBot(t) g.defaultHandler(router)(context.Background(), b, &models.Update{ @@ -194,7 +194,7 @@ func TestModelCommandDrillsFromProviderIntoFilteredModels(t *testing.T) { } router := gateway.NewRouter(nil, nil, "telegram") router.Models = manager - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) b, requests := newTelegramTestBot(t) g.defaultHandler(router)(context.Background(), b, &models.Update{ @@ -274,7 +274,7 @@ func TestModelSelectorKeyboardPageAcrossModelCounts(t *testing.T) { 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()) + g := New("1:test", []int64{42}, slog.Default()) page := g.modelSelectorKeyboardPage(manager, "provider", 0) rows := page.InlineKeyboard @@ -325,7 +325,7 @@ func TestModelSelectorPageCallbackAdvancesToNextPage(t *testing.T) { 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()) + g := New("1:test", []int64{42}, slog.Default()) first := g.modelSelectorKeyboardPage(manager, "provider", 0) nav := first.InlineKeyboard[4] @@ -379,7 +379,7 @@ func TestProviderCallbackHonoursTheProviderRenderedInTheSelector(t *testing.T) { } router := gateway.NewRouter(nil, nil, "telegram") router.Models = manager - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) b, _ := newTelegramTestBot(t) markup := g.providerSelectorKeyboard(manager) @@ -405,7 +405,7 @@ func TestModelCallbackSwitchesAndUpdatesSelector(t *testing.T) { } router := gateway.NewRouter(nil, nil, "telegram") router.Models = manager - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) b, requests := newTelegramTestBot(t) g.defaultHandler(router)(context.Background(), b, &models.Update{ @@ -451,7 +451,7 @@ func TestDirectModelSelectionWithProviderIsAtomicOnFailure(t *testing.T) { } router := gateway.NewRouter(nil, nil, "telegram") router.Models = manager - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) b, _ := newTelegramTestBot(t) g.handleModelCommand(context.Background(), b, &models.Message{ @@ -467,7 +467,7 @@ func TestDirectModelSelectionWithProviderIsAtomicOnFailure(t *testing.T) { func TestModelPageIndicatorCallbackIsAnswered(t *testing.T) { const allowedUserID = int64(42) - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) b, requests := newTelegramTestBot(t) g.defaultHandler(gateway.NewRouter(nil, nil, "telegram"))(context.Background(), b, &models.Update{ @@ -489,7 +489,7 @@ func TestModelCallbackHonoursTheModelRenderedInTheSelector(t *testing.T) { } router := gateway.NewRouter(nil, nil, "telegram") router.Models = manager - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) b, _ := newTelegramTestBot(t) markup := g.modelSelectorKeyboard(manager) @@ -528,7 +528,7 @@ func TestModelCallbackRejectsUnauthorizedAndMalformedSelections(t *testing.T) { } router := gateway.NewRouter(nil, nil, "telegram") router.Models = manager - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) b, requests := newTelegramTestBot(t) g.defaultHandler(router)(context.Background(), b, &models.Update{ @@ -574,7 +574,7 @@ func TestProviderCallbackRejectsUnauthorizedAndMalformedSelections(t *testing.T) } router := gateway.NewRouter(nil, nil, "telegram") router.Models = manager - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) b, requests := newTelegramTestBot(t) g.defaultHandler(router)(context.Background(), b, &models.Update{ diff --git a/internal/channels/telegram/restart_test.go b/internal/channels/telegram/restart_test.go index 9feb1ee5e..40610fb1d 100644 --- a/internal/channels/telegram/restart_test.go +++ b/internal/channels/telegram/restart_test.go @@ -11,7 +11,7 @@ import ( ) func TestRestartAcknowledgesArchie(t *testing.T) { - g := New("1:test", "", "", []int64{42}, slog.Default()) + g := New("1:test", []int64{42}, slog.Default()) b, requests := newTelegramTestBot(t) g.restartHandler()(context.Background(), b, &models.Update{Message: &models.Message{ @@ -35,7 +35,7 @@ func TestRestartAcknowledgesArchie(t *testing.T) { // blocking: the handler runs on the very bot the supervisor is about to // stop, so blocking there would deadlock the restart it just asked for. func TestRestartRequestNeverBlocksHandler(t *testing.T) { - g := New("tok", "", "", []int64{1}, slog.Default()) + g := New("tok", []int64{1}, slog.Default()) done := make(chan struct{}) go func() { @@ -61,7 +61,7 @@ func TestRestartRequestNeverBlocksHandler(t *testing.T) { } func TestRequestRestartQueuesScopedReload(t *testing.T) { - g := New("tok", "", "", []int64{1}, slog.Default()) + g := New("tok", []int64{1}, slog.Default()) if err := g.RequestRestart(); err != nil { t.Fatalf("RequestRestart: %v", err) } @@ -76,7 +76,7 @@ func TestRequestRestartQueuesScopedReload(t *testing.T) { // A failing Reload must not be fatal: a bad config edit should leave the // gateway running on its previous settings, not take chat down for good. func TestReloadFailureKeepsPreviousSettings(t *testing.T) { - g := New("original-token", "", "", []int64{1}, slog.Default()) + g := New("original-token", []int64{1}, slog.Default()) g.Reload = func(*Gateway) error { return errReloadTest } if err := g.Reload(g); err == nil { diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index 8e9799fd6..617a0b21c 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -28,9 +28,7 @@ import ( // Gateway is a Telegram gateway.Gateway backed by go-telegram/bot. type Gateway struct { - Token string - WebhookURL string - WebhookSecret string + Token string // AllowedUserIDs lists the Telegram user IDs allowed to use the bot, // matched against the sender rather than the chat so the bot cannot be // reached by adding it to a group. Empty denies everyone: a bot handle @@ -132,10 +130,9 @@ type Gateway struct { // false at the start of the next launch. liveStopped bool - log *slog.Logger - bot *bot.Bot - webhookCancel context.CancelFunc - running bool + log *slog.Logger + bot *bot.Bot + running bool // serverURL redirects the Bot API at a test server. Empty in production, // where the library's default endpoint is used. It exists so launch's @@ -158,13 +155,10 @@ type ReleaseAnnouncer interface { ) error } -// New returns an unstarted Gateway. Call Start to begin webhook -// processing. -func New(token, webhookURL, webhookSecret string, allowedUserIDs []int64, log *slog.Logger) *Gateway { +// New returns an unstarted Gateway. Call Start to begin long-polling. +func New(token string, allowedUserIDs []int64, log *slog.Logger) *Gateway { return &Gateway{ Token: token, - WebhookURL: webhookURL, - WebhookSecret: webhookSecret, AllowedUserIDs: allowedUserIDs, restartCh: make(chan restartRequest, 1), modelCallbacks: make(map[string]string), @@ -270,49 +264,16 @@ func (g *Gateway) registerCommandHandlers(b *bot.Bot, router *gateway.Router) { b.RegisterHandler(bot.HandlerTypeMessageText, "/deny", bot.MatchTypeExact, g.denyHandler()) } -func (g *Gateway) startListening(ctx context.Context, b *bot.Bot, lifecycle gateway.Lifecycle) error { - if g.WebhookURL != "" { - params := &bot.SetWebhookParams{ - URL: g.WebhookURL, - SecretToken: g.WebhookSecret, - MaxConnections: 40, - AllowedUpdates: []string{"message", "callback_query"}, - DropPendingUpdates: true, - } - if _, err := b.SetWebhook(ctx, params); err != nil { - return fmt.Errorf("set webhook: %w", err) - } - g.log.Info("webhook set", "url", g.WebhookURL) - - info, err := b.GetWebhookInfo(ctx) - if err != nil { - g.log.Warn("failed to get webhook info", "error", err) - } else { - g.log.Info( - "webhook info", - "url", info.URL, - "pending_update_count", info.PendingUpdateCount, - "last_error_message", info.LastErrorMessage, - "max_connections", info.MaxConnections, - ) - } - - webhookCtx, cancel := context.WithCancel(ctx) - g.webhookCancel = cancel - g.running = true - go b.StartWebhook(webhookCtx) - lifecycle.ReportRunning() - } else { - g.dropPendingUpdates(ctx, b) - g.running = true - go b.Start(ctx) - } +func (g *Gateway) startListening(ctx context.Context, b *bot.Bot, _ gateway.Lifecycle) error { + g.dropPendingUpdates(ctx, b) + g.running = true + go b.Start(ctx) return nil } -// launch builds one bot instance, registers handlers and starts its delivery -// worker. Webhook readiness is synchronous; long-poll readiness is reported by -// pollReadinessClient after the first successful getUpdates response. +// launch builds one bot instance, registers handlers and starts its +// long-poll delivery worker. Readiness is reported by pollReadinessClient +// after the first successful getUpdates response. func (g *Gateway) launch(ctx context.Context, router *gateway.Router, lifecycle gateway.Lifecycle) (*bot.Bot, error) { // Turns are per-launch. Each queued turn carries the update handler's // context, which is this launch's, so a /restart cancels everything @@ -327,15 +288,10 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router, lifecycle }), bot.WithDefaultHandler(g.defaultHandler(router)), bot.WithMiddlewares(g.panicRecoveryMiddleware(), g.updateLoggingMiddleware()), - } - if g.WebhookSecret != "" { - opts = append(opts, bot.WithWebhookSecretToken(g.WebhookSecret)) - } - if g.WebhookURL == "" { - opts = append(opts, bot.WithHTTPClient(telegramPollTimeout, &pollReadinessClient{ + bot.WithHTTPClient(telegramPollTimeout, &pollReadinessClient{ client: &http.Client{Timeout: telegramPollTimeout}, onRunning: lifecycle.ReportRunning, - })) + }), } if g.serverURL != "" { opts = append(opts, bot.WithServerURL(g.serverURL), bot.WithSkipGetMe()) @@ -410,7 +366,7 @@ func (g *Gateway) announceRelease(ctx context.Context, b *bot.Bot) { } } -// Stop gracefully shuts down the bot and deletes the webhook. +// Stop gracefully shuts down the bot. func (g *Gateway) Stop(ctx context.Context) error { if !g.running { return nil @@ -420,28 +376,9 @@ func (g *Gateway) Stop(ctx context.Context) error { g.abandonAllLive(ctx) - if g.webhookCancel != nil { - g.webhookCancel() - g.webhookCancel = nil - } - if g.WebhookURL != "" && g.bot != nil { - if _, err := g.bot.DeleteWebhook(ctx, &bot.DeleteWebhookParams{DropPendingUpdates: true}); err != nil { - g.log.Warn("error deleting webhook", "error", err) - } - } return nil } -// WebhookHandler returns the HTTP handler for Telegram webhooks. -func (g *Gateway) WebhookHandler() http.Handler { - if g.bot == nil { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.Error(w, "bot not initialized", http.StatusServiceUnavailable) - }) - } - return g.bot.WebhookHandler() -} - // ── command handlers (gateway-local -- no LLM) ──────────────── func (g *Gateway) statusHandler(router *gateway.Router) bot.HandlerFunc { @@ -904,14 +841,6 @@ func (g *Gateway) ConfigSchema() json.RawMessage { "type": "string", "description": "Environment variable holding the Telegram bot token from @BotFather" }, - "webhook_url": { - "type": "string", - "description": "Public HTTPS URL for Telegram webhook delivery" - }, - "webhook_secret": { - "type": "string", - "description": "Secret token for webhook validation" - }, "allowed_chat_ids": { "type": "array", "items": { "type": "integer" }, diff --git a/internal/channels/telegram/telegram_test.go b/internal/channels/telegram/telegram_test.go index 7df003011..a077331aa 100644 --- a/internal/channels/telegram/telegram_test.go +++ b/internal/channels/telegram/telegram_test.go @@ -19,20 +19,17 @@ import ( ) func TestName(t *testing.T) { - g := New("token", "", "", nil, slog.Default()) + g := New("token", nil, slog.Default()) if got := g.Name(); got != "telegram" { t.Errorf("Name() = %q, want telegram", got) } } func TestNewStoresFields(t *testing.T) { - g := New("abc123", "https://example.com/webhook", "secret", []int64{42}, slog.Default()) + g := New("abc123", []int64{42}, slog.Default()) if g.Token != "abc123" { t.Errorf("Token = %q", g.Token) } - if g.WebhookURL != "https://example.com/webhook" { - t.Errorf("WebhookURL = %q", g.WebhookURL) - } if len(g.AllowedUserIDs) != 1 || g.AllowedUserIDs[0] != 42 { t.Errorf("AllowedUserIDs = %v", g.AllowedUserIDs) } @@ -67,7 +64,7 @@ func TestHelpDescribesPublishedCommandsAndChat(t *testing.T) { if err != nil { t.Fatalf("new test bot: %v", err) } - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.helpHandler()(context.Background(), b, &models.Update{ Message: &models.Message{ From: &models.User{ID: allowedUserID}, @@ -133,7 +130,7 @@ func TestCommandSurfaceUsesOneModelSelectorAndUsefulHelpCopy(t *testing.T) { func TestStartHasDeterministicGatewayResponse(t *testing.T) { const allowedUserID = int64(42) - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) b, requests := newTelegramTestBot(t) g.startHandler()(context.Background(), b, &models.Update{ @@ -158,7 +155,7 @@ func TestStartHasDeterministicGatewayResponse(t *testing.T) { func TestVersionReportsBothComponents(t *testing.T) { const allowedUserID = int64(42) - g := New("1:test", "", "", []int64{allowedUserID}, slog.Default()) + g := New("1:test", []int64{allowedUserID}, slog.Default()) g.Version = func() string { return "Archie\nGateway: v1.2.3\nRuntime: v4.5.6" } b, requests := newTelegramTestBot(t) @@ -194,7 +191,7 @@ func (s *releaseAnnouncerStub) Announce( func TestReleaseAnnouncementTargetsAuthorizedUsers(t *testing.T) { const message = "Archie has just been updated to v0.2.0" announcer := &releaseAnnouncerStub{message: message} - g := New("1:test", "", "", []int64{7, 8}, slog.Default()) + g := New("1:test", []int64{7, 8}, slog.Default()) g.ReleaseAnnouncements = announcer b, requests := newTelegramTestBot(t) @@ -217,10 +214,10 @@ func TestReleaseAnnouncementTargetsAuthorizedUsers(t *testing.T) { // The allowlist must fail closed: a bot handle is public, so an unset // allowlist has to deny rather than admit everyone. func TestSenderAllowlistFailsClosed(t *testing.T) { - if New("t", "", "", nil, slog.Default()).isSenderAllowed(100000000) { + if New("t", nil, slog.Default()).isSenderAllowed(100000000) { t.Error("empty allowlist must deny every sender") } - g := New("t", "", "", []int64{100000000}, slog.Default()) + g := New("t", []int64{100000000}, slog.Default()) if !g.isSenderAllowed(100000000) { t.Error("listed sender must be allowed") } @@ -230,7 +227,7 @@ func TestSenderAllowlistFailsClosed(t *testing.T) { } func TestStartWithoutToken(t *testing.T) { - g := New("", "", "", nil, slog.Default()) + g := New("", nil, slog.Default()) router := gateway.NewRouter(nil, nil, "telegram") ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel() @@ -263,7 +260,7 @@ func TestStartReportsRunningAfterLaunch(t *testing.T) { })) defer api.Close() - g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler)) g.serverURL = api.URL ctx, cancel := context.WithCancel(t.Context()) started := make(chan bool, 1) @@ -310,7 +307,7 @@ func TestStartReportsStartingOnRestart(t *testing.T) { })) defer api.Close() - g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler)) g.serverURL = api.URL ctx, cancel := context.WithCancel(t.Context()) events := make(chan string, 4) @@ -348,15 +345,6 @@ func wantEvent(t *testing.T, events <-chan string, want string) { } } -func TestWebhookHandlerReturns503WhenNotStarted(t *testing.T) { - g := New("token", "", "", nil, slog.Default()) - rec := httptest.NewRecorder() - g.WebhookHandler().ServeHTTP(rec, httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/", nil)) - if rec.Code != http.StatusServiceUnavailable { - t.Errorf("status = %d, want 503", rec.Code) - } -} - func TestStartAndStopLifecycle(t *testing.T) { // Use a noop webhook server so the bot can initialize without hitting // the real Telegram API. @@ -367,7 +355,7 @@ func TestStartAndStopLifecycle(t *testing.T) { defer api.Close() log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})) - g := New("test-token", "", "", nil, log) + g := New("test-token", nil, log) // Override the API base URL -- the go-telegram/bot library uses // https://api.telegram.org by default. We want it to hit our test @@ -405,10 +393,10 @@ var ( // ── Regression tests for previously untested paths ──────────────────── func TestIsSenderAllowed(t *testing.T) { - g := New("tok", "", "", []int64{100, 200, 300}, slog.Default()) + g := New("tok", []int64{100, 200, 300}, slog.Default()) t.Run("empty allowlist denies all", func(t *testing.T) { - g2 := New("tok", "", "", nil, slog.Default()) + g2 := New("tok", nil, slog.Default()) if g2.isSenderAllowed(999999) { t.Error("empty allowlist must deny every sender, not admit them") } @@ -429,7 +417,7 @@ func TestIsSenderAllowed(t *testing.T) { }) t.Run("zero and negative ids", func(t *testing.T) { - g3 := New("tok", "", "", []int64{-1, 0, 1}, slog.Default()) + g3 := New("tok", []int64{-1, 0, 1}, slog.Default()) if !g3.isSenderAllowed(-1) || !g3.isSenderAllowed(0) { t.Error("explicitly listed -1 and 0 should be allowed") } @@ -486,7 +474,7 @@ func TestUpdateMetadata(t *testing.T) { } func TestPanicRecoveryMiddlewareDoesNotCrash(t *testing.T) { - g := New("tok", "", "", nil, slog.Default()) + g := New("tok", nil, slog.Default()) mw := g.panicRecoveryMiddleware() handler := mw(func(ctx context.Context, b *bot.Bot, update *models.Update) { panic("test panic") @@ -499,7 +487,7 @@ func TestPanicRecoveryMiddlewareDoesNotCrash(t *testing.T) { } func TestUpdateLoggingMiddlewareCallsInner(t *testing.T) { - g := New("tok", "", "", nil, slog.Default()) + g := New("tok", nil, slog.Default()) mw := g.updateLoggingMiddleware() called := false handler := mw(func(ctx context.Context, b *bot.Bot, update *models.Update) { @@ -515,7 +503,7 @@ func TestUpdateLoggingMiddlewareCallsInner(t *testing.T) { } func TestAuthorizedMessageNilMessage(t *testing.T) { - g := New("tok", "", "", []int64{42}, slog.Default()) + g := New("tok", []int64{42}, slog.Default()) msg, ok := g.authorizedMessage(context.Background(), nil, &models.Update{ID: 1}) if ok || msg != nil { t.Error("nil message should return false, nil") @@ -523,7 +511,7 @@ func TestAuthorizedMessageNilMessage(t *testing.T) { } func TestGatewayStopWhenNotRunning(t *testing.T) { - g := New("tok", "", "", nil, slog.Default()) + g := New("tok", nil, slog.Default()) if err := g.Stop(context.Background()); err != nil { t.Errorf("unexpected error stopping unstarted gateway: %v", err) } @@ -573,7 +561,7 @@ func TestDropPendingUpdatesClearsTheBacklog(t *testing.T) { if err != nil { t.Fatalf("new test bot: %v", err) } - g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler)) g.dropPendingUpdates(context.Background(), b) if !strings.Contains(gotPath, "deleteWebhook") { @@ -599,7 +587,7 @@ func TestDropPendingUpdatesSurvivesAPIFailure(t *testing.T) { t.Fatalf("new test bot: %v", err) } var logged strings.Builder - g := New("1:test", "", "", []int64{42}, slog.New(slog.NewTextHandler(&logged, nil))) + g := New("1:test", []int64{42}, slog.New(slog.NewTextHandler(&logged, nil))) g.dropPendingUpdates(context.Background(), b) // must not panic or block if !strings.Contains(logged.String(), "could not drop pending telegram updates") { @@ -625,7 +613,7 @@ func TestLaunchDropsPendingUpdatesBeforePolling(t *testing.T) { })) defer api.Close() - g := New("1:test", "", "", []int64{42}, slog.New(slog.DiscardHandler)) + g := New("1:test", []int64{42}, slog.New(slog.DiscardHandler)) g.serverURL = api.URL ctx, cancel := context.WithCancel(context.Background()) diff --git a/internal/channels/telegram/update_test.go b/internal/channels/telegram/update_test.go index 76daefccc..268408570 100644 --- a/internal/channels/telegram/update_test.go +++ b/internal/channels/telegram/update_test.go @@ -17,7 +17,7 @@ import ( var errFixtureInstall = errors.New("build failed: exit status 1") func TestUpdateShowsComponentSectionsAndActions(t *testing.T) { - g := New("1:test", "", "", []int64{42}, slog.Default()) + g := New("1:test", []int64{42}, slog.Default()) g.Updates = &updateStub{snapshot: releaseupdate.Snapshot{Components: []releaseupdate.Component{ {ID: "gateway", Label: "THE GATEWAY", Installed: "v0.1.0", Available: "v0.1.1", Changelog: "- Clearer help"}, {ID: "runtime", Label: "THE RUNTIME", Installed: "v0.1.0"}, @@ -47,7 +47,7 @@ func TestUpdateShowsComponentSectionsAndActions(t *testing.T) { // restarted yet when this message is sent, so it can only promise that the // build/install step succeeded and a restart is queued. func TestInstallUpdateStreamsProgressAndReportsSuccess(t *testing.T) { - g := New("1:test", "", "", []int64{42}, slog.Default()) + g := New("1:test", []int64{42}, slog.Default()) stub := &updateStub{ progressText: []string{"==> fetching", "==> building"}, result: releaseupdate.Result{ @@ -88,7 +88,7 @@ func TestInstallUpdateStreamsProgressAndReportsSuccess(t *testing.T) { // because the reference script never reaches the restart step on a // non-zero exit. func TestInstallUpdateReportsBuildFailureWithoutClaimingRestart(t *testing.T) { - g := New("1:test", "", "", []int64{42}, slog.Default()) + g := New("1:test", []int64{42}, slog.Default()) stub := &updateStub{installErr: errFixtureInstall} g.Updates = stub b, requests := newTelegramTestBot(t) @@ -123,7 +123,7 @@ func TestReportPendingUpdateSendsAndClearsReport(t *testing.T) { if err := releaseupdate.WritePendingReport(path, report); err != nil { t.Fatal(err) } - g := New("1:test", "", "", []int64{42}, slog.Default()) + g := New("1:test", []int64{42}, slog.Default()) g.UpdateReportPath = path b, requests := newTelegramTestBot(t) @@ -150,7 +150,7 @@ func TestReportPendingUpdateClearsUnreadableReport(t *testing.T) { if err := os.WriteFile(path, []byte("{not valid json"), 0o600); err != nil { t.Fatal(err) } - g := New("1:test", "", "", []int64{42}, slog.Default()) + g := New("1:test", []int64{42}, slog.Default()) g.UpdateReportPath = path b, _ := newTelegramTestBot(t) @@ -162,7 +162,7 @@ func TestReportPendingUpdateClearsUnreadableReport(t *testing.T) { } func TestReportPendingUpdateNoFileIsNoop(t *testing.T) { - g := New("1:test", "", "", []int64{42}, slog.Default()) + g := New("1:test", []int64{42}, slog.Default()) g.UpdateReportPath = filepath.Join(t.TempDir(), "does-not-exist.json") b, requests := newTelegramTestBot(t) @@ -174,7 +174,7 @@ func TestReportPendingUpdateNoFileIsNoop(t *testing.T) { } func TestReportPendingUpdateDisabledWhenPathEmpty(t *testing.T) { - g := New("1:test", "", "", []int64{42}, slog.Default()) + g := New("1:test", []int64{42}, slog.Default()) b, requests := newTelegramTestBot(t) g.reportPendingUpdate(context.Background(), b) @@ -375,7 +375,7 @@ func TestFormatPendingReportDistinguishesUnrolledBackFailure(t *testing.T) { } func TestUpdateCallbackRejectsUnauthorizedSender(t *testing.T) { - g := New("1:test", "", "", []int64{42}, slog.Default()) + g := New("1:test", []int64{42}, slog.Default()) g.Updates = &updateStub{} b, requests := newTelegramTestBot(t) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 8f0b82c01..a233e870c 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -138,13 +138,6 @@ type UpdateService interface { CanInstall() bool } -// DangerousApprover is the adapter-neutral decision surface for pending -// sandbox actions. Numeric /approve arguments remain task approvals; action -// IDs are routed here when this capability is present. -type DangerousApprover interface { - Decide(context.Context, string, string) (string, error) -} - // TaskController approves or cancels a chat-originated task. Both // methods must enforce authorization (identity must own the task) and // valid state transitions; see gateway.tasks.go's StoreTaskController @@ -213,8 +206,6 @@ type Router struct { Version string // Updates handles the shared /update command. Nil means unavailable. Updates UpdateService - // Dangerous handles typed approval decisions for sandbox actions. - Dangerous DangerousApprover // Restart requests a scoped chat-adapter reload. It deliberately does not // restart the daemon; Telegram's /restart has this same boundary. Restart func(context.Context) error @@ -334,10 +325,7 @@ func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, text, reply, err := r.handleSpawn(ctx, rest) return reply, true, err case "/approve": - reply, err := r.handleApproveCommand(ctx, rest) - return reply, true, err - case "/deny": - reply, err := r.handleDeny(ctx, rest) + reply, err := r.handleApprove(ctx, rest) return reply, true, err case "/cancel": reply, err := r.handleCancel(ctx, rest) @@ -384,22 +372,6 @@ func (r *Router) dispatchLocalMisc(ctx context.Context, msg messaging.Message, c return r.dispatchSessionCommand(ctx, msg, cmd, rest) } -// handleDeny denies a pending dangerous action by ID. -func (r *Router) handleDeny(ctx context.Context, rest string) (string, error) { - if r.Dangerous == nil { - return "Dangerous approvals are not configured.", nil - } - fields := strings.Fields(rest) - if len(fields) != 1 { - return "Usage: /deny ", nil - } - result, err := r.Dangerous.Decide(ctx, fields[0], "deny") - if err != nil { - return fmt.Sprintf("Cannot deny action: %v", err), nil - } - return result, nil -} - // handleVersion reports the configured build version. func (r *Router) handleVersion() string { if r.Version == "" { @@ -611,30 +583,6 @@ func parseTaskID(arg string) (int64, error) { return id, nil } -func (r *Router) handleApproveCommand(ctx context.Context, rest string) (string, error) { - fields := strings.Fields(rest) - if r.Dangerous != nil && len(fields) == 1 && !isTaskID(fields[0]) { - result, err := r.Dangerous.Decide(ctx, fields[0], "approve") - if err != nil { - return fmt.Sprintf("Cannot approve action: %v", err), nil - } - return result, nil - } - if r.Dangerous != nil && len(fields) == 2 && strings.EqualFold(fields[0], "permanent") { - result, err := r.Dangerous.Decide(ctx, fields[1], "permanent") - if err != nil { - return fmt.Sprintf("Cannot approve action: %v", err), nil - } - return result, nil - } - return r.handleApprove(ctx, rest) -} - -func isTaskID(value string) bool { - _, err := strconv.ParseInt(value, 10, 64) - return err == nil -} - func (r *Router) handleApprove(ctx context.Context, rest string) (string, error) { if r.Controller == nil { return "Task control is not configured.", nil diff --git a/internal/gateway/session_state.go b/internal/gateway/session_state.go deleted file mode 100644 index eed2c9a85..000000000 --- a/internal/gateway/session_state.go +++ /dev/null @@ -1,307 +0,0 @@ -package gateway - -import ( - "fmt" - "strings" - "sync" -) - -// GoalStatus is the operational state of a goal. -type GoalStatus string - -const ( - GoalActive GoalStatus = "active" - GoalPaused GoalStatus = "paused" -) - -// Goal is a standing objective for a session. -type Goal struct { - Text string `json:"text"` - Status GoalStatus `json:"status"` -} - -// Subgoal is a child objective under a goal. -type Subgoal struct { - Text string `json:"text"` -} - -// QueueEntry is a single item in the session's background queue. -type QueueEntry struct { - Text string `json:"text"` -} - -// SessionState holds per-session control state for goal, steer, and -// queue commands. All access is guarded by the embedded mutex. -type SessionState struct { - mu sync.Mutex - - // Goal management - goals []Goal - subgoals []Subgoal - waiting bool // /goal wait flag - - // Steer injection - steerText string - - // Background queue - queue []QueueEntry -} - -// NewSessionState returns an empty, usable SessionState. -func NewSessionState() *SessionState { - return &SessionState{} -} - -// ── Goal operations ────────────────────────────────────────────────── - -// SetGoal replaces the current goal. If there is an existing goal with -// subgoals, subgoals are preserved unless clearSubgoals is true. -func (s *SessionState) SetGoal(text string, clearSubgoals bool) { - s.mu.Lock() - defer s.mu.Unlock() - if len(s.goals) == 0 { - s.goals = []Goal{{Text: text, Status: GoalActive}} - return - } - s.goals[0] = Goal{Text: text, Status: GoalActive} - if clearSubgoals { - s.subgoals = nil - } -} - -// Goals returns a snapshot of current goals. -func (s *SessionState) Goals() []Goal { - s.mu.Lock() - defer s.mu.Unlock() - out := make([]Goal, len(s.goals)) - copy(out, s.goals) - return out -} - -// PauseGoal marks the first goal as paused. -func (s *SessionState) PauseGoal() bool { - s.mu.Lock() - defer s.mu.Unlock() - if len(s.goals) == 0 { - return false - } - s.goals[0].Status = GoalPaused - return true -} - -// ResumeGoal marks the first goal as active. -func (s *SessionState) ResumeGoal() bool { - s.mu.Lock() - defer s.mu.Unlock() - if len(s.goals) == 0 { - return false - } - s.goals[0].Status = GoalActive - return true -} - -// ClearGoal removes all goals and subgoals. -func (s *SessionState) ClearGoal() { - s.mu.Lock() - defer s.mu.Unlock() - s.goals = nil - s.subgoals = nil - s.waiting = false -} - -// HasGoal reports whether a goal is set. -func (s *SessionState) HasGoal() bool { - s.mu.Lock() - defer s.mu.Unlock() - return len(s.goals) > 0 -} - -// ── Subgoal operations ─────────────────────────────────────────────── - -// AddSubgoal appends a subgoal. -func (s *SessionState) AddSubgoal(text string) bool { - s.mu.Lock() - defer s.mu.Unlock() - if len(s.goals) == 0 { - return false - } - s.subgoals = append(s.subgoals, Subgoal{Text: text}) - return true -} - -// Subgoals returns a snapshot of current subgoals. -func (s *SessionState) Subgoals() []Subgoal { - s.mu.Lock() - defer s.mu.Unlock() - out := make([]Subgoal, len(s.subgoals)) - copy(out, s.subgoals) - return out -} - -// RemoveSubgoal removes the subgoal at the given 1-indexed position. -// Returns false if the index is out of range. -func (s *SessionState) RemoveSubgoal(n int) bool { - s.mu.Lock() - defer s.mu.Unlock() - idx := n - 1 - if idx < 0 || idx >= len(s.subgoals) { - return false - } - s.subgoals = append(s.subgoals[:idx], s.subgoals[idx+1:]...) - return true -} - -// ClearSubgoals removes all subgoals. -func (s *SessionState) ClearSubgoals() { - s.mu.Lock() - defer s.mu.Unlock() - s.subgoals = nil -} - -// ── Wait operations ────────────────────────────────────────────────── - -// SetWait sets the wait flag. -func (s *SessionState) SetWait() { - s.mu.Lock() - defer s.mu.Unlock() - s.waiting = true -} - -// ClearWait clears the wait flag. -func (s *SessionState) ClearWait() { - s.mu.Lock() - defer s.mu.Unlock() - s.waiting = false -} - -// IsWaiting reports the wait flag. -func (s *SessionState) IsWaiting() bool { - s.mu.Lock() - defer s.mu.Unlock() - return s.waiting -} - -// ── Steer operations ───────────────────────────────────────────────── - -// SetSteer stores a pending steer message. The previous steer (if not yet -// consumed) is replaced. -func (s *SessionState) SetSteer(text string) { - s.mu.Lock() - defer s.mu.Unlock() - s.steerText = text -} - -// PollSteer returns and clears any pending steer message. The second -// return value is false when no steer was pending. -func (s *SessionState) PollSteer() (string, bool) { - s.mu.Lock() - defer s.mu.Unlock() - if s.steerText == "" { - return "", false - } - text := s.steerText - s.steerText = "" - return text, true -} - -// PeekSteer returns the pending steer message without consuming it. -func (s *SessionState) PeekSteer() (string, bool) { - s.mu.Lock() - defer s.mu.Unlock() - if s.steerText == "" { - return "", false - } - return s.steerText, true -} - -// HasPendingSteer reports whether a steer message is waiting. -func (s *SessionState) HasPendingSteer() bool { - s.mu.Lock() - defer s.mu.Unlock() - return s.steerText != "" -} - -// ── Queue operations ───────────────────────────────────────────────── - -// AddToQueue appends an entry to the queue. -func (s *SessionState) AddToQueue(text string) { - s.mu.Lock() - defer s.mu.Unlock() - s.queue = append(s.queue, QueueEntry{Text: text}) -} - -// QueueEntries returns a snapshot of the queue. -func (s *SessionState) QueueEntries() []QueueEntry { - s.mu.Lock() - defer s.mu.Unlock() - out := make([]QueueEntry, len(s.queue)) - copy(out, s.queue) - return out -} - -// RemoveFromQueue removes the entry at the given 1-indexed position. -// Returns false if the index is out of range. -func (s *SessionState) RemoveFromQueue(n int) bool { - s.mu.Lock() - defer s.mu.Unlock() - idx := n - 1 - if idx < 0 || idx >= len(s.queue) { - return false - } - s.queue = append(s.queue[:idx], s.queue[idx+1:]...) - return true -} - -// ClearQueue removes all queue entries. -func (s *SessionState) ClearQueue() { - s.mu.Lock() - defer s.mu.Unlock() - s.queue = nil -} - -// QueueLen returns the number of queue entries. -func (s *SessionState) QueueLen() int { - s.mu.Lock() - defer s.mu.Unlock() - return len(s.queue) -} - -// ── Prompt rendering ───────────────────────────────────────────────── - -// BuildGoalPrompt returns a string suitable for injecting into the system -// prompt. Returns empty string when no goal is set. -func (s *SessionState) BuildGoalPrompt() string { - s.mu.Lock() - defer s.mu.Unlock() - if len(s.goals) == 0 { - return "" - } - var b strings.Builder - b.WriteString("\n") - b.WriteString(s.goals[0].Text) - b.WriteString("\n") - - if len(s.subgoals) > 0 { - b.WriteString("\nSubgoals:\n") - for i, sg := range s.subgoals { - fmt.Fprintf(&b, "%d. %s\n", i+1, sg.Text) - } - } - b.WriteString("") - - if s.waiting && s.goals[0].Status == GoalActive { - b.WriteString("\n\nThe goal has a wait flag set. Do not begin new work toward the goal unless the user explicitly asks you to proceed. Continue responding to other requests normally.") - } - if s.goals[0].Status == GoalPaused { - b.WriteString("\n\nThe goal is paused. Do not work toward it unless the user explicitly resumes it.") - } - - return b.String() -} diff --git a/internal/gateway/session_state_test.go b/internal/gateway/session_state_test.go deleted file mode 100644 index 5d9ece183..000000000 --- a/internal/gateway/session_state_test.go +++ /dev/null @@ -1,308 +0,0 @@ -package gateway - -import ( - "strings" - "testing" -) - -func TestSessionStateGoalLifecycle(t *testing.T) { - s := NewSessionState() - - if s.HasGoal() { - t.Error("new state should have no goal") - } - if g := s.Goals(); len(g) != 0 { - t.Errorf("Goals() = %d, want 0", len(g)) - } - - s.SetGoal("ship the thing", true) - if !s.HasGoal() { - t.Error("HasGoal() = false after SetGoal") - } - goals := s.Goals() - if len(goals) != 1 || goals[0].Text != "ship the thing" || goals[0].Status != GoalActive { - t.Errorf("Goals() = %+v, want active goal", goals) - } - - s.PauseGoal() - goals = s.Goals() - if goals[0].Status != GoalPaused { - t.Errorf("status = %s, want paused", goals[0].Status) - } - - s.ResumeGoal() - goals = s.Goals() - if goals[0].Status != GoalActive { - t.Errorf("status = %s, want active after resume", goals[0].Status) - } - - s.ClearGoal() - if s.HasGoal() { - t.Error("HasGoal() = true after ClearGoal") - } -} - -func TestPauseResumeWithoutGoalIsNoop(t *testing.T) { - s := NewSessionState() - if s.PauseGoal() { - t.Error("PauseGoal() without goal should return false") - } - if s.ResumeGoal() { - t.Error("ResumeGoal() without goal should return false") - } -} - -func TestSessionStateSubgoals(t *testing.T) { - s := NewSessionState() - - // Cannot add subgoal without a goal - if s.AddSubgoal("do thing 1") { - t.Error("AddSubgoal() without goal should return false") - } - - s.SetGoal("ship", true) - if !s.AddSubgoal("sub-a") { - t.Error("AddSubgoal() should succeed with goal present") - } - s.AddSubgoal("sub-b") - s.AddSubgoal("sub-c") - - sgs := s.Subgoals() - if len(sgs) != 3 { - t.Fatalf("Subgoals() = %d, want 3", len(sgs)) - } - - // Remove subgoal at position 2 (sub-b) - if !s.RemoveSubgoal(2) { - t.Error("RemoveSubgoal(2) should succeed") - } - sgs = s.Subgoals() - if len(sgs) != 2 || sgs[0].Text != "sub-a" || sgs[1].Text != "sub-c" { - t.Errorf("Subgoals() = %+v, want [sub-a, sub-c]", sgs) - } - - // Out of range - if s.RemoveSubgoal(10) { - t.Error("RemoveSubgoal(10) should return false") - } - if s.RemoveSubgoal(0) { - t.Error("RemoveSubgoal(0) should return false") - } - - s.ClearSubgoals() - if len(s.Subgoals()) != 0 { - t.Error("Subgoals() not empty after ClearSubgoals") - } -} - -func TestSessionStateSetGoalPreservesSubgoalsByDefault(t *testing.T) { - s := NewSessionState() - s.SetGoal("goal-a", false) - s.AddSubgoal("sg-1") - s.AddSubgoal("sg-2") - - s.SetGoal("goal-b", false) // no clear - sgs := s.Subgoals() - if len(sgs) != 2 { - t.Errorf("subgoals = %d after SetGoal without clear, want 2", len(sgs)) - } - - s.SetGoal("goal-c", true) // clear - sgs = s.Subgoals() - if len(sgs) != 0 { - t.Errorf("subgoals = %d after SetGoal with clear, want 0", len(sgs)) - } -} - -func TestSessionStateWait(t *testing.T) { - s := NewSessionState() - if s.IsWaiting() { - t.Error("IsWaiting() = true on new state") - } - s.SetWait() - if !s.IsWaiting() { - t.Error("IsWaiting() = false after SetWait") - } - s.ClearWait() - if s.IsWaiting() { - t.Error("IsWaiting() = true after ClearWait") - } -} - -func TestSessionStateSteer(t *testing.T) { - s := NewSessionState() - - if s.HasPendingSteer() { - t.Error("HasPendingSteer() = true on new state") - } - if _, ok := s.PollSteer(); ok { - t.Error("PollSteer() should return false on empty") - } - - s.SetSteer("do the thing") - if !s.HasPendingSteer() { - t.Error("HasPendingSteer() = false after SetSteer") - } - if text, ok := s.PeekSteer(); !ok || text != "do the thing" { - t.Errorf("PeekSteer() = (%q, %v), want (do the thing, true)", text, ok) - } - // Peek doesn't consume - if !s.HasPendingSteer() { - t.Error("PeekSteer should not consume") - } - - text, ok := s.PollSteer() - if !ok || text != "do the thing" { - t.Errorf("PollSteer() = (%q, %v), want (do the thing, true)", text, ok) - } - if s.HasPendingSteer() { - t.Error("HasPendingSteer() = true after PollSteer") - } - - // Second set replaces - s.SetSteer("first") - s.SetSteer("second") - text, _ = s.PollSteer() - if text != "second" { - t.Errorf("second SetSteer should replace: got %q", text) - } -} - -func TestSessionStateQueue(t *testing.T) { - s := NewSessionState() - - if n := s.QueueLen(); n != 0 { - t.Errorf("QueueLen() = %d, want 0", n) - } - - s.AddToQueue("item-a") - s.AddToQueue("item-b") - s.AddToQueue("item-c") - - if n := s.QueueLen(); n != 3 { - t.Errorf("QueueLen() = %d, want 3", n) - } - - entries := s.QueueEntries() - if len(entries) != 3 { - t.Fatalf("QueueEntries() = %d, want 3", len(entries)) - } - - if !s.RemoveFromQueue(2) { - t.Error("RemoveFromQueue(2) should succeed") - } - entries = s.QueueEntries() - if len(entries) != 2 || entries[0].Text != "item-a" || entries[1].Text != "item-c" { - t.Errorf("QueueEntries() = %+v, want [item-a, item-c]", entries) - } - - s.ClearQueue() - if n := s.QueueLen(); n != 0 { - t.Errorf("QueueLen() = %d after clear, want 0", n) - } -} - -func TestSessionStateClearGoalResetsWait(t *testing.T) { - s := NewSessionState() - s.SetGoal("g", false) - s.SetWait() - - s.ClearGoal() - if s.IsWaiting() { - t.Error("ClearGoal should reset wait flag") - } -} - -func TestBuildGoalPromptEmpty(t *testing.T) { - s := NewSessionState() - if p := s.BuildGoalPrompt(); p != "" { - t.Errorf("BuildGoalPrompt() = %q, want empty", p) - } -} - -func TestBuildGoalPromptActive(t *testing.T) { - s := NewSessionState() - s.SetGoal("build the API", false) - s.AddSubgoal("add auth") - s.AddSubgoal("add rate limiting") - - p := s.BuildGoalPrompt() - if p == "" { - t.Fatal("BuildGoalPrompt() returned empty") - } - if !strings.Contains(p, "build the API") { - t.Error("prompt missing goal text") - } - if !strings.Contains(p, "add auth") { - t.Error("prompt missing subgoal") - } - if !strings.Contains(p, "add rate limiting") { - t.Error("prompt missing subgoal") - } - if !strings.Contains(p, "standing_goal") { - t.Error("prompt missing standing_goal tag") - } - // Active goal should not mention pause/wait - if strings.Contains(p, "paused") { - t.Error("active goal should not mention paused") - } -} - -func TestBuildGoalPromptPaused(t *testing.T) { - s := NewSessionState() - s.SetGoal("refactor", false) - s.PauseGoal() - - p := s.BuildGoalPrompt() - if !strings.Contains(p, `status="paused"`) { - t.Error("prompt missing paused status attribute") - } - if !strings.Contains(p, "paused") { - t.Error("prompt should mention goal is paused") - } -} - -func TestBuildGoalPromptWaiting(t *testing.T) { - s := NewSessionState() - s.SetGoal("write docs", false) - s.SetWait() - - p := s.BuildGoalPrompt() - if !strings.Contains(p, `wait="true"`) { - t.Error("prompt missing wait attribute") - } - if !strings.Contains(p, "wait flag") { - t.Error("prompt should mention wait flag") - } -} - -func TestBuildGoalPromptConcurrency(t *testing.T) { - // Verify that concurrent access to BuildGoalPrompt and mutations - // does not race. Run with -race. - s := NewSessionState() - s.SetGoal("concurrent goal", false) - s.AddSubgoal("sg-1") - s.AddSubgoal("sg-2") - - done := make(chan struct{}) - go func() { - for i := range 100 { - s.SetSteer("steer " + string(rune('a'+i%26))) - s.SetWait() - s.ClearWait() - s.AddToQueue("q") - } - close(done) - }() - - for range 1000 { - p := s.BuildGoalPrompt() - if p == "" { - t.Error("BuildGoalPrompt returned empty during concurrent access") - break - } - s.PollSteer() - s.QueueEntries() - } - <-done -} diff --git a/internal/gateway/web_parity_test.go b/internal/gateway/web_parity_test.go index 211e645c7..ab484cf96 100644 --- a/internal/gateway/web_parity_test.go +++ b/internal/gateway/web_parity_test.go @@ -19,13 +19,6 @@ func (parityUpdateStub) Install(context.Context, releaseupdate.Snapshot, release } func (parityUpdateStub) CanInstall() bool { return true } -type parityDangerousStub struct{ decisions []string } - -func (s *parityDangerousStub) Decide(_ context.Context, id, decision string) (string, error) { - s.decisions = append(s.decisions, id+":"+decision) - return "dangerous decision applied", nil -} - func TestSharedRouterWebParityCommands(t *testing.T) { t.Parallel() r := NewRouter(nil, nil, "web") @@ -33,8 +26,6 @@ func TestSharedRouterWebParityCommands(t *testing.T) { restarted := false r.Restart = func(context.Context) error { restarted = true; return nil } r.Updates = parityUpdateStub{} - dangerous := &parityDangerousStub{} - r.Dangerous = dangerous r.Personas = NewPersonaRegistry(DefaultPersonas()) sessions := NewSessionStoreMemory() t.Cleanup(func() { _ = sessions.Close() }) @@ -59,16 +50,4 @@ func TestSharedRouterWebParityCommands(t *testing.T) { if err != nil || !strings.Contains(reply, "v2 available") { t.Fatalf("/update = %q, err=%v", reply, err) } - reply, err = r.Route(context.Background(), inbound("browser", "/approve action-1")) - if err != nil || !strings.Contains(reply, "decision applied") || len(dangerous.decisions) != 1 || dangerous.decisions[0] != "action-1:approve" { - t.Fatalf("typed /approve = %q, decisions=%v, err=%v", reply, dangerous.decisions, err) - } - _, err = r.Route(context.Background(), inbound("browser", "/approve permanent action-2")) - if err != nil || len(dangerous.decisions) != 2 || dangerous.decisions[1] != "action-2:permanent" { - t.Fatalf("permanent /approve decisions=%v, err=%v", dangerous.decisions, err) - } - _, err = r.Route(context.Background(), inbound("browser", "/deny action-3")) - if err != nil || len(dangerous.decisions) != 3 || dangerous.decisions[2] != "action-3:deny" { - t.Fatalf("/deny decisions=%v, err=%v", dangerous.decisions, err) - } }