diff --git a/coderd/x/chatd/chatd.go b/coderd/x/chatd/chatd.go index 1909be962bd..4c86922a186 100644 --- a/coderd/x/chatd/chatd.go +++ b/coderd/x/chatd/chatd.go @@ -447,7 +447,7 @@ func (p *Server) pinnedWorkspaceMCPTools( return nil, xerrors.Errorf("list chat context resources: %w", err) } infos := workspaceMCPToolInfosFromResources(resources) - return chattool.NewWorkspaceMCPTools(infos, getConn, nil), nil + return chattool.NewWorkspaceMCPTools(infos, getConn), nil } type turnWorkspaceContext struct { @@ -977,8 +977,8 @@ func (c *turnWorkspaceContext) getWorkspaceConn(ctx context.Context) (workspaces } // Surface the dial timeout sentinel only when the // parent context is still alive. If the parent was - // canceled (e.g. ErrInterrupted), its error must - // propagate unchanged so the chatloop can detect it. + // canceled, its error must propagate unchanged so + // the runner can recognize cancellation. if ctx.Err() == nil && errors.Is(context.Cause(dialCtx), errChatDialTimeout) { c.clearCachedWorkspaceState() return nil, c.latestWorkspaceAgentRecoveryError(ctx, chatSnapshot.WorkspaceID.UUID) diff --git a/coderd/x/chatd/chatd_internal_test.go b/coderd/x/chatd/chatd_internal_test.go index 186977f4a7e..2c6e9246e20 100644 --- a/coderd/x/chatd/chatd_internal_test.go +++ b/coderd/x/chatd/chatd_internal_test.go @@ -2812,8 +2812,6 @@ func TestGetWorkspaceConn_DialTimeout(t *testing.T) { func TestGetWorkspaceConn_DialTimeoutParentCanceled(t *testing.T) { // When the parent context is canceled, the parent's error // must propagate unchanged (not wrapped as a dial timeout). - // This is critical because the chatloop checks - // context.Cause(ctx) for ErrInterrupted. t.Parallel() ctrl := gomock.NewController(t) diff --git a/coderd/x/chatd/chatdebug/context.go b/coderd/x/chatd/chatdebug/context.go index f67ddb64567..5fde6dba30b 100644 --- a/coderd/x/chatd/chatdebug/context.go +++ b/coderd/x/chatd/chatdebug/context.go @@ -9,10 +9,9 @@ import ( ) type ( - runContextKey struct{} - stepContextKey struct{} - reuseStepKey struct{} - reuseHolder struct { + runContextKey struct{} + reuseStepKey struct{} + reuseHolder struct { mu sync.Mutex handle *stepHandle } @@ -50,23 +49,6 @@ func RunFromContext(ctx context.Context) (*RunContext, bool) { return rc, true } -// ContextWithStep stores sc in ctx. -func ContextWithStep(ctx context.Context, sc *StepContext) context.Context { - if sc == nil { - panic("chatdebug: nil StepContext") - } - return context.WithValue(ctx, stepContextKey{}, sc) -} - -// StepFromContext returns the debug step context stored in ctx. -func StepFromContext(ctx context.Context) (*StepContext, bool) { - sc, ok := ctx.Value(stepContextKey{}).(*StepContext) - if !ok { - return nil, false - } - return sc, true -} - // ReuseStep marks ctx so wrapped model calls under it share one debug step. func ReuseStep(ctx context.Context) context.Context { if holder, ok := reuseHolderFromContext(ctx); ok { diff --git a/coderd/x/chatd/chatdebug/context_test.go b/coderd/x/chatd/chatdebug/context_test.go index d8ee2e183ba..bfacec41098 100644 --- a/coderd/x/chatd/chatdebug/context_test.go +++ b/coderd/x/chatd/chatdebug/context_test.go @@ -40,52 +40,6 @@ func TestRunFromContextAbsent(t *testing.T) { require.Nil(t, got) } -func TestContextWithStepRoundTrip(t *testing.T) { - t.Parallel() - - sc := &chatdebug.StepContext{ - StepID: uuid.New(), - RunID: uuid.New(), - ChatID: uuid.New(), - StepNumber: 7, - Operation: chatdebug.OperationStream, - } - - ctx := chatdebug.ContextWithStep(context.Background(), sc) - got, ok := chatdebug.StepFromContext(ctx) - require.True(t, ok) - require.Same(t, sc, got) - require.Equal(t, *sc, *got) -} - -func TestStepFromContextAbsent(t *testing.T) { - t.Parallel() - - got, ok := chatdebug.StepFromContext(context.Background()) - require.False(t, ok) - require.Nil(t, got) -} - -func TestContextWithRunAndStep(t *testing.T) { - t.Parallel() - - rc := &chatdebug.RunContext{RunID: uuid.New(), ChatID: uuid.New()} - sc := &chatdebug.StepContext{StepID: uuid.New(), RunID: rc.RunID, ChatID: rc.ChatID} - - ctx := chatdebug.ContextWithStep( - chatdebug.ContextWithRun(context.Background(), rc), - sc, - ) - - gotRun, ok := chatdebug.RunFromContext(ctx) - require.True(t, ok) - require.Same(t, rc, gotRun) - - gotStep, ok := chatdebug.StepFromContext(ctx) - require.True(t, ok) - require.Same(t, sc, gotStep) -} - func TestContextWithRunPanicsOnNil(t *testing.T) { t.Parallel() @@ -93,11 +47,3 @@ func TestContextWithRunPanicsOnNil(t *testing.T) { _ = chatdebug.ContextWithRun(context.Background(), nil) }) } - -func TestContextWithStepPanicsOnNil(t *testing.T) { - t.Parallel() - - require.Panics(t, func() { - _ = chatdebug.ContextWithStep(context.Background(), nil) - }) -} diff --git a/coderd/x/chatd/chatdebug/export_test.go b/coderd/x/chatd/chatdebug/export_test.go new file mode 100644 index 00000000000..3ab3c4fe3b1 --- /dev/null +++ b/coderd/x/chatd/chatdebug/export_test.go @@ -0,0 +1,23 @@ +package chatdebug + +// AllRunKinds contains every RunKind value for SDK parity checks. +var AllRunKinds = []RunKind{ + KindChatTurn, + KindTitleGeneration, + KindQuickgen, + KindCompaction, +} + +// AllStatuses contains every Status value for SDK parity checks. +var AllStatuses = []Status{ + StatusInProgress, + StatusCompleted, + StatusError, + StatusInterrupted, +} + +// AllOperations contains every Operation value for SDK parity checks. +var AllOperations = []Operation{ + OperationStream, + OperationGenerate, +} diff --git a/coderd/x/chatd/chatdebug/model_internal_test.go b/coderd/x/chatd/chatdebug/model_internal_test.go index 03bb51cab80..822c43a251c 100644 --- a/coderd/x/chatd/chatdebug/model_internal_test.go +++ b/coderd/x/chatd/chatdebug/model_internal_test.go @@ -171,8 +171,6 @@ func TestDebugModel_Disabled(t *testing.T) { respWant := &fantasy.Response{FinishReason: fantasy.FinishReasonStop} inner := &chattest.FakeModel{ GenerateFn: func(ctx context.Context, call fantasy.Call) (*fantasy.Response, error) { - _, ok := StepFromContext(ctx) - require.False(t, ok) require.Nil(t, attemptSinkFromContext(ctx)) return respWant, nil }, @@ -244,13 +242,6 @@ func TestDebugModel_Generate(t *testing.T) { inner := &chattest.FakeModel{ GenerateFn: func(ctx context.Context, got fantasy.Call) (*fantasy.Response, error) { require.Equal(t, call, got) - stepCtx, ok := StepFromContext(ctx) - require.True(t, ok) - require.Equal(t, runID, stepCtx.RunID) - require.Equal(t, chatID, stepCtx.ChatID) - require.Equal(t, int32(1), stepCtx.StepNumber) - require.Equal(t, OperationGenerate, stepCtx.Operation) - require.NotEqual(t, uuid.Nil, stepCtx.StepID) require.NotNil(t, attemptSinkFromContext(ctx)) return respWant, nil }, @@ -537,13 +528,6 @@ func TestDebugModel_Stream(t *testing.T) { model := &debugModel{ inner: &chattest.FakeModel{ StreamFn: func(ctx context.Context, call fantasy.Call) (fantasy.StreamResponse, error) { - stepCtx, ok := StepFromContext(ctx) - require.True(t, ok) - require.Equal(t, runID, stepCtx.RunID) - require.Equal(t, chatID, stepCtx.ChatID) - require.Equal(t, int32(1), stepCtx.StepNumber) - require.Equal(t, OperationStream, stepCtx.Operation) - require.NotEqual(t, uuid.Nil, stepCtx.StepID) require.NotNil(t, attemptSinkFromContext(ctx)) return partsToSeq(parts), nil }, @@ -620,13 +604,6 @@ func TestDebugModel_StreamObject(t *testing.T) { model := &debugModel{ inner: &chattest.FakeModel{ StreamObjectFn: func(ctx context.Context, call fantasy.ObjectCall) (fantasy.ObjectStreamResponse, error) { - stepCtx, ok := StepFromContext(ctx) - require.True(t, ok) - require.Equal(t, runID, stepCtx.RunID) - require.Equal(t, chatID, stepCtx.ChatID) - require.Equal(t, int32(1), stepCtx.StepNumber) - require.Equal(t, OperationStream, stepCtx.Operation) - require.NotEqual(t, uuid.Nil, stepCtx.StepID) require.NotNil(t, attemptSinkFromContext(ctx)) return objectPartsToSeq(parts), nil }, @@ -1001,12 +978,6 @@ func TestDebugModel_GenerateObject(t *testing.T) { inner := &chattest.FakeModel{ GenerateObjectFn: func(ctx context.Context, got fantasy.ObjectCall) (*fantasy.ObjectResponse, error) { require.Equal(t, call, got) - stepCtx, ok := StepFromContext(ctx) - require.True(t, ok) - require.Equal(t, runID, stepCtx.RunID) - require.Equal(t, chatID, stepCtx.ChatID) - require.Equal(t, OperationGenerate, stepCtx.Operation) - require.NotEqual(t, uuid.Nil, stepCtx.StepID) require.NotNil(t, attemptSinkFromContext(ctx)) return respWant, nil }, @@ -1225,8 +1196,8 @@ func TestLaunchHeartbeat(t *testing.T) { // short enough to test easily (threshold/2 = 5s, clamped ≥1s). svc := NewService(db, testutil.Logger(t), nil, WithClock(mClock), - WithStaleThreshold(10*time.Second), ) + svc.SetStaleAfter(10 * time.Second) stepID := uuid.New() runID := uuid.New() @@ -1291,8 +1262,8 @@ func TestLaunchHeartbeat(t *testing.T) { svc := NewService(db, testutil.Logger(t), nil, WithClock(mClock), - WithStaleThreshold(10*time.Second), ) + svc.SetStaleAfter(10 * time.Second) stepID := uuid.New() runID := uuid.New() @@ -1338,8 +1309,8 @@ func TestLaunchHeartbeat(t *testing.T) { svc := NewService(db, testutil.Logger(t), nil, WithClock(mClock), - WithStaleThreshold(60*time.Second), ) + svc.SetStaleAfter(60 * time.Second) stepID := uuid.New() runID := uuid.New() diff --git a/coderd/x/chatd/chatdebug/recorder.go b/coderd/x/chatd/chatdebug/recorder.go index 8083308b4a6..c8b07ff50c3 100644 --- a/coderd/x/chatd/chatdebug/recorder.go +++ b/coderd/x/chatd/chatdebug/recorder.go @@ -198,7 +198,7 @@ type stepHandle struct { } // beginStep validates preconditions, creates a debug step, and returns a -// handle plus an enriched context carrying StepContext and attemptSink. +// handle plus an enriched context carrying the attempt sink. // Returns (nil, original ctx) when debug recording should be skipped. func beginStep( ctx context.Context, @@ -232,8 +232,7 @@ func beginStep( // A different RunContext means a new logical run, so we must // create a fresh step to avoid cross-run attribution. if holder.handle != nil && holder.handle.stepCtx.RunID == rc.RunID { - enriched := ContextWithStep(ctx, holder.handle.stepCtx) - enriched = withAttemptSink(enriched, holder.handle.sink) + enriched := withAttemptSink(ctx, holder.handle.sink) return holder.handle, enriched } } @@ -259,21 +258,14 @@ func beginStep( } syncStepCounter(rc.RunID, step.StepNumber) - actualStepNumber := step.StepNumber - if actualStepNumber == 0 { - actualStepNumber = stepNum - } sc := &StepContext{ - StepID: step.ID, - RunID: rc.RunID, - ChatID: chatID, - StepNumber: actualStepNumber, - Operation: op, + StepID: step.ID, + RunID: rc.RunID, + ChatID: chatID, } handle := &stepHandle{stepCtx: sc, sink: &attemptSink{}, svc: svc} - enriched := ContextWithStep(ctx, handle.stepCtx) - enriched = withAttemptSink(enriched, handle.sink) + enriched := withAttemptSink(ctx, handle.sink) if reuseStep { holder.handle = handle } diff --git a/coderd/x/chatd/chatdebug/recorder_internal_test.go b/coderd/x/chatd/chatdebug/recorder_internal_test.go index a9ed5e9bd8c..2dbbe116b6a 100644 --- a/coderd/x/chatd/chatdebug/recorder_internal_test.go +++ b/coderd/x/chatd/chatdebug/recorder_internal_test.go @@ -141,8 +141,6 @@ func TestBeginStep_NilService(t *testing.T) { handle, enriched := beginStep(ctx, nil, RecorderOptions{}, OperationGenerate, nil) require.Nil(t, handle) require.Nil(t, attemptSinkFromContext(enriched)) - _, ok := StepFromContext(enriched) - require.False(t, ok) } func TestBeginStep_FallsBackToRunChatID(t *testing.T) { @@ -163,9 +161,7 @@ func TestBeginStep_FallsBackToRunChatID(t *testing.T) { require.NotNil(t, handle) require.Equal(t, runChatID, handle.stepCtx.ChatID) - stepCtx, ok := StepFromContext(enriched) - require.True(t, ok) - require.Equal(t, runChatID, stepCtx.ChatID) + require.Same(t, handle.sink, attemptSinkFromContext(enriched)) } func TestWrapModel_ReturnsDebugModel(t *testing.T) { diff --git a/coderd/x/chatd/chatdebug/reuse_step_internal_test.go b/coderd/x/chatd/chatdebug/reuse_step_internal_test.go index 466ec3b117c..5feb1ac6224 100644 --- a/coderd/x/chatd/chatdebug/reuse_step_internal_test.go +++ b/coderd/x/chatd/chatdebug/reuse_step_internal_test.go @@ -51,16 +51,8 @@ func TestBeginStepReuseStep(t *testing.T) { require.Same(t, firstHandle.sink, secondHandle.sink) require.Equal(t, runID, firstHandle.stepCtx.RunID) require.Equal(t, chatID, firstHandle.stepCtx.ChatID) - require.Equal(t, int32(1), firstHandle.stepCtx.StepNumber) - require.Equal(t, OperationStream, firstHandle.stepCtx.Operation) require.NotEqual(t, uuid.Nil, firstHandle.stepCtx.StepID) - firstStepCtx, ok := StepFromContext(firstEnriched) - require.True(t, ok) - secondStepCtx, ok := StepFromContext(secondEnriched) - require.True(t, ok) - require.Same(t, firstStepCtx, secondStepCtx) - require.Same(t, firstHandle.stepCtx, firstStepCtx) require.Same(t, attemptSinkFromContext(firstEnriched), attemptSinkFromContext(secondEnriched)) }) @@ -106,8 +98,6 @@ func TestBeginStepReuseStep(t *testing.T) { require.NotNil(t, secondHandle) require.NotSame(t, firstHandle, secondHandle) require.NotSame(t, firstHandle.sink, secondHandle.sink) - require.Equal(t, int32(1), firstHandle.stepCtx.StepNumber) - require.Equal(t, int32(2), secondHandle.stepCtx.StepNumber) require.NotEqual(t, firstHandle.stepCtx.StepID, secondHandle.stepCtx.StepID) }) } diff --git a/coderd/x/chatd/chatdebug/service.go b/coderd/x/chatd/chatdebug/service.go index 337172413cf..bda2884513f 100644 --- a/coderd/x/chatd/chatdebug/service.go +++ b/coderd/x/chatd/chatdebug/service.go @@ -49,18 +49,6 @@ type Service struct { // ServiceOption configures optional Service behavior. type ServiceOption func(*Service) -// WithStaleThreshold overrides the default stale-row finalization -// threshold. Callers that already have a configurable in-flight chat -// timeout (e.g. chatd's InFlightChatStaleAfter) should pass it here -// so the two sweeps stay in sync. -func WithStaleThreshold(d time.Duration) ServiceOption { - return func(s *Service) { - if d > 0 { - s.staleAfterNanos.Store(d.Nanoseconds()) - } - } -} - // WithAlwaysEnable forces debug logging on for every chat regardless // of the runtime admin and user opt-in settings. This is used for the // deployment-level serpent flag. @@ -713,9 +701,7 @@ func (s *Service) FinalizeRun(ctx context.Context, p FinalizeRunParams) error { // ClassifyError maps a run error to the appropriate debug status. // nil → StatusCompleted, context.Canceled → StatusInterrupted, -// everything else → StatusError. Callers with additional -// classification rules (e.g. ErrInterrupted) -// should handle those before falling back to this helper. +// everything else → StatusError. func ClassifyError(err error) Status { switch { case err == nil: diff --git a/coderd/x/chatd/chatdebug/types.go b/coderd/x/chatd/chatdebug/types.go index e6ec078e9ae..6aff6ec79fd 100644 --- a/coderd/x/chatd/chatdebug/types.go +++ b/coderd/x/chatd/chatdebug/types.go @@ -16,15 +16,6 @@ const ( KindCompaction RunKind = "compaction" ) -// AllRunKinds contains every RunKind value. Update this when -// adding new constants above. -var AllRunKinds = []RunKind{ - KindChatTurn, - KindTitleGeneration, - KindQuickgen, - KindCompaction, -} - // Status identifies lifecycle state shared by runs and steps. type Status string @@ -62,15 +53,6 @@ func (s Status) Priority() int { } } -// AllStatuses contains every Status value. Update this when -// adding new constants above. -var AllStatuses = []Status{ - StatusInProgress, - StatusCompleted, - StatusError, - StatusInterrupted, -} - // Operation identifies the model operation a step performed. type Operation string @@ -81,13 +63,6 @@ const ( OperationGenerate Operation = "generate" ) -// AllOperations contains every Operation value. Update this when -// adding new constants above. -var AllOperations = []Operation{ - OperationStream, - OperationGenerate, -} - // RunContext carries identity and metadata for a debug run. type RunContext struct { RunID uuid.UUID @@ -103,11 +78,9 @@ type RunContext struct { // StepContext carries identity and metadata for a debug step. type StepContext struct { - StepID uuid.UUID - RunID uuid.UUID - ChatID uuid.UUID - StepNumber int32 - Operation Operation + StepID uuid.UUID + RunID uuid.UUID + ChatID uuid.UUID } // Attempt captures a single HTTP round trip made during a step. diff --git a/coderd/x/chatd/chatloop/chatloop.go b/coderd/x/chatd/chatloop/chatloop.go index 3ce418171fc..f019d752197 100644 --- a/coderd/x/chatd/chatloop/chatloop.go +++ b/coderd/x/chatd/chatloop/chatloop.go @@ -40,7 +40,6 @@ const ( ) var ( - ErrInterrupted = xerrors.New("chat interrupted") // ErrContentFiltered is returned when the provider's safety // classifiers blocked the response and the model produced no // content, e.g. Anthropic's stop_reason "refusal". @@ -127,7 +126,6 @@ type AssistantOutcome struct { Step PersistedStep ToolCalls []fantasy.ToolCallContent FinishReason fantasy.FinishReason - ModelStopped bool } // ExecuteLocalToolsOptions configures one local tool execution batch. @@ -197,7 +195,6 @@ type GenerateCompactionOptions struct { SummaryHint string SystemSummaryPrefix string StepUsage fantasy.Usage - StepMetadata fantasy.ProviderMetadata // Force skips the threshold gate (including the threshold=100 // disable and the zero-usage early return). Set for manual, @@ -339,11 +336,8 @@ func GenerateAssistant(ctx context.Context, opts GenerateAssistantOptions) (Assi } defer attempt.release() - result, processErr := processStepStream(attempt.ctx, attempt.stream, opts.Clock, publishMessagePart) + result, processErr := processStepStream(attempt.stream, opts.Clock, publishMessagePart) if err := attempt.finish(processErr); err != nil { - if errors.Is(err, ErrInterrupted) { - return AssistantOutcome{}, ErrInterrupted - } wrappedErr := wrapProviderStreamError(errorProvider, err) classified := chaterror.Classify(wrappedErr).WithProvider(errorProvider) if classified.Retryable { @@ -385,7 +379,6 @@ func GenerateAssistant(ctx context.Context, opts GenerateAssistantOptions) (Assi Step: step, ToolCalls: append([]fantasy.ToolCallContent(nil), result.toolCalls...), FinishReason: result.finishReason, - ModelStopped: len(result.content) == 0, }, nil } @@ -814,14 +807,13 @@ func clockNow(clock quartz.Clock) time.Time { // accumulates all content into a stepResult. Callbacks fire // inline and their errors propagate directly. func processStepStream( - ctx context.Context, stream fantasy.StreamResponse, clock quartz.Clock, publishMessagePart func(codersdk.ChatMessageRole, codersdk.ChatMessagePart), ) (stepResult, error) { var result stepResult - activeToolCalls := make(map[string]*fantasy.ToolCallContent) + providerExecutedCalls := make(map[string]bool) activeTextContent := make(map[string]string) activeReasoningContent := make(map[string]reasoningState) // Track tool names by ID for input delta publishing. @@ -884,22 +876,13 @@ func processStepStream( delete(activeReasoningContent, part.ID) } case fantasy.StreamPartTypeToolInputStart: - activeToolCalls[part.ID] = &fantasy.ToolCallContent{ - ToolCallID: part.ID, - ToolName: part.ToolCallName, - Input: "", - ProviderExecuted: part.ProviderExecuted, - } + providerExecutedCalls[part.ID] = part.ProviderExecuted if strings.TrimSpace(part.ToolCallName) != "" { toolNames[part.ID] = part.ToolCallName } case fantasy.StreamPartTypeToolInputDelta: - var providerExecuted bool - if toolCall, exists := activeToolCalls[part.ID]; exists { - toolCall.Input += part.Delta - providerExecuted = toolCall.ProviderExecuted - } + providerExecuted := providerExecutedCalls[part.ID] toolName := toolNames[part.ID] publishMessagePart(codersdk.ChatMessageRoleAssistant, codersdk.ChatMessagePart{ Type: codersdk.ChatMessagePartTypeToolCall, @@ -926,7 +909,7 @@ func processStepStream( toolNames[part.ID] = part.ToolCallName } // Clean up active tool call tracking. - delete(activeToolCalls, part.ID) + delete(providerExecutedCalls, part.ID) // Record when the model emitted this tool call // so the persisted part carries an accurate @@ -991,47 +974,10 @@ func processStepStream( result.providerMetadata = part.ProviderMetadata case fantasy.StreamPartTypeError: - // Detect interruption: the stream may surface the - // cancel as context.Canceled or propagate the - // ErrInterrupted cause directly, depending on - // the provider implementation. - if errors.Is(context.Cause(ctx), ErrInterrupted) && - (errors.Is(part.Error, context.Canceled) || errors.Is(part.Error, ErrInterrupted)) { - // Flush in-progress content so that - // persistInterruptedStep has access to partial - // text, reasoning, and tool calls that were - // still streaming when the interrupt arrived. - flushActiveState( - &result, - clock, - activeTextContent, - activeReasoningContent, - activeToolCalls, - toolNames, - ) - return result, ErrInterrupted - } return result, part.Error } } - // The stream iterator may stop yielding parts without - // producing a StreamPartTypeError when the context is - // canceled (e.g. some providers close the response body - // silently). Detect this case and flush partial content - // so that persistInterruptedStep can save it. - if ctx.Err() != nil && - errors.Is(context.Cause(ctx), ErrInterrupted) { - flushActiveState( - &result, - clock, - activeTextContent, - activeReasoningContent, - activeToolCalls, - toolNames, - ) - return result, ErrInterrupted - } return result, nil } @@ -1419,69 +1365,6 @@ func executeSingleTool( return result } -// flushActiveState moves any in-progress text, reasoning, and -// tool calls from the active tracking maps into result.content -// and result.toolCalls. This is called on interruption so that -// partial content from an incomplete stream is available for -// persistence. -func flushActiveState( - result *stepResult, - clock quartz.Clock, - activeText map[string]string, - activeReasoning map[string]reasoningState, - activeToolCalls map[string]*fantasy.ToolCallContent, - toolNames map[string]string, -) { - // Flush partial text content. - for _, text := range activeText { - if text != "" { - result.content = append(result.content, fantasy.TextContent{Text: text}) - } - } - - // Flush partial reasoning content. The matching - // completedAt is filled in here with the interruption - // time so partial reasoning shows the time spent before - // the interruption. - flushedAt := clockNow(clock) - for _, rs := range activeReasoning { - if rs.text == "" && !chatsanitize.HasAnthropicSignedReasoningOptions(fantasy.ProviderOptions(rs.options)) { - continue - } - result.content = append(result.content, fantasy.ReasoningContent{ - Text: rs.text, - ProviderMetadata: rs.options, - }) - result.reasoningStartedAt = append(result.reasoningStartedAt, rs.startedAt) - result.reasoningCompletedAt = append(result.reasoningCompletedAt, flushedAt) - } - - // Flush in-progress tool calls. These haven't received a - // StreamPartTypeToolCall yet, so they only exist in - // activeToolCalls. We add them to both content and toolCalls - // so persistInterruptedStep can generate synthetic error - // results for them. - for id, tc := range activeToolCalls { - if tc == nil { - continue - } - // Prefer the tool name from the toolNames map since - // ToolInputStart may provide a cleaner name. - toolName := tc.ToolName - if name, ok := toolNames[id]; ok && strings.TrimSpace(name) != "" { - toolName = name - } - flushed := fantasy.ToolCallContent{ - ToolCallID: tc.ToolCallID, - ToolName: toolName, - Input: tc.Input, - ProviderExecuted: tc.ProviderExecuted, - } - result.content = append(result.content, flushed) - result.toolCalls = append(result.toolCalls, flushed) - } -} - func isToolActive(name string, activeTools []string) bool { return len(activeTools) == 0 || slices.Contains(activeTools, name) } @@ -1880,12 +1763,6 @@ func metadataKeyWords(key string) []string { func numericContextLimitValue(value any) (int64, bool) { switch typed := value.(type) { - case int64: - return positiveInt64(typed) - case int32: - return positiveInt64(int64(typed)) - case int: - return positiveInt64(int64(typed)) case float64: casted := int64(typed) if typed > 0 && float64(casted) == typed { @@ -1896,11 +1773,6 @@ func numericContextLimitValue(value any) (int64, bool) { if err == nil { return positiveInt64(parsed) } - case json.Number: - parsed, err := typed.Int64() - if err == nil { - return positiveInt64(parsed) - } } return 0, false diff --git a/coderd/x/chatd/chatloop/chatloop_internal_test.go b/coderd/x/chatd/chatloop/chatloop_internal_test.go index 91d8bd0ff66..92ff8492925 100644 --- a/coderd/x/chatd/chatloop/chatloop_internal_test.go +++ b/coderd/x/chatd/chatloop/chatloop_internal_test.go @@ -1,7 +1,6 @@ package chatloop import ( - "context" "encoding/json" "iter" "testing" @@ -35,7 +34,7 @@ func TestProcessStepStreamPreservesReasoningMetadataAcrossNilDelta(t *testing.T) yield(fantasy.StreamPart{Type: fantasy.StreamPartTypeFinish, FinishReason: fantasy.FinishReasonStop}) }) - result, err := processStepStream(context.Background(), stream, quartz.NewMock(t), func(codersdk.ChatMessageRole, codersdk.ChatMessagePart) {}) + result, err := processStepStream(stream, quartz.NewMock(t), func(codersdk.ChatMessageRole, codersdk.ChatMessagePart) {}) require.NoError(t, err) require.Len(t, result.content, 1) reasoning, ok := fantasy.AsContentType[fantasy.ReasoningContent](result.content[0]) @@ -71,7 +70,7 @@ func TestProcessStepStreamPersistsRedactedThinkingOnEnd(t *testing.T) { yield(fantasy.StreamPart{Type: fantasy.StreamPartTypeFinish, FinishReason: fantasy.FinishReasonStop}) }) - result, err := processStepStream(context.Background(), stream, quartz.NewMock(t), func(codersdk.ChatMessageRole, codersdk.ChatMessagePart) {}) + result, err := processStepStream(stream, quartz.NewMock(t), func(codersdk.ChatMessageRole, codersdk.ChatMessagePart) {}) require.NoError(t, err) require.Len(t, result.content, 2) reasoning, ok := fantasy.AsContentType[fantasy.ReasoningContent](result.content[0]) @@ -127,34 +126,3 @@ func TestBuildToolDefinitionsNilPropertiesBecomesEmptyObject(t *testing.T) { require.NoError(t, err) require.JSONEq(t, `{"type":"object","properties":{}}`, string(bs)) } - -func TestFlushActiveStatePreservesEmptySignedReasoning(t *testing.T) { - t.Parallel() - - result := &stepResult{} - flushActiveState( - result, - quartz.NewMock(t), - map[string]string{}, - map[string]reasoningState{ - "signed": { - options: fantasy.ProviderMetadata{ - fantasyanthropic.Name: &fantasyanthropic.ReasoningOptionMetadata{ - RedactedData: "redacted-payload", - }, - }, - }, - "empty": {}, - }, - map[string]*fantasy.ToolCallContent{}, - map[string]string{}, - ) - - require.Len(t, result.content, 1) - reasoning, ok := fantasy.AsContentType[fantasy.ReasoningContent](result.content[0]) - require.True(t, ok) - require.Empty(t, reasoning.Text) - metadata := fantasyanthropic.GetReasoningMetadata(fantasy.ProviderOptions(reasoning.ProviderMetadata)) - require.NotNil(t, metadata) - require.Equal(t, "redacted-payload", metadata.RedactedData) -} diff --git a/coderd/x/chatd/chatloop/compaction.go b/coderd/x/chatd/chatloop/compaction.go index 57bfff82d96..69ba2f6dc2b 100644 --- a/coderd/x/chatd/chatloop/compaction.go +++ b/coderd/x/chatd/chatloop/compaction.go @@ -151,9 +151,7 @@ func GenerateCompaction(ctx context.Context, opts GenerateCompactionOptions) (Co if contextTokens <= 0 && !config.Force { return CompactionResult{}, nil } - metadataLimit := extractContextLimit(opts.StepMetadata) contextLimit := resolveContextLimit( - metadataLimit.Int64, config.ContextLimit, opts.ContextLimitFallback, ) @@ -300,13 +298,9 @@ func contextTokensFromUsage(usage fantasy.Usage) int64 { return total } -// resolveContextLimit picks the first positive value from metadata, -// configured limit, and fallback — in that priority order. Returns -// 0 when none are positive. -func resolveContextLimit(metadataLimit, configLimit, fallback int64) int64 { - if metadataLimit > 0 { - return metadataLimit - } +// resolveContextLimit returns the configured limit when positive, then +// the fallback, or zero when neither is positive. +func resolveContextLimit(configLimit, fallback int64) int64 { if configLimit > 0 { return configLimit } @@ -400,9 +394,6 @@ func startCompactionDebugRun( return compactionCtx, func(runErr error) { status := chatdebug.ClassifyError(runErr) - if runErr != nil && xerrors.Is(runErr, ErrInterrupted) { - status = chatdebug.StatusInterrupted - } // Debug instrumentation must not surface as a compaction failure. _ = options.DebugSvc.FinalizeRun(compactionCtx, chatdebug.FinalizeRunParams{ RunID: run.ID, diff --git a/coderd/x/chatd/chatloop/contextlimit_internal_test.go b/coderd/x/chatd/chatloop/contextlimit_internal_test.go index f70fad09de8..f6cb506e675 100644 --- a/coderd/x/chatd/chatloop/contextlimit_internal_test.go +++ b/coderd/x/chatd/chatloop/contextlimit_internal_test.go @@ -144,19 +144,6 @@ func TestNumericContextLimitValue(t *testing.T) { {name: "float64 zero rejected", value: float64(0), want: 0, wantOK: false}, {name: "float64 negative rejected", value: float64(-1), want: 0, wantOK: false}, - // int64 - {name: "int64 positive", value: int64(200000), want: 200000, wantOK: true}, - {name: "int64 zero rejected", value: int64(0), want: 0, wantOK: false}, - {name: "int64 negative rejected", value: int64(-1), want: 0, wantOK: false}, - - // int32 - {name: "int32 positive", value: int32(50000), want: 50000, wantOK: true}, - {name: "int32 zero rejected", value: int32(0), want: 0, wantOK: false}, - - // int - {name: "int positive", value: int(50000), want: 50000, wantOK: true}, - {name: "int zero rejected", value: int(0), want: 0, wantOK: false}, - // string {name: "string numeric", value: "128000", want: 128000, wantOK: true}, {name: "string trimmed", value: " 128000 ", want: 128000, wantOK: true}, @@ -165,11 +152,6 @@ func TestNumericContextLimitValue(t *testing.T) { {name: "string zero rejected", value: "0", want: 0, wantOK: false}, {name: "string negative rejected", value: "-1", want: 0, wantOK: false}, - // json.Number - {name: "json.Number valid", value: json.Number("200000"), want: 200000, wantOK: true}, - {name: "json.Number invalid rejected", value: json.Number("invalid"), want: 0, wantOK: false}, - {name: "json.Number zero rejected", value: json.Number("0"), want: 0, wantOK: false}, - // Unhandled types. {name: "bool rejected", value: true, want: 0, wantOK: false}, {name: "nil rejected", value: nil, want: 0, wantOK: false}, diff --git a/coderd/x/chatd/chatloop/metrics.go b/coderd/x/chatd/chatloop/metrics.go index ae6b118fba8..614f64c2ea3 100644 --- a/coderd/x/chatd/chatloop/metrics.go +++ b/coderd/x/chatd/chatloop/metrics.go @@ -36,7 +36,6 @@ type Metrics struct { CompactionTotal *prometheus.CounterVec StepsTotal *prometheus.CounterVec StreamRetriesTotal *prometheus.CounterVec - StreamBufferDroppedTotal prometheus.Counter FindToolsCallsTotal prometheus.Counter FindToolsEmptyTotal prometheus.Counter FindToolsMatchCount prometheus.Histogram @@ -137,12 +136,6 @@ func NewMetrics(reg prometheus.Registerer) *Metrics { Name: "find_tools_activations_total", Help: "Total deferred tool activations returned by find_tools.", }), - StreamBufferDroppedTotal: factory.NewCounter(prometheus.CounterOpts{ - Namespace: metricsNamespace, - Subsystem: metricsSubsystem, - Name: "stream_buffer_dropped_total", - Help: "Number of chat stream buffer events dropped due to the per-chat buffer cap.", - }), } } @@ -209,15 +202,6 @@ func (m *Metrics) RecordToolResultTruncated(provider, model, toolLabel string) { m.ToolResultTruncatedTotal.WithLabelValues(provider, model, toolLabel).Inc() } -// RecordStreamBufferDropped increments stream_buffer_dropped_total -// once per dropped event. No-op when m is nil. -func (m *Metrics) RecordStreamBufferDropped() { - if m == nil { - return - } - m.StreamBufferDroppedTotal.Inc() -} - // EstimatePromptSize returns a cheap byte-size estimate of a // fantasy prompt by summing the text content lengths of all // message parts. This avoids JSON marshaling overhead. diff --git a/coderd/x/chatd/chatloop/metrics_test.go b/coderd/x/chatd/chatloop/metrics_test.go index 0094867fe1c..bddfc26f340 100644 --- a/coderd/x/chatd/chatloop/metrics_test.go +++ b/coderd/x/chatd/chatloop/metrics_test.go @@ -33,24 +33,20 @@ func TestNewMetrics_RegistersAllMetrics(t *testing.T) { m.TTFTSeconds.WithLabelValues("anthropic", "claude-sonnet-4-5") m.StepsTotal.WithLabelValues("anthropic", "claude-sonnet-4-5") m.StreamRetriesTotal.WithLabelValues("anthropic", "claude-sonnet-4-5", string(codersdk.ChatErrorKindTimeout)) - // StreamBufferDroppedTotal is a plain Counter, so it's always present - // in Gather output once registered; no exerciser call is - // needed. families, err := reg.Gather() require.NoError(t, err) expected := map[string]dto.MetricType{ - "coderd_chatd_chats": dto.MetricType_GAUGE, - "coderd_chatd_message_count": dto.MetricType_HISTOGRAM, - "coderd_chatd_prompt_size_bytes": dto.MetricType_HISTOGRAM, - "coderd_chatd_tool_result_size_bytes": dto.MetricType_HISTOGRAM, - "coderd_chatd_ttft_seconds": dto.MetricType_HISTOGRAM, - "coderd_chatd_compaction_total": dto.MetricType_COUNTER, - "coderd_chatd_steps_total": dto.MetricType_COUNTER, - "coderd_chatd_stream_retries_total": dto.MetricType_COUNTER, - "coderd_chatd_stream_buffer_dropped_total": dto.MetricType_COUNTER, - "coderd_chatd_tool_errors_total": dto.MetricType_COUNTER, + "coderd_chatd_chats": dto.MetricType_GAUGE, + "coderd_chatd_message_count": dto.MetricType_HISTOGRAM, + "coderd_chatd_prompt_size_bytes": dto.MetricType_HISTOGRAM, + "coderd_chatd_tool_result_size_bytes": dto.MetricType_HISTOGRAM, + "coderd_chatd_ttft_seconds": dto.MetricType_HISTOGRAM, + "coderd_chatd_compaction_total": dto.MetricType_COUNTER, + "coderd_chatd_steps_total": dto.MetricType_COUNTER, + "coderd_chatd_stream_retries_total": dto.MetricType_COUNTER, + "coderd_chatd_tool_errors_total": dto.MetricType_COUNTER, } found := make(map[string]dto.MetricType) @@ -87,14 +83,10 @@ func TestNopMetrics_DoesNotPanic(t *testing.T) { m.CompactionTotal.WithLabelValues("google", "gemini-2.5-pro", "timeout").Inc() m.StepsTotal.WithLabelValues("anthropic", "claude-sonnet-4-5").Inc() m.StreamRetriesTotal.WithLabelValues("anthropic", "claude-sonnet-4-5", string(codersdk.ChatErrorKindTimeout)).Inc() - m.StreamBufferDroppedTotal.Inc() - // Nil-receiver guard for RecordStreamRetry and - // RecordStreamBufferDropped mirrors the existing RecordCompaction nil - // guard. + // Recording through nil metrics must not panic. var nilMetrics *chatloop.Metrics nilMetrics.RecordStreamRetry("anthropic", "claude-sonnet-4-5", chaterror.ClassifiedError{Kind: codersdk.ChatErrorKindTimeout}) - nilMetrics.RecordStreamBufferDropped() nilMetrics.RecordToolError("anthropic", "claude-sonnet-4-5", "test") } @@ -315,43 +307,6 @@ func TestRecordStreamRetry(t *testing.T) { } } -func TestRecordStreamBufferDropped(t *testing.T) { - t.Parallel() - - t.Run("nil metrics does not panic", func(t *testing.T) { - t.Parallel() - var m *chatloop.Metrics - m.RecordStreamBufferDropped() - }) - - t.Run("increments monotonically", func(t *testing.T) { - t.Parallel() - - reg := prometheus.NewRegistry() - m := chatloop.NewMetrics(reg) - - m.RecordStreamBufferDropped() - m.RecordStreamBufferDropped() - m.RecordStreamBufferDropped() - - families, err := reg.Gather() - require.NoError(t, err) - - var found bool - for _, f := range families { - if f.GetName() != "coderd_chatd_stream_buffer_dropped_total" { - continue - } - found = true - require.Len(t, f.GetMetric(), 1) - assert.Equal(t, float64(3), f.GetMetric()[0].GetCounter().GetValue()) - assert.Empty(t, f.GetMetric()[0].GetLabel(), - "stream_buffer_dropped_total must be an unlabeled counter") - } - assert.True(t, found, "stream_buffer_dropped_total metric not found") - }) -} - // requireCounter gathers metrics from reg, finds the named counter // family, and asserts it has exactly one series with the given value // and labels. diff --git a/coderd/x/chatd/chatloop/nooutput_internal_test.go b/coderd/x/chatd/chatloop/nooutput_internal_test.go index d7f9622ca7b..3d114fe3004 100644 --- a/coderd/x/chatd/chatloop/nooutput_internal_test.go +++ b/coderd/x/chatd/chatloop/nooutput_internal_test.go @@ -93,7 +93,6 @@ func TestGenerateAssistant_SilentNoOutputFinish(t *testing.T) { outcome, metrics, err := generate(t, unterminatedReasoning(fantasy.FinishReasonStop)) require.NoError(t, err) require.Empty(t, outcome.Step.Content) - require.True(t, outcome.ModelStopped) retries := promtestutil.ToFloat64(metrics.StreamRetriesTotal.WithLabelValues( "google", "test-model", string(codersdk.ChatErrorKindGeneric), diff --git a/coderd/x/chatd/chatprompt/chatprompt.go b/coderd/x/chatd/chatprompt/chatprompt.go index 692fa137112..e80882f6116 100644 --- a/coderd/x/chatd/chatprompt/chatprompt.go +++ b/coderd/x/chatd/chatprompt/chatprompt.go @@ -615,85 +615,6 @@ func ExtractToolCalls(parts []fantasy.MessagePart) []fantasy.ToolCallContent { return toolCalls } -// MarshalContent encodes message content blocks in legacy fantasy -// envelope format. Retained for backward-compatible test fixtures -// that create legacy-format DB rows. Production write paths use -// MarshalParts instead. -func MarshalContent(blocks []fantasy.Content, fileIDs map[int]uuid.UUID) (pqtype.NullRawMessage, error) { - if len(blocks) == 0 { - return pqtype.NullRawMessage{}, nil - } - - encodedBlocks := make([]json.RawMessage, 0, len(blocks)) - for i, block := range blocks { - encoded, err := json.Marshal(block) - if err != nil { - return pqtype.NullRawMessage{}, xerrors.Errorf( - "encode content block %d: %w", - i, - err, - ) - } - if fid, ok := fileIDs[i]; ok { - // Inline file_id injection into the fantasy envelope's - // data sub-object, stripping inline data. - var envelope struct { - Type string `json:"type"` - Data struct { - MediaType string `json:"media_type"` - Data json.RawMessage `json:"data,omitempty"` - FileID string `json:"file_id,omitempty"` - ProviderMetadata *json.RawMessage `json:"provider_metadata,omitempty"` - } `json:"data"` - } - if err := json.Unmarshal(encoded, &envelope); err == nil { - envelope.Data.FileID = fid.String() - envelope.Data.Data = nil - if patched, err := json.Marshal(envelope); err == nil { - encoded = patched - } - } - } - encodedBlocks = append(encodedBlocks, encoded) - } - - data, err := json.Marshal(encodedBlocks) - if err != nil { - return pqtype.NullRawMessage{}, xerrors.Errorf("encode content blocks: %w", err) - } - return pqtype.NullRawMessage{RawMessage: data, Valid: true}, nil -} - -// MarshalToolResult encodes a single tool result in the legacy -// tool-row format. Retained for test fixtures that create -// legacy-format DB rows. Production write paths use MarshalParts. -// The stored shape is -// [{"tool_call_id":…,"tool_name":…,"result":…,"is_error":…,"is_media":…}]. -func MarshalToolResult(toolCallID, toolName string, result json.RawMessage, isError bool, isMedia bool, providerExecuted bool, providerMetadata fantasy.ProviderMetadata) (pqtype.NullRawMessage, error) { - var metaJSON json.RawMessage - if len(providerMetadata) > 0 { - var err error - metaJSON, err = json.Marshal(providerMetadata) - if err != nil { - return pqtype.NullRawMessage{}, xerrors.Errorf("encode provider metadata: %w", err) - } - } - row := toolResultRaw{ - ToolCallID: toolCallID, - ToolName: toolName, - Result: result, - IsError: isError, - IsMedia: isMedia, - ProviderExecuted: providerExecuted, - ProviderMetadata: metaJSON, - } - data, err := json.Marshal([]toolResultRaw{row}) - if err != nil { - return pqtype.NullRawMessage{}, xerrors.Errorf("encode tool result: %w", err) - } - return pqtype.NullRawMessage{RawMessage: data, Valid: true}, nil -} - // PartFromContent converts fantasy content into a SDK chat message // part, preserving ProviderMetadata and ProviderExecuted fields. func PartFromContent(block fantasy.Content) codersdk.ChatMessagePart { diff --git a/coderd/x/chatd/chatprompt/export_test.go b/coderd/x/chatd/chatprompt/export_test.go index d546449b31d..9a2d86c69ec 100644 --- a/coderd/x/chatd/chatprompt/export_test.go +++ b/coderd/x/chatd/chatprompt/export_test.go @@ -1,7 +1,12 @@ package chatprompt import ( + "encoding/json" + "charm.land/fantasy" + "github.com/google/uuid" + "github.com/sqlc-dev/pqtype" + "golang.org/x/xerrors" "cdr.dev/slog/v3" "github.com/coder/coder/v2/codersdk" @@ -26,3 +31,82 @@ var NeedsNulEncodingInJSONForTest = needsNulEncodingInJSON var ToolResultContentToPartForTest = func(logger slog.Logger, content fantasy.ToolResultContent) codersdk.ChatMessagePart { return toolResultContentToPart(logger, content, nil) } + +// MarshalContent encodes message content blocks in legacy fantasy +// envelope format. Retained for backward-compatible test fixtures +// that create legacy-format DB rows. Production write paths use +// MarshalParts instead. +func MarshalContent(blocks []fantasy.Content, fileIDs map[int]uuid.UUID) (pqtype.NullRawMessage, error) { + if len(blocks) == 0 { + return pqtype.NullRawMessage{}, nil + } + + encodedBlocks := make([]json.RawMessage, 0, len(blocks)) + for i, block := range blocks { + encoded, err := json.Marshal(block) + if err != nil { + return pqtype.NullRawMessage{}, xerrors.Errorf( + "encode content block %d: %w", + i, + err, + ) + } + if fid, ok := fileIDs[i]; ok { + // Inline file_id injection into the fantasy envelope's + // data sub-object, stripping inline data. + var envelope struct { + Type string `json:"type"` + Data struct { + MediaType string `json:"media_type"` + Data json.RawMessage `json:"data,omitempty"` + FileID string `json:"file_id,omitempty"` + ProviderMetadata *json.RawMessage `json:"provider_metadata,omitempty"` + } `json:"data"` + } + if err := json.Unmarshal(encoded, &envelope); err == nil { + envelope.Data.FileID = fid.String() + envelope.Data.Data = nil + if patched, err := json.Marshal(envelope); err == nil { + encoded = patched + } + } + } + encodedBlocks = append(encodedBlocks, encoded) + } + + data, err := json.Marshal(encodedBlocks) + if err != nil { + return pqtype.NullRawMessage{}, xerrors.Errorf("encode content blocks: %w", err) + } + return pqtype.NullRawMessage{RawMessage: data, Valid: true}, nil +} + +// MarshalToolResult encodes a single tool result in the legacy +// tool-row format. Retained for test fixtures that create +// legacy-format DB rows. Production write paths use MarshalParts. +// The stored shape is +// [{"tool_call_id":…,"tool_name":…,"result":…,"is_error":…,"is_media":…}]. +func MarshalToolResult(toolCallID, toolName string, result json.RawMessage, isError bool, isMedia bool, providerExecuted bool, providerMetadata fantasy.ProviderMetadata) (pqtype.NullRawMessage, error) { + var metaJSON json.RawMessage + if len(providerMetadata) > 0 { + var err error + metaJSON, err = json.Marshal(providerMetadata) + if err != nil { + return pqtype.NullRawMessage{}, xerrors.Errorf("encode provider metadata: %w", err) + } + } + row := toolResultRaw{ + ToolCallID: toolCallID, + ToolName: toolName, + Result: result, + IsError: isError, + IsMedia: isMedia, + ProviderExecuted: providerExecuted, + ProviderMetadata: metaJSON, + } + data, err := json.Marshal([]toolResultRaw{row}) + if err != nil { + return pqtype.NullRawMessage{}, xerrors.Errorf("encode tool result: %w", err) + } + return pqtype.NullRawMessage{RawMessage: data, Valid: true}, nil +} diff --git a/coderd/x/chatd/chatstate/export_test.go b/coderd/x/chatd/chatstate/export_test.go new file mode 100644 index 00000000000..ebae900b9de --- /dev/null +++ b/coderd/x/chatd/chatstate/export_test.go @@ -0,0 +1,126 @@ +package chatstate + +import ( + "slices" + + "github.com/google/uuid" +) + +// AllowedExecutionTransitionsFrom returns a deterministic slice of +// transitions legal from `from`. Mostly used by tests to enumerate the +// matrix without leaking the internal map. +func AllowedExecutionTransitionsFrom(from ExecutionState) []Transition { + allowed := transitionMatrix[from] + out := make([]Transition, 0, len(allowed)) + for _, t := range AllExecutionTransitions { + if _, ok := allowed[t]; ok { + out = append(out, t) + } + } + return out +} + +// AllowedInputStates returns a deterministic slice of execution states +// from which `tr` is legal per transitionMatrix. Mostly used by tests +// to enumerate the matrix without leaking the internal map. +func AllowedInputStates(tr Transition) []ExecutionState { + var out []ExecutionState + for _, from := range AllExecutionStates { + if isExecutionTransitionAllowed(tr, from) { + out = append(out, from) + } + } + return out +} + +// AllowedExecutionTransitionOutputs returns the set of classified +// post-states that the transition `tr` may produce from `from` per +// transitionMatrix. The returned slice is a copy so callers may mutate +// it without affecting the underlying matrix. +// +// When `tr` is not allowed from `from`, an empty (nil) slice is +// returned. Tests use this helper to enumerate the (transition, from, +// want) triples that must be exercised by the row-level matrix tests. +func AllowedExecutionTransitionOutputs(from ExecutionState, tr Transition) []ExecutionState { + allowed, ok := transitionMatrix[from] + if !ok { + return nil + } + outputs, ok := allowed[tr] + if !ok { + return nil + } + return slices.Clone(outputs) +} + +// ChatID returns the chat ID this machine is scoped to. +func (m *ChatMachine) ChatID() uuid.UUID { return m.chatID } + +// snapshotPending returns a snapshot of the buffered messages for +// tests via [PublishBuffer.BufferedChannels]. The returned slice is a +// copy and safe to inspect without holding the buffer lock. +func (b *PublishBuffer) snapshotPending() []bufferedMessage { + b.mu.Lock() + defer b.mu.Unlock() + out := make([]bufferedMessage, len(b.pending)) + copy(out, b.pending) + return out +} + +// BufferedChannels returns just the channels of the pending messages +// in order. Primarily useful for assertions in tests. +func (b *PublishBuffer) BufferedChannels() []string { + pending := b.snapshotPending() + out := make([]string, len(pending)) + for i, m := range pending { + out[i] = m.Channel + } + return out +} + +// AllExecutionTransitions is the canonical enumeration of every +// execution-state transition that has an entry in transitionMatrix. +// Ownership transitions (Acquire, Abandon) are intentionally not part +// of this slice because they are validated independently and do not +// have a (from->to) execution mapping. +var AllExecutionTransitions = []Transition{ + TransitionCreateChat, + TransitionSetArchived, + TransitionSendMessage, + TransitionEditMessage, + TransitionRequestCompaction, + TransitionClearContext, + TransitionDeleteQueuedMessage, + TransitionPromoteQueuedMessage, + TransitionInterrupt, + TransitionCompleteRequiresAction, + TransitionRecordGenerationAttempt, + TransitionRecordRetryState, + TransitionCommitStep, + TransitionEnterRequiresAction, + TransitionFinishInterruption, + TransitionFinishTurn, + TransitionFinishError, + TransitionCancelRequiresAction, + TransitionReconcileInvalidState, +} + +// AllExecutionStates is the canonical enumeration of every value the +// classifier can return. Tests rely on this list to iterate over every +// state when verifying transition coverage. +var AllExecutionStates = []ExecutionState{ + StateN, + StateW, + StateE0, + StateE1, + StateR0, + StateR1, + StateI0, + StateI1, + StateA0, + StateA1, + StateXW, + StateXE0, + StateXE1, + StateInvalid, +} diff --git a/coderd/x/chatd/chatstate/machine.go b/coderd/x/chatd/chatstate/machine.go index afe85ae1dac..35d60817604 100644 --- a/coderd/x/chatd/chatstate/machine.go +++ b/coderd/x/chatd/chatstate/machine.go @@ -50,9 +50,6 @@ func NewChatMachine( } } -// ChatID returns the chat ID this machine is scoped to. -func (m *ChatMachine) ChatID() uuid.UUID { return m.chatID } - // Tx is the per-transaction handle passed to [ChatMachine.Update] // callbacks. It carries the active context, the transactional store, // and the chat ID. Tx does not cache mutable chat state across calls: diff --git a/coderd/x/chatd/chatstate/machine_test.go b/coderd/x/chatd/chatstate/machine_test.go index 7e3b92dadf7..c26f1475a50 100644 --- a/coderd/x/chatd/chatstate/machine_test.go +++ b/coderd/x/chatd/chatstate/machine_test.go @@ -9,12 +9,10 @@ import ( "github.com/google/uuid" "github.com/stretchr/testify/require" - "golang.org/x/xerrors" "github.com/coder/coder/v2/coderd/database" "github.com/coder/coder/v2/coderd/database/dbgen" "github.com/coder/coder/v2/coderd/database/dbtestutil" - "github.com/coder/coder/v2/coderd/database/pubsub" coderdpubsub "github.com/coder/coder/v2/coderd/pubsub" "github.com/coder/coder/v2/coderd/x/chatd/chatprompt" "github.com/coder/coder/v2/coderd/x/chatd/chatstate" @@ -27,17 +25,16 @@ import ( // helper accessors. It is intentionally NOT a generic chatd test // fixture; tests outside this package should not depend on it. type testFixture struct { - DB database.Store - PubSub pubsub.Pubsub - Pub *recordingPubsub - User database.User - Org database.Organization - Model database.ChatModelConfig + DB database.Store + Pub *recordingPubsub + User database.User + Org database.Organization + Model database.ChatModelConfig } func newTestFixture(t *testing.T) *testFixture { t.Helper() - db, ps := dbtestutil.NewDB(t) + db, _ := dbtestutil.NewDB(t) user := dbgen.User(t, db, database.User{}) org := dbgen.Organization(t, db, database.Organization{}) dbgen.OrganizationMember(t, db, database.OrganizationMember{ @@ -55,12 +52,11 @@ func newTestFixture(t *testing.T) *testFixture { }) pub := newRecordingPubsub() return &testFixture{ - DB: db, - PubSub: ps, - Pub: pub, - User: user, - Org: org, - Model: model, + DB: db, + Pub: pub, + User: user, + Org: org, + Model: model, } } @@ -227,46 +223,6 @@ func TestChatMachine_ReadLock_RejectsMissingChat(t *testing.T) { require.Empty(t, f.Pub.channels) } -func TestChatMachine_UpdatePublishesAfterCommit(t *testing.T) { - t.Parallel() - f := newTestFixture(t) - ctx := testutil.Context(t, testutil.WaitShort) - created := createTestChat(t, f) - m := chatstate.NewChatMachine(f.DB, f.Pub, created.Chat.ID) - - publishedBefore := len(f.Pub.channels) - // Run a no-op Update; snapshot bump still happens, one update message - // should follow the commit. - require.NoError(t, m.Update(ctx, func(_ *chatstate.Tx, _ database.Store) error { return nil })) - channel := coderdpubsub.ChatStateUpdateChannel(created.Chat.ID) - var found bool - for _, c := range f.Pub.channels[publishedBefore:] { - if c == channel { - found = true - break - } - } - require.True(t, found, "expected one chat:update message after commit") -} - -func TestChatMachine_FailedUpdate_PublishesNothing(t *testing.T) { - t.Parallel() - f := newTestFixture(t) - ctx := testutil.Context(t, testutil.WaitShort) - created := createTestChat(t, f) - m := chatstate.NewChatMachine(f.DB, f.Pub, created.Chat.ID) - - before := f.readChat(ctx, t, created.Chat.ID) - channelsBefore := len(f.Pub.channels) - expected := newSentinel() - cbErr := m.Update(ctx, func(_ *chatstate.Tx, _ database.Store) error { return expected }) - require.ErrorIs(t, cbErr, expected) - require.Equal(t, channelsBefore, len(f.Pub.channels), "failed update should not publish") - // snapshot_version should not have advanced. - after := f.readChat(ctx, t, created.Chat.ID) - require.Equal(t, before.SnapshotVersion, after.SnapshotVersion) -} - func TestMessageRevisionTrigger_AssignsRevisionFromSnapshot(t *testing.T) { t.Parallel() f := newTestFixture(t) @@ -359,37 +315,6 @@ func TestUpdateFlushesBufferedPublicationsAfterCommit(t *testing.T) { "exactly one new chat:update reached the inner publisher after commit") } -// TestUpdateDiscardsBufferedPublicationsOnCallbackError verifies the -// deferred Discard path: when the callback returns an error the -// transaction rolls back and no buffered messages reach the inner -// publisher. -func TestUpdateDiscardsBufferedPublicationsOnCallbackError(t *testing.T) { - t.Parallel() - f := newTestFixture(t) - ctx := testutil.Context(t, testutil.WaitShort) - created := createTestChat(t, f) - m := chatstate.NewChatMachine(f.DB, f.Pub, created.Chat.ID) - - before := f.readChat(ctx, t, created.Chat.ID) - channelsBefore := len(f.Pub.channels) - - sentinel := xerrors.New("callback boom") - err := m.Update(ctx, func(_ *chatstate.Tx, _ database.Store) error { return sentinel }) - require.ErrorIs(t, err, sentinel) - - require.Equal(t, channelsBefore, len(f.Pub.channels), - "failed update must not flush any buffered publications") - after := f.readChat(ctx, t, created.Chat.ID) - require.Equal(t, before.SnapshotVersion, after.SnapshotVersion, - "snapshot bump rolled back when callback returns error") -} - -type sentinelError struct{ msg string } - -func (s *sentinelError) Error() string { return s.msg } - -func newSentinel() error { return &sentinelError{msg: "sentinel"} } - func countChannel(channels []string, channel string) int { c := 0 for _, ch := range channels { diff --git a/coderd/x/chatd/chatstate/notify.go b/coderd/x/chatd/chatstate/notify.go index 4b7c44eee3b..3b0bf09a71d 100644 --- a/coderd/x/chatd/chatstate/notify.go +++ b/coderd/x/chatd/chatstate/notify.go @@ -99,28 +99,6 @@ func (b *PublishBuffer) Discard() { b.disabled = true } -// pending returns a snapshot of the buffered messages, primarily for -// tests via [PublishBuffer.BufferedChannels]. The returned slice is a -// copy and safe to inspect without holding the buffer lock. -func (b *PublishBuffer) snapshotPending() []bufferedMessage { - b.mu.Lock() - defer b.mu.Unlock() - out := make([]bufferedMessage, len(b.pending)) - copy(out, b.pending) - return out -} - -// BufferedChannels returns just the channels of the pending messages -// in order. Primarily useful for assertions in tests. -func (b *PublishBuffer) BufferedChannels() []string { - pending := b.snapshotPending() - out := make([]string, len(pending)) - for i, m := range pending { - out[i] = m.Channel - } - return out -} - // buildChatUpdateMessage produces the JSON payload for a // `chat:update:{chat_id}` message describing the post-transition // snapshot of chat. diff --git a/coderd/x/chatd/chatstate/notify_integration_test.go b/coderd/x/chatd/chatstate/notify_integration_test.go index 9030a56e71d..3f1b0a09b33 100644 --- a/coderd/x/chatd/chatstate/notify_integration_test.go +++ b/coderd/x/chatd/chatstate/notify_integration_test.go @@ -162,54 +162,6 @@ func TestFailedUpdatePublishesNothing(t *testing.T) { "failed update rolls back snapshot bump") } -// TestLockPublishesNothing verifies that Lock does not publish even -// though it locks the chat row. -func TestLockPublishesNothing(t *testing.T) { - t.Parallel() - f := newTestFixture(t) - ctx := testutil.Context(t, testutil.WaitShort) - created := createTestChat(t, f) - m := chatstate.NewChatMachine(f.DB, f.Pub, created.Chat.ID) - - publishedBefore := len(f.Pub.channels) - require.NoError(t, m.Lock(ctx, func(_ database.Store) error { return nil })) - require.Equal(t, publishedBefore, len(f.Pub.channels), "Lock publishes nothing") -} - -// TestPublishBufferWithRolledBackOuterTransactionPublishesNothing -// wires a chatstate machine through a PublishBuffer and exercises -// the buffer primitive directly: when the caller discards before -// flushing, the inner publisher receives nothing. ChatMachine.Update -// uses the same primitive internally with a deferred Discard; -// callers no longer drive Flush or Discard themselves. -func TestPublishBufferWithRolledBackOuterTransactionPublishesNothing(t *testing.T) { - t.Parallel() - f := newTestFixture(t) - ctx := testutil.Context(t, testutil.WaitShort) - created := createTestChat(t, f) - - // Run one normal Update to establish a stable baseline channel - // count. CreateChat plus this Update may publish chat:update - // and chat:ownership messages depending on ownership, so we - // take the snapshot after that activity settles. - m := chatstate.NewChatMachine(f.DB, f.Pub, created.Chat.ID) - require.NoError(t, m.Update(ctx, func(_ *chatstate.Tx, _ database.Store) error { return nil })) - baseline := len(f.Pub.channels) - - // Now exercise the PublishBuffer rollback path explicitly. The - // outer transaction "rolls back": the caller buffers messages, - // discards them, then flushes. The inner publisher must see - // none of the buffered messages. - buf := chatstate.NewPublishBuffer(f.Pub) - require.NoError(t, buf.Publish("chat:update:bogus", []byte("payload"))) - require.NoError(t, buf.Publish("chat:ownership", []byte("payload"))) - buf.Discard() - require.NoError(t, buf.Flush()) - - require.Equal(t, baseline, len(f.Pub.channels), - "discarded buffer publishes nothing through the inner publisher") -} - // TestChatUpdateMessagePayloadShape verifies the JSON shape of the // chat:update payload contains every field consumers depend on: // snapshot_version, history_version, queue_version, diff --git a/coderd/x/chatd/chatstate/notify_internal_test.go b/coderd/x/chatd/chatstate/notify_internal_test.go index 833f1022956..e1ba91be582 100644 --- a/coderd/x/chatd/chatstate/notify_internal_test.go +++ b/coderd/x/chatd/chatstate/notify_internal_test.go @@ -8,9 +8,8 @@ import ( ) type recordingPublisher struct { - calls []recordedCall - errOn map[string]error - failed map[string]int + calls []recordedCall + errOn map[string]error } type recordedCall struct { @@ -20,15 +19,13 @@ type recordedCall struct { func newRecordingPublisher() *recordingPublisher { return &recordingPublisher{ - errOn: map[string]error{}, - failed: map[string]int{}, + errOn: map[string]error{}, } } func (r *recordingPublisher) Publish(channel string, payload []byte) error { r.calls = append(r.calls, recordedCall{Channel: channel, Payload: append([]byte(nil), payload...)}) if err, ok := r.errOn[channel]; ok { - r.failed[channel]++ return err } return nil diff --git a/coderd/x/chatd/chatstate/state.go b/coderd/x/chatd/chatstate/state.go index be22f25f297..7f144de1dcc 100644 --- a/coderd/x/chatd/chatstate/state.go +++ b/coderd/x/chatd/chatstate/state.go @@ -47,26 +47,6 @@ const ( // String implements fmt.Stringer. func (s ExecutionState) String() string { return string(s) } -// AllExecutionStates is the canonical enumeration of every value the -// classifier can return. Tests rely on this list to iterate over every -// state when verifying transition coverage. -var AllExecutionStates = []ExecutionState{ - StateN, - StateW, - StateE0, - StateE1, - StateR0, - StateR1, - StateI0, - StateI1, - StateA0, - StateA1, - StateXW, - StateXE0, - StateXE1, - StateInvalid, -} - // IsRunnable returns true for the execution states that the chat // worker is allowed to acquire and drive forward: R0, R1, I0, I1, // A0, and A1. Requires-action states need worker ownership for diff --git a/coderd/x/chatd/chatstate/synthetic_cancellation_test.go b/coderd/x/chatd/chatstate/synthetic_cancellation_test.go index d4056c34929..37c74618ce5 100644 --- a/coderd/x/chatd/chatstate/synthetic_cancellation_test.go +++ b/coderd/x/chatd/chatstate/synthetic_cancellation_test.go @@ -1,7 +1,6 @@ package chatstate_test import ( - "context" "encoding/json" "testing" @@ -510,7 +509,3 @@ func testFinishInterruptionRejectsOutstandingToolCalls(t *testing.T) { require.Equal(t, publishedBefore, len(f.Pub.channels), "failed FinishInterruption publishes nothing") } - -// ensure unused imports don't break the build if any helper is -// removed later. -var _ = context.Background diff --git a/coderd/x/chatd/chatstate/transition.go b/coderd/x/chatd/chatstate/transition.go index ea82171e847..bbd723b6a20 100644 --- a/coderd/x/chatd/chatstate/transition.go +++ b/coderd/x/chatd/chatstate/transition.go @@ -1,7 +1,5 @@ package chatstate -import "slices" - // Transition is the enumeration of transitions implemented by the // state machine. Values intentionally match the names of the public // methods on [Tx] (and [CreateChat]). The transition matrix below @@ -35,33 +33,6 @@ const ( // String implements fmt.Stringer. func (t Transition) String() string { return string(t) } -// AllExecutionTransitions is the canonical enumeration of every -// execution-state transition that has an entry in the matrix below. -// Ownership transitions (Acquire, Abandon) are intentionally not part -// of this slice because they are validated independently and do not -// have a (from->to) execution mapping. -var AllExecutionTransitions = []Transition{ - TransitionCreateChat, - TransitionSetArchived, - TransitionSendMessage, - TransitionEditMessage, - TransitionRequestCompaction, - TransitionClearContext, - TransitionDeleteQueuedMessage, - TransitionPromoteQueuedMessage, - TransitionInterrupt, - TransitionCompleteRequiresAction, - TransitionRecordGenerationAttempt, - TransitionRecordRetryState, - TransitionCommitStep, - TransitionEnterRequiresAction, - TransitionFinishInterruption, - TransitionFinishTurn, - TransitionFinishError, - TransitionCancelRequiresAction, - TransitionReconcileInvalidState, -} - // transitionMatrix is the in-code representation of the chat execution // state transition table. Each entry maps an input state to the set of // allowed transitions together with the possible classified output @@ -186,50 +157,3 @@ func requireExecutionTransition(t Transition, from ExecutionState) error { } return newTransitionError(t, from, "") } - -// AllowedExecutionTransitionsFrom returns a deterministic slice of -// transitions legal from `from`. Mostly used by tests to enumerate the -// matrix without leaking the internal map. -func AllowedExecutionTransitionsFrom(from ExecutionState) []Transition { - allowed := transitionMatrix[from] - out := make([]Transition, 0, len(allowed)) - for _, t := range AllExecutionTransitions { - if _, ok := allowed[t]; ok { - out = append(out, t) - } - } - return out -} - -// AllowedInputStates returns a deterministic slice of execution states -// from which `tr` is legal per the matrix above. Mostly used by tests -// to enumerate the matrix without leaking the internal map. -func AllowedInputStates(tr Transition) []ExecutionState { - var out []ExecutionState - for _, from := range AllExecutionStates { - if isExecutionTransitionAllowed(tr, from) { - out = append(out, from) - } - } - return out -} - -// AllowedExecutionTransitionOutputs returns the set of classified -// post-states that the transition `tr` may produce from `from` per -// the matrix above. The returned slice is a copy so callers may mutate -// it without affecting the underlying matrix. -// -// When `tr` is not allowed from `from`, an empty (nil) slice is -// returned. Tests use this helper to enumerate the (transition, from, -// want) triples that must be exercised by the row-level matrix tests. -func AllowedExecutionTransitionOutputs(from ExecutionState, tr Transition) []ExecutionState { - allowed, ok := transitionMatrix[from] - if !ok { - return nil - } - outputs, ok := allowed[tr] - if !ok { - return nil - } - return slices.Clone(outputs) -} diff --git a/coderd/x/chatd/chatstate/transitions.go b/coderd/x/chatd/chatstate/transitions.go index 6a607597a6f..79d74803bb0 100644 --- a/coderd/x/chatd/chatstate/transitions.go +++ b/coderd/x/chatd/chatstate/transitions.go @@ -853,7 +853,6 @@ type PromoteQueuedMessageInput struct { type PromoteQueuedMessageResult struct { QueuedMessage database.ChatQueuedMessage InsertedMessage *database.ChatMessage - ReorderedQueueOnly bool CancellationMessages []database.ChatMessage } @@ -874,14 +873,13 @@ func (tx *Tx) PromoteQueuedMessage(input PromoteQueuedMessageInput) (PromoteQueu if err != nil { return PromoteQueuedMessageResult{}, xerrors.Errorf("get queued: %w", err) } - rows, err := tx.store.ReorderChatQueuedMessageToHead(tx.ctx, database.ReorderChatQueuedMessageToHeadParams{ + _, err = tx.store.ReorderChatQueuedMessageToHead(tx.ctx, database.ReorderChatQueuedMessageToHeadParams{ ID: input.QueuedMessageID, ChatID: tx.chatID, }) if err != nil { return PromoteQueuedMessageResult{}, xerrors.Errorf("reorder queue: %w", err) } - reorderOnly := rows > 0 // R1/I1: leave the target at the queue head and transition to // status `interrupting` so the worker can drain the in-flight @@ -899,8 +897,7 @@ func (tx *Tx) PromoteQueuedMessage(input PromoteQueuedMessageInput) (PromoteQueu return PromoteQueuedMessageResult{}, xerrors.Errorf("set interrupting: %w", err) } return PromoteQueuedMessageResult{ - QueuedMessage: target, - ReorderedQueueOnly: reorderOnly, + QueuedMessage: target, }, nil } @@ -948,7 +945,6 @@ func (tx *Tx) PromoteQueuedMessage(input PromoteQueuedMessageInput) (PromoteQueu QueuedMessage: target, InsertedMessage: &insertedUserMsg, CancellationMessages: cancellations, - ReorderedQueueOnly: reorderOnly, }, nil } diff --git a/coderd/x/chatd/chatstate/trigger_test.go b/coderd/x/chatd/chatstate/trigger_test.go index 004e1704648..bfa030c1df1 100644 --- a/coderd/x/chatd/chatstate/trigger_test.go +++ b/coderd/x/chatd/chatstate/trigger_test.go @@ -25,7 +25,7 @@ type triggerFixture struct { func newTriggerFixture(t *testing.T) *triggerFixture { t.Helper() - db, ps, sqlDB := dbtestutil.NewDBWithSQLDB(t) + db, _, sqlDB := dbtestutil.NewDBWithSQLDB(t) user := dbgen.User(t, db, database.User{}) org := dbgen.Organization(t, db, database.Organization{}) dbgen.OrganizationMember(t, db, database.OrganizationMember{ @@ -41,12 +41,11 @@ func newTriggerFixture(t *testing.T) *triggerFixture { IsDefault: true, }) f := &testFixture{ - DB: db, - PubSub: ps, - Pub: newRecordingPubsub(), - User: user, - Org: org, - Model: model, + DB: db, + Pub: newRecordingPubsub(), + User: user, + Org: org, + Model: model, } return &triggerFixture{f: f, sqlDB: sqlDB} } diff --git a/coderd/x/chatd/chattool/mcpworkspace.go b/coderd/x/chatd/chattool/mcpworkspace.go index 7f9e90524f6..439af90bf92 100644 --- a/coderd/x/chatd/chattool/mcpworkspace.go +++ b/coderd/x/chatd/chattool/mcpworkspace.go @@ -4,8 +4,6 @@ import ( "context" "encoding/base64" "encoding/json" - "errors" - "net/http" "regexp" "slices" "strconv" @@ -13,7 +11,6 @@ import ( "charm.land/fantasy" - "github.com/coder/coder/v2/codersdk" "github.com/coder/coder/v2/codersdk/workspacesdk" ) @@ -39,33 +36,9 @@ type WorkspaceMCPTool struct { // calls the original tool name. info.Name is the sanitized, provider-safe // name shown to the model, so the two can differ when the server or tool // name contains characters outside the provider's allowed set. - routingName string - getConn func(context.Context) (workspacesdk.AgentConn, error) - providerOpts fantasy.ProviderOptions - invalidateCache func() -} - -// NewWorkspaceMCPTool creates a single tool wrapper from an MCPToolInfo -// discovered on a workspace agent. Each tool proxies calls back through the -// agent connection. The optional invalidateCache callback is invoked when -// CallMCPTool returns a 404 error, indicating that the server was removed and -// the chat's cached tool list should be dropped. -// -// The model-facing name is sanitized to the provider-safe character set and -// length so a server or tool name containing a character such as "@" cannot -// produce an invalid tool name that the provider rejects. The unsanitized name -// is retained as routingName so the workspace agent can still route the call to -// the original server and tool. -// -// Prefer NewWorkspaceMCPTools when building a set of tools, because that path -// also disambiguates names that collide after sanitization. This single-tool -// constructor cannot detect collisions on its own. -func NewWorkspaceMCPTool( - tool workspacesdk.MCPToolInfo, - getConn func(context.Context) (workspacesdk.AgentConn, error), - invalidateCache func(), -) *WorkspaceMCPTool { - return buildWorkspaceMCPTool(tool, sanitizeModelToolName(tool.Name), getConn, invalidateCache) + routingName string + getConn func(context.Context) (workspacesdk.AgentConn, error) + providerOpts fantasy.ProviderOptions } // NewWorkspaceMCPTools builds wrappers for a set of workspace MCP tools. @@ -81,7 +54,6 @@ func NewWorkspaceMCPTool( func NewWorkspaceMCPTools( infos []workspacesdk.MCPToolInfo, getConn func(context.Context) (workspacesdk.AgentConn, error), - invalidateCache func(), ) []fantasy.AgentTool { sorted := slices.Clone(infos) slices.SortFunc(sorted, func(a, b workspacesdk.MCPToolInfo) int { @@ -91,7 +63,7 @@ func NewWorkspaceMCPTools( seen := make(map[string]struct{}, len(sorted)) for _, info := range sorted { modelName := uniqueModelToolName(sanitizeModelToolName(info.Name), seen) - tools = append(tools, buildWorkspaceMCPTool(info, modelName, getConn, invalidateCache)) + tools = append(tools, buildWorkspaceMCPTool(info, modelName, getConn)) } return tools } @@ -100,7 +72,6 @@ func buildWorkspaceMCPTool( tool workspacesdk.MCPToolInfo, modelName string, getConn func(context.Context) (workspacesdk.AgentConn, error), - invalidateCache func(), ) *WorkspaceMCPTool { required := tool.Required if required == nil { @@ -114,9 +85,8 @@ func buildWorkspaceMCPTool( Required: required, Parallel: true, }, - routingName: tool.Name, - getConn: getConn, - invalidateCache: invalidateCache, + routingName: tool.Name, + getConn: getConn, } } @@ -201,15 +171,6 @@ func (t *WorkspaceMCPTool) Run( Arguments: args, }) if err != nil { - // If the agent returns a 404 (ErrUnknownServer), the - // server was removed or renamed. Invalidate the chat's - // cached tool list so the next turn refetches. - var coderErr *codersdk.Error - if errors.As(err, &coderErr) && coderErr.StatusCode() == http.StatusNotFound { - if t.invalidateCache != nil { - t.invalidateCache() - } - } return fantasy.NewTextErrorResponse(err.Error()), nil } diff --git a/coderd/x/chatd/chattool/mcpworkspace_test.go b/coderd/x/chatd/chattool/mcpworkspace_test.go index 1e32d1a1394..a04066c5b80 100644 --- a/coderd/x/chatd/chattool/mcpworkspace_test.go +++ b/coderd/x/chatd/chattool/mcpworkspace_test.go @@ -4,7 +4,6 @@ import ( "context" "net/http" "strings" - "sync/atomic" "testing" "charm.land/fantasy" @@ -27,18 +26,17 @@ func (f *fakeAgentConn) CallMCPTool(ctx context.Context, req workspacesdk.CallMC return f.callMCPToolFunc(ctx, req) } -func TestWorkspaceMCPTool_InvalidateOn404(t *testing.T) { +func TestWorkspaceMCPTool_Errors(t *testing.T) { t.Parallel() - t.Run("404ErrorInvalidatesCache", func(t *testing.T) { + t.Run("NotFound", func(t *testing.T) { t.Parallel() - var invalidated atomic.Bool - tool := chattool.NewWorkspaceMCPTool( - workspacesdk.MCPToolInfo{ + tool := chattool.NewWorkspaceMCPTools( + []workspacesdk.MCPToolInfo{{ Name: "test__echo", Description: "test tool", - }, + }}, func(ctx context.Context) (workspacesdk.AgentConn, error) { return &fakeAgentConn{ callMCPToolFunc: func(_ context.Context, _ workspacesdk.CallMCPToolRequest) (workspacesdk.CallMCPToolResponse, error) { @@ -52,25 +50,21 @@ func TestWorkspaceMCPTool_InvalidateOn404(t *testing.T) { }, }, nil }, - func() { invalidated.Store(true) }, - ) + )[0] resp, err := tool.Run(context.Background(), fantasy.ToolCall{}) require.NoError(t, err) assert.True(t, resp.IsError, "response should be an error") - assert.True(t, invalidated.Load(), - "invalidateCache should fire on 404") }) - t.Run("Non404DoesNotInvalidate", func(t *testing.T) { + t.Run("BadGateway", func(t *testing.T) { t.Parallel() - var invalidated atomic.Bool - tool := chattool.NewWorkspaceMCPTool( - workspacesdk.MCPToolInfo{ + tool := chattool.NewWorkspaceMCPTools( + []workspacesdk.MCPToolInfo{{ Name: "test__echo", Description: "test tool", - }, + }}, func(ctx context.Context) (workspacesdk.AgentConn, error) { return &fakeAgentConn{ callMCPToolFunc: func(_ context.Context, _ workspacesdk.CallMCPToolRequest) (workspacesdk.CallMCPToolResponse, error) { @@ -83,25 +77,21 @@ func TestWorkspaceMCPTool_InvalidateOn404(t *testing.T) { }, }, nil }, - func() { invalidated.Store(true) }, - ) + )[0] resp, err := tool.Run(context.Background(), fantasy.ToolCall{}) require.NoError(t, err) assert.True(t, resp.IsError) - assert.False(t, invalidated.Load(), - "invalidateCache should NOT fire on non-404 error") }) - t.Run("ToolLevelErrorNoInvalidation", func(t *testing.T) { + t.Run("ToolError", func(t *testing.T) { t.Parallel() - var invalidated atomic.Bool - tool := chattool.NewWorkspaceMCPTool( - workspacesdk.MCPToolInfo{ + tool := chattool.NewWorkspaceMCPTools( + []workspacesdk.MCPToolInfo{{ Name: "test__echo", Description: "test tool", - }, + }}, func(ctx context.Context) (workspacesdk.AgentConn, error) { return &fakeAgentConn{ callMCPToolFunc: func(_ context.Context, _ workspacesdk.CallMCPToolRequest) (workspacesdk.CallMCPToolResponse, error) { @@ -114,44 +104,11 @@ func TestWorkspaceMCPTool_InvalidateOn404(t *testing.T) { }, }, nil }, - func() { invalidated.Store(true) }, - ) + )[0] resp, err := tool.Run(context.Background(), fantasy.ToolCall{}) require.NoError(t, err) assert.True(t, resp.IsError) - assert.False(t, invalidated.Load(), - "invalidateCache should NOT fire on tool-level error (HTTP 200)") - }) - - t.Run("NilInvalidateCallbackSafe", func(t *testing.T) { - t.Parallel() - - tool := chattool.NewWorkspaceMCPTool( - workspacesdk.MCPToolInfo{ - Name: "test__echo", - Description: "test tool", - }, - func(ctx context.Context) (workspacesdk.AgentConn, error) { - return &fakeAgentConn{ - callMCPToolFunc: func(_ context.Context, _ workspacesdk.CallMCPToolRequest) (workspacesdk.CallMCPToolResponse, error) { - return workspacesdk.CallMCPToolResponse{}, codersdk.NewError( - http.StatusNotFound, - codersdk.Response{ - Message: "MCP tool call failed.", - Detail: `unknown MCP server: "test"`, - }, - ) - }, - }, nil - }, - nil, - ) - - // Should not panic. - resp, err := tool.Run(context.Background(), fantasy.ToolCall{}) - require.NoError(t, err) - assert.True(t, resp.IsError) }) } @@ -162,13 +119,13 @@ func TestWorkspaceMCPTool_SanitizesModelNameKeepsRoutingName(t *testing.T) { t.Parallel() var gotToolName string - tool := chattool.NewWorkspaceMCPTool( - workspacesdk.MCPToolInfo{ + tool := chattool.NewWorkspaceMCPTools( + []workspacesdk.MCPToolInfo{{ // "@" is outside the provider's allowed tool-name set; the // model must never see it or the whole request is rejected. Name: "weather@home__get_forecast", Description: "test tool", - }, + }}, func(_ context.Context) (workspacesdk.AgentConn, error) { return &fakeAgentConn{ callMCPToolFunc: func(_ context.Context, req workspacesdk.CallMCPToolRequest) (workspacesdk.CallMCPToolResponse, error) { @@ -179,8 +136,7 @@ func TestWorkspaceMCPTool_SanitizesModelNameKeepsRoutingName(t *testing.T) { }, }, nil }, - nil, - ) + )[0] // The model-facing name is sanitized to the provider-safe set. assert.Equal(t, "weather_home__get_forecast", tool.Info().Name) @@ -196,11 +152,11 @@ func TestWorkspaceMCPTool_SanitizesModelNameKeepsRoutingName(t *testing.T) { t.Run("ValidNameUnchanged", func(t *testing.T) { t.Parallel() - tool := chattool.NewWorkspaceMCPTool( - workspacesdk.MCPToolInfo{ + tool := chattool.NewWorkspaceMCPTools( + []workspacesdk.MCPToolInfo{{ Name: "github__create_issue", Description: "test tool", - }, + }}, func(_ context.Context) (workspacesdk.AgentConn, error) { return &fakeAgentConn{ callMCPToolFunc: func(_ context.Context, _ workspacesdk.CallMCPToolRequest) (workspacesdk.CallMCPToolResponse, error) { @@ -208,8 +164,7 @@ func TestWorkspaceMCPTool_SanitizesModelNameKeepsRoutingName(t *testing.T) { }, }, nil }, - nil, - ) + )[0] // A name already within the allowed set is left untouched. assert.Equal(t, "github__create_issue", tool.Info().Name) @@ -221,11 +176,11 @@ func TestWorkspaceMCPTool_SanitizesModelNameKeepsRoutingName(t *testing.T) { // A name longer than the provider limit is truncated. "srv__" plus a // 64-char tool name exceeds the 64-char cap. longName := "srv__" + strings.Repeat("a", 64) - tool := chattool.NewWorkspaceMCPTool( - workspacesdk.MCPToolInfo{ + tool := chattool.NewWorkspaceMCPTools( + []workspacesdk.MCPToolInfo{{ Name: longName, Description: "test tool", - }, + }}, func(_ context.Context) (workspacesdk.AgentConn, error) { return &fakeAgentConn{ callMCPToolFunc: func(_ context.Context, _ workspacesdk.CallMCPToolRequest) (workspacesdk.CallMCPToolResponse, error) { @@ -233,8 +188,7 @@ func TestWorkspaceMCPTool_SanitizesModelNameKeepsRoutingName(t *testing.T) { }, }, nil }, - nil, - ) + )[0] // The model-facing name is capped at the strictest provider limit. assert.LessOrEqual(t, len(tool.Info().Name), 64) @@ -261,7 +215,7 @@ func TestNewWorkspaceMCPTools_DisambiguatesCollidingNames(t *testing.T) { {Name: "foo_bar__echo"}, } - tools := chattool.NewWorkspaceMCPTools(infos, getConn, nil) + tools := chattool.NewWorkspaceMCPTools(infos, getConn) require.Len(t, tools, 2) names := []string{tools[0].Info().Name, tools[1].Info().Name} diff --git a/coderd/x/chatd/chattool/skill.go b/coderd/x/chatd/chattool/skill.go index f93786af464..d81308a22da 100644 --- a/coderd/x/chatd/chattool/skill.go +++ b/coderd/x/chatd/chattool/skill.go @@ -1,7 +1,6 @@ package chattool import ( - "cmp" "context" "fmt" "io" @@ -34,9 +33,6 @@ type SkillMeta struct { // Dir is the absolute path to the skill directory inside // the workspace filesystem. Dir string - // MetaFile is the basename of the skill meta file (e.g. - // "SKILL.md"). When empty, DefaultSkillMetaFile is used. - MetaFile string // Meta is the verbatim skill meta file (SKILL.md) content the // agent pushed in the workspace context snapshot: front-matter // plus body. When present, read_skill serves the body from it @@ -213,7 +209,7 @@ func bestEffortSkillFiles( if err != nil { return nil } - files, err := listSkillFiles(ctx, conn, skill.Dir, cmp.Or(skill.MetaFile, DefaultSkillMetaFile)) + files, err := listSkillFiles(ctx, conn, skill.Dir, DefaultSkillMetaFile) if err != nil { return nil } diff --git a/coderd/x/chatd/context_prompt.go b/coderd/x/chatd/context_prompt.go index 0646109e544..7434c3700b7 100644 --- a/coderd/x/chatd/context_prompt.go +++ b/coderd/x/chatd/context_prompt.go @@ -275,13 +275,9 @@ func contextResourcesToPrompt( if decodedBody.GetName() == "" { continue } - // source is the skill directory. MetaFile is left empty so - // chattool falls back to DefaultSkillMetaFile ("SKILL.md"). - // SkillMetaBody carries no meta file name, so a non-default - // CODER_AGENT_EXP_SKILL_META_FILE is not preserved on this - // path, unlike the per-turn discovery path. Meta carries the - // verbatim SKILL.md so read_skill serves the body from the - // pin instead of dialing the workspace. + // Source is the skill directory. Meta carries the verbatim + // SKILL.md so read_skill serves the pinned body without + // dialing the workspace. skills = append(skills, chattool.SkillMeta{ Name: decodedBody.GetName(), Description: decodedBody.GetDescription(), diff --git a/coderd/x/chatd/context_prompt_internal_test.go b/coderd/x/chatd/context_prompt_internal_test.go index 96738f67831..5e5ad9d6ff4 100644 --- a/coderd/x/chatd/context_prompt_internal_test.go +++ b/coderd/x/chatd/context_prompt_internal_test.go @@ -109,8 +109,6 @@ func TestContextResourcesToPrompt(t *testing.T) { require.Equal(t, "deploy", skills[0].Name) require.Equal(t, "Deploy the app", skills[0].Description) require.Equal(t, "/home/coder/.coder/skills/deploy", skills[0].Dir) - // MetaFile is left empty so chattool defaults to SKILL.md. - require.Empty(t, skills[0].MetaFile) // Meta carries the pushed SKILL.md so read_skill serves the body // from the pin without dialing the workspace. require.Equal(t, []byte("# deploy"), skills[0].Meta) diff --git a/coderd/x/chatd/generation.go b/coderd/x/chatd/generation.go index 528e518cb36..c25f918c129 100644 --- a/coderd/x/chatd/generation.go +++ b/coderd/x/chatd/generation.go @@ -61,7 +61,6 @@ type generationPrepared struct { ActiveTools []string AllowInactiveTools map[string]bool ProviderTools []chatloop.ProviderTool - ModelRoute aiGatewayModelRoute ModelBuildOptions modelBuildOptions // ResolvedProvider is the configured provider identity used to label @@ -114,11 +113,9 @@ type generationDebug struct { // generationOutcome describes a completed generation outcome. type generationOutcome struct { - Chat database.Chat - Kind runnerActionKind - WatchEventKind codersdk.ChatWatchEventKind - LastError string - PromotedMessageID int64 + Chat database.Chat + Kind runnerActionKind + LastError string } type generationActionKind string @@ -148,10 +145,9 @@ var errCompactionStillOverLimit = chaterror.WithClassification( ) type generationDecision struct { - kind generationActionKind - localToolCalls []fantasy.ToolCallContent - finishReason generationFinishReason - promotedMessageID int64 + kind generationActionKind + localToolCalls []fantasy.ToolCallContent + finishReason generationFinishReason // forced marks a compact action triggered by a manual // compaction request rather than the usage threshold. forced bool @@ -512,7 +508,7 @@ func (s *taskStarter) StartGeneration(ctx context.Context, input chatWorkerTaskS return s.enterRequiresAction(ctx, machine, input) case generationActionFinishTurn: cleanup() - return s.finishGenerationTurn(ctx, machine, input, decision, generationAttemptNotRequired) + return s.finishGenerationTurn(ctx, machine, input, generationAttemptNotRequired) case generationActionGenerateAssistant: actionErr = s.generateAssistant(ctx, machine, input, prepared) case generationActionExecuteLocalTools: @@ -530,9 +526,6 @@ func (s *taskStarter) StartGeneration(ctx context.Context, input chatWorkerTaskS if ctx.Err() != nil && errors.Is(actionErr, context.Canceled) { return errors.Join(errTaskExpectedExit, xerrors.Errorf("generation action: %w", actionErr), ctx.Err()) } - if errors.Is(actionErr, chatloop.ErrInterrupted) { - return errors.Join(errTaskExpectedExit, xerrors.Errorf("generation action: %w", actionErr)) - } if errors.Is(actionErr, errTaskExpectedExit) { return xerrors.Errorf("generation action: %w", actionErr) } @@ -758,7 +751,7 @@ func (s *taskStarter) generateAssistant( return xerrors.Errorf("generate assistant: %w", err) } if len(outcome.Step.Content) == 0 { - return s.finishGenerationTurn(ctx, machine, input, generationDecision{kind: generationActionFinishTurn, finishReason: generationFinishReasonComplete}, requireGenerationAttempt(attempt.number)) + return s.finishGenerationTurn(ctx, machine, input, requireGenerationAttempt(attempt.number)) } preflight, err := s.admitStepToolCalls(ctx, input, prepared, outcome.Step.Content) if err != nil { @@ -1078,7 +1071,6 @@ func (s *taskStarter) generateCompaction( persistedPreResult := &chathooks.Result{UserMessage: preResult.GetUserMessage()} commitMessages, err := applyHookResultMessages(stepMessagesForCommit{ Messages: messages.Messages, - VisibleIndexes: visibleMessageIndexes(messages.Messages), ConsumeCompactionRequest: true, }, []*chathooks.Result{persistedPreResult}, prepared.ModelConfigID) if err != nil { @@ -1226,7 +1218,7 @@ func (s *taskStarter) commitGenerationStep( if commitHooks.PostCommitError != nil { return s.finishGenerationError(ctx, machine, input, commitHooks.PostCommitError, requireGenerationAttempt(attempt)) } - return s.finishGenerationTurn(ctx, machine, input, generationDecision{kind: generationActionFinishTurn, finishReason: generationFinishReasonComplete}, requireGenerationAttempt(attempt)) + return s.finishGenerationTurn(ctx, machine, input, requireGenerationAttempt(attempt)) } failClosed := commitHooks.PostCommitError != nil var postCommitLastError pqtype.NullRawMessage @@ -1282,10 +1274,9 @@ func (s *taskStarter) commitGenerationStep( return xerrors.Errorf("publish watch and route: %w", err) } return s.afterGenerationOutcome(postCommitCtx, generationOutcome{ - Chat: committed, - Kind: runnerActionKindFinishError, - WatchEventKind: codersdk.ChatWatchEventKindStatusChange, - LastError: postCommitMessage, + Chat: committed, + Kind: runnerActionKindFinishError, + LastError: postCommitMessage, }) } s.routeStateHint(ctx, stateUpdateFromChat(committed)) @@ -1322,9 +1313,8 @@ func (s *taskStarter) enterRequiresAction( return xerrors.Errorf("publish watch and route: %w", err) } return s.afterGenerationOutcome(ctx, generationOutcome{ - Chat: committed, - Kind: runnerActionKindEnterRequiresAction, - WatchEventKind: codersdk.ChatWatchEventKindActionRequired, + Chat: committed, + Kind: runnerActionKindEnterRequiresAction, }) } @@ -1380,7 +1370,6 @@ func (s *taskStarter) completeGenerationTurn( ctx context.Context, input chatWorkerTaskStartInput, committed database.Chat, - promotedMessageID int64, ) error { input.StopNudges.reset() input.DebugTurn.RecordOutcome(chatdebug.StatusCompleted) @@ -1390,10 +1379,8 @@ func (s *taskStarter) completeGenerationTurn( return xerrors.Errorf("publish watch and route: %w", err) } if err := s.afterGenerationOutcome(ctx, generationOutcome{ - Chat: committed, - Kind: runnerActionKindFinishTurn, - WatchEventKind: codersdk.ChatWatchEventKindStatusChange, - PromotedMessageID: promotedMessageID, + Chat: committed, + Kind: runnerActionKindFinishTurn, }); err != nil { return xerrors.Errorf("after generation outcome: %w", err) } @@ -1405,7 +1392,6 @@ func (s *taskStarter) finishGenerationTurnWithoutHook( ctx context.Context, machine *chatstate.ChatMachine, input chatWorkerTaskStartInput, - decision generationDecision, fence generationAttemptFence, ) error { var committed database.Chat @@ -1417,9 +1403,6 @@ func (s *taskStarter) finishGenerationTurnWithoutHook( if err != nil { return xerrors.Errorf("tx.FinishTurn: %w", err) } - if finishResult.PromotedMessage != nil { - decision.promotedMessageID = finishResult.PromotedMessage.ID - } committed = finishResult.Chat return nil }) @@ -1428,18 +1411,17 @@ func (s *taskStarter) finishGenerationTurnWithoutHook( recordGenerationFinishFailure(input.DebugTurn, err) return err } - return s.completeGenerationTurn(ctx, input, committed, decision.promotedMessageID) + return s.completeGenerationTurn(ctx, input, committed) } func (s *taskStarter) finishGenerationTurn( ctx context.Context, machine *chatstate.ChatMachine, input chatWorkerTaskStartInput, - decision generationDecision, fence generationAttemptFence, ) error { if !s.server.hooks.Enabled() { - return s.finishGenerationTurnWithoutHook(ctx, machine, input, decision, fence) + return s.finishGenerationTurnWithoutHook(ctx, machine, input, fence) } var chat database.Chat var messages []database.ChatMessage @@ -1490,9 +1472,6 @@ func (s *taskStarter) finishGenerationTurn( if err != nil { return xerrors.Errorf("tx.FinishTurn: %w", err) } - if finishResult.PromotedMessage != nil { - decision.promotedMessageID = finishResult.PromotedMessage.ID - } committed = finishResult.Chat return nil } @@ -1518,7 +1497,7 @@ func (s *taskStarter) finishGenerationTurn( Kind: runnerActionKind(generationActionGenerateAssistant), }) } - return s.completeGenerationTurn(ctx, input, committed, decision.promotedMessageID) + return s.completeGenerationTurn(ctx, input, committed) } func (s *taskStarter) finishGenerationError( @@ -1568,10 +1547,9 @@ func (s *taskStarter) finishGenerationError( return xerrors.Errorf("publish watch and route: %w", err) } return s.afterGenerationOutcome(ctx, generationOutcome{ - Chat: committed, - Kind: runnerActionKindFinishError, - WatchEventKind: codersdk.ChatWatchEventKindStatusChange, - LastError: message, + Chat: committed, + Kind: runnerActionKindFinishError, + LastError: message, }) } diff --git a/coderd/x/chatd/generation_preparer.go b/coderd/x/chatd/generation_preparer.go index 20606e132fc..28088cdf7ce 100644 --- a/coderd/x/chatd/generation_preparer.go +++ b/coderd/x/chatd/generation_preparer.go @@ -768,7 +768,6 @@ func (server *Server) prepareGeneration( ActiveTools: activeToolNames, AllowInactiveTools: allowInactiveTools, ProviderTools: providerTools, - ModelRoute: modelRoute, ModelBuildOptions: modelOpts, ResolvedProvider: resolved.resolvedProvider, ModelConfigID: modelConfig.ID, diff --git a/coderd/x/chatd/hook_server.go b/coderd/x/chatd/hook_server.go index 4a6bc17f4c0..1595d1b8efd 100644 --- a/coderd/x/chatd/hook_server.go +++ b/coderd/x/chatd/hook_server.go @@ -59,7 +59,6 @@ func insertHookResultMessages( } else { messages.Messages = append(messages.Messages, rows...) } - messages.VisibleIndexes = visibleMessageIndexes(messages.Messages) } return messages, nil } diff --git a/coderd/x/chatd/mcp_tool_search_internal_test.go b/coderd/x/chatd/mcp_tool_search_internal_test.go index 7c2834290b4..86d9f3216f9 100644 --- a/coderd/x/chatd/mcp_tool_search_internal_test.go +++ b/coderd/x/chatd/mcp_tool_search_internal_test.go @@ -315,7 +315,7 @@ func TestCollectDeferredMCPCandidates(t *testing.T) { require.Equal(t, []string{"github__create_issue", "linear__create_issue"}, names(collectDeferredMCPCandidates(noWorkspace))) longServer := strings.Repeat("s", 70) - truncated := chattool.NewWorkspaceMCPTool(workspacesdk.MCPToolInfo{Name: longServer + "__echo"}, nil, nil) + truncated := chattool.NewWorkspaceMCPTools([]workspacesdk.MCPToolInfo{{Name: longServer + "__echo"}}, nil)[0] require.NotContains(t, truncated.Info().Name, "__", "sanitization must drop the separator for this scenario to be meaningful") truncatedInput := deferredMCPCandidateInput{ @@ -325,7 +325,7 @@ func TestCollectDeferredMCPCandidates(t *testing.T) { require.Equal(t, longServer, collectDeferredMCPCandidates(truncatedInput)[0].server, "the server comes from the unsanitized routing name, not the capped model name") - padded := chattool.NewWorkspaceMCPTool(workspacesdk.MCPToolInfo{Name: " everything __echo"}, nil, nil) + padded := chattool.NewWorkspaceMCPTools([]workspacesdk.MCPToolInfo{{Name: " everything __echo"}}, nil)[0] paddedInput := deferredMCPCandidateInput{ workspaceMCPTools: []fantasy.AgentTool{padded}, includeWorkspaceTools: true, @@ -333,7 +333,7 @@ func TestCollectDeferredMCPCandidates(t *testing.T) { require.Equal(t, "everything", collectDeferredMCPCandidates(paddedInput)[0].server, "surrounding whitespace is trimmed so scope matching and catalog display see the canonical name") - unpadded := chattool.NewWorkspaceMCPTool(workspacesdk.MCPToolInfo{Name: "everything__ping"}, nil, nil) + unpadded := chattool.NewWorkspaceMCPTools([]workspacesdk.MCPToolInfo{{Name: "everything__ping"}}, nil)[0] collidingInput := deferredMCPCandidateInput{ workspaceMCPTools: []fantasy.AgentTool{padded, unpadded}, includeWorkspaceTools: true, diff --git a/coderd/x/chatd/message_conversion.go b/coderd/x/chatd/message_conversion.go index 7edd0c5a449..4a9eb0f50f6 100644 --- a/coderd/x/chatd/message_conversion.go +++ b/coderd/x/chatd/message_conversion.go @@ -36,8 +36,7 @@ type buildCommitStepMessagesInput struct { } type stepMessagesForCommit struct { - Messages []chatstate.Message - VisibleIndexes []int + Messages []chatstate.Message // ConsumeCompactionRequest clears the manual compaction marker // atomically with the commit. Set on compaction commits. ConsumeCompactionRequest bool @@ -87,8 +86,7 @@ func buildCommitStepMessages(input buildCommitStepMessagesInput) (stepMessagesFo } return stepMessagesForCommit{ - Messages: messages, - VisibleIndexes: visibleMessageIndexes(messages), + Messages: messages, }, nil } @@ -283,16 +281,6 @@ func batchUsageMessage( return msg, true, nil } -func visibleMessageIndexes(messages []chatstate.Message) []int { - indexes := make([]int, 0, len(messages)) - for i, msg := range messages { - if msg.Visibility == database.ChatMessageVisibilityBoth || msg.Visibility == database.ChatMessageVisibilityUser { - indexes = append(indexes, i) - } - } - return indexes -} - func textFromParts(parts []codersdk.ChatMessagePart) string { var builder strings.Builder for _, part := range parts { @@ -313,8 +301,7 @@ type buildCompactionMessagesInput struct { } type compactionMessagesForCommit struct { - Messages []chatstate.Message - HiddenCount int + Messages []chatstate.Message } func buildCompactionMessages(input buildCompactionMessagesInput) (compactionMessagesForCommit, error) { @@ -391,7 +378,7 @@ func buildCompactionMessages(input buildCompactionMessagesInput) (compactionMess ContentVersion: row.ContentVersion, }) } - return compactionMessagesForCommit{Messages: messages, HiddenCount: 1}, nil + return compactionMessagesForCommit{Messages: messages}, nil } type buildClearMessagesInput struct { diff --git a/coderd/x/chatd/message_conversion_internal_test.go b/coderd/x/chatd/message_conversion_internal_test.go index 878e175c86f..817e5512f65 100644 --- a/coderd/x/chatd/message_conversion_internal_test.go +++ b/coderd/x/chatd/message_conversion_internal_test.go @@ -191,13 +191,8 @@ func TestBuildAssistantParts_PartialReasoningTimestamps(t *testing.T) { startedAt := time.Date(2026, time.April, 10, 12, 0, 0, 0, time.UTC) - // Tests the persistence helper when the parallel CompletedAt - // slot is zero-valued, ensuring it leaves CompletedAt nil rather - // than setting it to the Go zero time. No production code path - // currently emits a zero CompletedAt alongside a non-zero - // StartedAt (flushActiveState always stamps both with - // dbtime.Now()), so this is a defensive boundary test for the - // `variants:"reasoning?"` contract. + // Missing completion timestamps must remain nil rather than being + // serialized as the Go zero time. parts := buildAssistantParts( testutil.Logger(t), []fantasy.Content{ diff --git a/coderd/x/chatd/message_conversion_test.go b/coderd/x/chatd/message_conversion_test.go index 4da99906caf..a3db10959cd 100644 --- a/coderd/x/chatd/message_conversion_test.go +++ b/coderd/x/chatd/message_conversion_test.go @@ -43,7 +43,6 @@ func TestBuildCommitStepMessages_AssistantTextAndReasoning(t *testing.T) { }) require.NoError(t, err) require.Len(t, got.Messages, 1) - require.Equal(t, []int{0}, got.VisibleIndexes) msg := got.Messages[0] require.Equal(t, database.ChatMessageRoleAssistant, msg.Role) @@ -82,7 +81,6 @@ func TestBuildCommitStepMessages_LocalToolResultsBecomeToolMessages(t *testing.T }) require.NoError(t, err) require.Len(t, got.Messages, 2) - require.Equal(t, []int{0, 1}, got.VisibleIndexes) require.Equal(t, sql.NullInt64{Int64: 1500, Valid: true}, got.Messages[0].RuntimeMs) require.False(t, got.Messages[1].RuntimeMs.Valid) @@ -132,6 +130,7 @@ func TestBuildCommitStepMessages_BatchRuntimeBillsDedicatedUsageRow(t *testing.T stamp := got.Messages[2] require.Equal(t, database.ChatMessageRoleTool, stamp.Role) + // The usage record is model-only bookkeeping, never published to clients. require.Equal(t, database.ChatMessageVisibilityModel, stamp.Visibility) require.Equal(t, sql.NullInt64{Int64: 10000, Valid: true}, stamp.RuntimeMs) stampParts, err := chatprompt.ParseContent(database.ChatMessage{ @@ -143,9 +142,6 @@ func TestBuildCommitStepMessages_BatchRuntimeBillsDedicatedUsageRow(t *testing.T require.Len(t, stampParts, 1) require.Equal(t, toolBatchUsagePartType, stampParts[0].Type) require.JSONEq(t, `{"billed_ms":10000,"billed_calls":2}`, string(stampParts[0].Result)) - // The usage record is model-only bookkeeping, never published to - // clients. - require.Equal(t, []int{0, 1}, got.VisibleIndexes) } func TestBuildCommitStepMessages_BatchAttachmentAssistantRowStaysNull(t *testing.T) { @@ -314,7 +310,6 @@ func TestBuildCompactionMessages_CompressedSummaryToolCallAndResult(t *testing.T }, }) require.NoError(t, err) - require.Equal(t, 1, got.HiddenCount) require.Len(t, got.Messages, 3) require.Equal(t, database.ChatMessageRoleUser, got.Messages[0].Role) diff --git a/coderd/x/chatd/stream_loop.go b/coderd/x/chatd/stream_loop.go index 5004e8a490e..ff647907bb8 100644 --- a/coderd/x/chatd/stream_loop.go +++ b/coderd/x/chatd/stream_loop.go @@ -57,13 +57,11 @@ type streamSyncHint struct { type streamDBSnapshot struct { chat database.Chat - historyChanged bool changedMessages []database.ChatMessage historyReset bool fullHistory []database.ChatMessage - queueChanged bool - queue []database.ChatQueuedMessage + queue []database.ChatQueuedMessage actionRequired *codersdk.ChatStreamActionRequired } @@ -149,7 +147,6 @@ func (l *streamLoop) loadDBSnapshot(ctx context.Context) (streamDBSnapshot, erro snapshot.chat = chat if chat.HistoryVersion > l.state.historyVersion { - snapshot.historyChanged = true snapshot.changedMessages, err = tx.GetChatMessagesByRevisionForStream(ctx, database.GetChatMessagesByRevisionForStreamParams{ ChatID: l.chatID, AfterRevision: l.state.historyVersion, @@ -175,7 +172,6 @@ func (l *streamLoop) loadDBSnapshot(ctx context.Context) (streamDBSnapshot, erro } if chat.QueueVersion > l.state.queueVersion { - snapshot.queueChanged = true snapshot.queue, err = tx.GetChatQueuedMessages(ctx, l.chatID) if err != nil { return xerrors.Errorf("get chat queue: %w", err) diff --git a/coderd/x/chatd/tasks.go b/coderd/x/chatd/tasks.go index eefa42af3d1..43e0ff9d632 100644 --- a/coderd/x/chatd/tasks.go +++ b/coderd/x/chatd/tasks.go @@ -175,9 +175,8 @@ func executeTaskSafely(ctx context.Context, fn func(context.Context) error) (err } type interruptionOutcome struct { - Chat database.Chat - Kind runnerActionKind - WatchEventKind codersdk.ChatWatchEventKind + Chat database.Chat + Kind runnerActionKind } type taskStarter struct { @@ -335,9 +334,8 @@ func (s *taskStarter) StartInterrupt(ctx context.Context, input chatWorkerTaskSt return xerrors.Errorf("publish watch and route: %w", err) } return s.runAfterInterruptionOutcome(ctx, interruptionOutcome{ - Chat: committed, - Kind: runnerActionKindFinishInterruption, - WatchEventKind: codersdk.ChatWatchEventKindStatusChange, + Chat: committed, + Kind: runnerActionKindFinishInterruption, }) } diff --git a/docs/admin/integrations/prometheus.md b/docs/admin/integrations/prometheus.md index 03e1872aa2f..1513958ccf9 100644 --- a/docs/admin/integrations/prometheus.md +++ b/docs/admin/integrations/prometheus.md @@ -250,7 +250,6 @@ The `coder_ai_gateway_cost_control_*` metrics are exported only by `coderd`. | `coderd_chatd_message_count` | histogram | Number of messages in the prompt per LLM request. | `model` `provider` | | `coderd_chatd_prompt_size_bytes` | histogram | Estimated byte size of the prompt per LLM request. | `model` `provider` | | `coderd_chatd_steps_total` | counter | Total agentic loop steps across all chats. | `model` `provider` | -| `coderd_chatd_stream_buffer_dropped_total` | counter | Number of chat stream buffer events dropped due to the per-chat buffer cap. | | | `coderd_chatd_stream_retries_total` | counter | Total LLM stream retries. | `kind` `model` `provider` | | `coderd_chatd_tool_errors_total` | counter | Total tool calls that returned an error result. | `model` `provider` `tool_name` | | `coderd_chatd_tool_result_size_bytes` | histogram | Size in bytes of each tool execution result. | `model` `provider` `tool_name` | diff --git a/scripts/metricsdocgen/generated_metrics b/scripts/metricsdocgen/generated_metrics index 2b1e7ee9dcc..ee0ec28fdcd 100644 --- a/scripts/metricsdocgen/generated_metrics +++ b/scripts/metricsdocgen/generated_metrics @@ -322,9 +322,6 @@ coderd_chatd_prompt_size_bytes{provider="",model=""} 0 # HELP coderd_chatd_steps_total Total agentic loop steps across all chats. # TYPE coderd_chatd_steps_total counter coderd_chatd_steps_total{provider="",model=""} 0 -# HELP coderd_chatd_stream_buffer_dropped_total Number of chat stream buffer events dropped due to the per-chat buffer cap. -# TYPE coderd_chatd_stream_buffer_dropped_total counter -coderd_chatd_stream_buffer_dropped_total 0 # HELP coderd_chatd_stream_retries_total Total LLM stream retries. # TYPE coderd_chatd_stream_retries_total counter coderd_chatd_stream_retries_total{provider="",model="",kind=""} 0