Files
coder/coderd/x/chatd/chattool/chattool.go
T
Ben Potter 82e602e092 fix(coderd): surface external auth login link when creating a workspace (#28992)
When a template requires a non-optional external auth provider that the
workspace owner hasn't linked yet, `create_workspace` rejects the
request with a 403, but the error never included a way to actually
resolve it. The web UI and CLI don't hit this path in practice, since
they preflight-check `/templateversions/{id}/external-auth` and render a
login button before ever submitting. Coder Agents' `create_workspace`
chat tool has no such preflight, so it's the one place a real user hits
this error, and the assistant could only repeat "external authentication
is required" with no way forward.

`requireWorkspaceOwnerExternalAuth` now includes each missing provider's
authenticate URL in the error `Detail`, and the chatd `create_workspace`
tool's `responseErrorResult` adds an `action_required` hint so the model
reliably tells the user to open the link and retry, instead of just
echoing the raw error.

Fixes
[CODAGT-1011](https://linear.app/codercom/issue/CODAGT-1011/external-authentication-is-required-is-a-dead-end-in-coder-agents)


![Demo](https://raw.githubusercontent.com/coder/coder/recordings/recordings/chatd-external-auth-link/recording.gif)

<details>
<summary>Full recording and thumbnail</summary>

-
[mp4](https://raw.githubusercontent.com/coder/coder/recordings/recordings/chatd-external-auth-link/recording.mp4)
-
[Thumbnail](https://raw.githubusercontent.com/coder/coder/recordings/recordings/chatd-external-auth-link/thumbnail.jpg)
</details>

<details>
<summary>Implementation notes</summary>

- Only the free-text `Detail` string changed. The `Validations` shape
(`Field: "external_auth"`, `Detail: provider.ID`) is untouched, since
it's a separate, tested, machine-readable contract that other code may
rely on.
- Recorded against a local dev instance with a dummy GitHub OAuth
client, so the clip ends right after the assistant surfaces the link.
Following the link past Coder's own external-auth page would fail
regardless of this fix, since there's no real OAuth client secret
configured in that environment.
- Generated by Coder Agents on behalf of @bpmct.
</details>
2026-09-17 19:04:55 -05:00

200 lines
6.0 KiB
Go

package chattool
import (
"context"
"encoding/json"
"unicode/utf8"
"charm.land/fantasy"
"github.com/google/uuid"
"golang.org/x/xerrors"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/codersdk"
)
const templateNotAvailableMessage = "template not available for chat workspaces; use list_templates to find allowed templates"
// WorkspaceUnavailableHint follows errors that keep a tool from loading the
// chat's workspace so the model recovers instead of concluding it is blocked.
const WorkspaceUnavailableHint = "The workspace is probably gone; use the create_workspace tool to make a new one"
func workspaceLoadErrorResponse(err error) fantasy.ToolResponse {
return fantasy.NewTextErrorResponse(
xerrors.Errorf("load workspace: %w. %s", err, WorkspaceUnavailableHint).Error(),
)
}
// externalAuthRequiredMessage tells the model how to unblock a request that
// failed because the workspace owner has not authenticated with a required
// external auth provider. The login links are in the response detail.
const externalAuthRequiredMessage = "the workspace owner must authenticate with the listed external auth providers before this template can be used. " +
"Show the user the authentication link(s) from detail so they can open them, then retry create_workspace once they confirm they have authenticated"
// hasExternalAuthValidation reports whether any validation error identifies a
// missing external auth provider.
func hasExternalAuthValidation(validations []codersdk.ValidationError) bool {
for _, validation := range validations {
if validation.Field == "external_auth" {
return true
}
}
return false
}
func marshalToolResponse(result any) fantasy.ToolResponse {
data, err := json.Marshal(result)
if err != nil {
return fantasy.NewTextResponse("{}")
}
return fantasy.NewTextResponse(string(data))
}
// toolResponse builds a fantasy.ToolResponse from a JSON-serializable
// result map. The map constraint ensures all tool results serialize
// to JSON objects so the frontend can safely parse them.
func toolResponse(result map[string]any) fantasy.ToolResponse {
return marshalToolResponse(result)
}
// buildToolResponse marshals a buildErrorResult into a tool response.
// Separate from toolResponse to keep the map[string]any constraint
// on the general helper while allowing typed error structs.
func buildToolResponse(r buildErrorResult) fantasy.ToolResponse {
return marshalToolResponse(r)
}
// responseErrorResult converts a codersdk.Response into a structured
// tool result. We return these via toolResponse rather than
// NewTextErrorResponse because the fantasy/chatprompt pipeline flattens
// IsError content into a single string and drops validation details.
func responseErrorResult(resp codersdk.Response) map[string]any {
message := resp.Message
if message == "" {
message = "request failed"
}
result := map[string]any{
"error": message,
}
if resp.Detail != "" {
result["detail"] = resp.Detail
}
if len(resp.Validations) > 0 {
result["validations"] = resp.Validations
}
if hasExternalAuthValidation(resp.Validations) {
result["action_required"] = externalAuthRequiredMessage
}
return result
}
func latestWorkspaceBuildAndJob(
ctx context.Context,
db database.Store,
workspaceID uuid.UUID,
) (database.WorkspaceBuild, database.ProvisionerJob, error) {
build, err := db.GetLatestWorkspaceBuildByWorkspaceID(ctx, workspaceID)
if err != nil {
return database.WorkspaceBuild{}, database.ProvisionerJob{}, xerrors.Errorf("get latest build: %w", err)
}
job, err := db.GetProvisionerJobByID(ctx, build.JobID)
if err != nil {
return database.WorkspaceBuild{}, database.ProvisionerJob{}, xerrors.Errorf("get provisioner job: %w", err)
}
return build, job, nil
}
func publishBuildBinding(
ctx context.Context,
db database.Store,
logger slog.Logger,
chatID uuid.UUID,
workspaceID uuid.UUID,
buildID uuid.UUID,
onChatUpdated func(database.Chat),
) {
updatedChat, bindErr := db.UpdateChatWorkspaceBinding(ctx, database.UpdateChatWorkspaceBindingParams{
ID: chatID,
WorkspaceID: uuid.NullUUID{UUID: workspaceID, Valid: true},
BuildID: uuid.NullUUID{
UUID: buildID,
Valid: buildID != uuid.Nil,
},
AgentID: uuid.NullUUID{},
})
if bindErr != nil {
logger.Error(ctx, "failed to persist build ID on chat binding",
slog.F("chat_id", chatID),
slog.F("build_id", buildID),
slog.Error(bindErr),
)
return
}
if onChatUpdated != nil {
onChatUpdated(updatedChat)
}
}
func provisionerJobTerminal(status database.ProvisionerJobStatus) bool {
switch status {
case database.ProvisionerJobStatusSucceeded,
database.ProvisionerJobStatusFailed,
database.ProvisionerJobStatusCanceled:
return true
default:
return false
}
}
func truncateRunes(value string, maxLen int) string {
if maxLen <= 0 || value == "" {
return ""
}
if utf8.RuneCountInString(value) <= maxLen {
return value
}
runes := []rune(value)
if maxLen > len(runes) {
maxLen = len(runes)
}
return string(runes[:maxLen])
}
// buildErrorResult is a structured error response that preserves
// the build ID alongside the error message. This lets the frontend
// keep showing build logs when a build fails instead of losing
// them on the error transition.
type buildErrorResult struct {
Error string `json:"error"`
BuildID string `json:"build_id,omitempty"`
}
func newBuildError(msg string, buildID uuid.UUID) buildErrorResult {
r := buildErrorResult{Error: msg}
if buildID != uuid.Nil {
r.BuildID = buildID.String()
}
return r
}
// setBuildID adds the build_id field to a tool response map when
// the build ID is known (non-zero).
func setBuildID(result map[string]any, buildID uuid.UUID) {
if buildID != uuid.Nil {
result["build_id"] = buildID.String()
}
}
// setNoBuild marks the response with no_build: true when no build
// was triggered. The frontend uses this flag to suppress the
// build-log section for already-running workspaces.
func setNoBuild(result map[string]any, buildID uuid.UUID) {
if buildID == uuid.Nil {
result["no_build"] = true
}
}