Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions coderd/apidoc/docs.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions coderd/apidoc/swagger.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion coderd/exp_chats.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,10 @@ func writeChatHookErr(ctx context.Context, rw http.ResponseWriter, err error, de
if message == "" {
message = deniedFallback
}
httpapi.Write(ctx, rw, http.StatusForbidden, codersdk.Response{Message: message})
httpapi.Write(ctx, rw, http.StatusForbidden, codersdk.ChatHookDeniedResponse{
Response: codersdk.Response{Message: message},
Kind: codersdk.ChatErrorKindHookDenied,
})
return true
}
if hookErr, ok := errors.AsType[*dispatch.Error](err); ok {
Expand Down
12 changes: 8 additions & 4 deletions coderd/exp_chats_hooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,22 @@ func TestPostChatsInitialPromptHookErrors(t *testing.T) {
model := createAdditionalChatModelConfig(t, client, "openai", "gpt-4.1")
ctx := testutil.Context(t, testutil.WaitLong)

_, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
res, err := client.Request(ctx, http.MethodPost, "/api/experimental/chats", codersdk.CreateChatRequest{
OrganizationID: user.OrganizationID,
ModelConfigID: &model.ID,
Content: []codersdk.ChatInputPart{{
Type: codersdk.ChatInputPartTypeText,
Text: "blocked prompt",
}},
})
sdkErr := coderdtest.SDKError(t, err)
require.Equal(t, test.wantStatus, sdkErr.StatusCode())
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, test.wantStatus, res.StatusCode)
var response codersdk.ChatHookDeniedResponse
require.NoError(t, json.NewDecoder(res.Body).Decode(&response))
if test.wantMessage != "" {
require.Equal(t, test.wantMessage, sdkErr.Message)
require.Equal(t, test.wantMessage, response.Message)
require.Equal(t, codersdk.ChatErrorKindHookDenied, response.Kind)
}
request := testutil.RequireReceive(ctx, t, requests)
require.Equal(t, agenthooks.EventUserPromptSubmit, request.Type)
Expand Down
10 changes: 10 additions & 0 deletions codersdk/chats.go
Original file line number Diff line number Diff line change
Expand Up @@ -1740,6 +1740,7 @@ const (
ChatErrorKindProviderDisabled ChatErrorKind = "provider_disabled"
ChatErrorKindContentFilter ChatErrorKind = "content_filter"
ChatErrorKindHookDispatchFailed ChatErrorKind = "hook_dispatch_failed"
ChatErrorKindHookDenied ChatErrorKind = "hook_denied"
)

// AllChatErrorKinds contains every ChatErrorKind value.
Expand All @@ -1757,6 +1758,7 @@ var AllChatErrorKinds = []ChatErrorKind{
ChatErrorKindProviderDisabled,
ChatErrorKindContentFilter,
ChatErrorKindHookDispatchFailed,
ChatErrorKindHookDenied,
}

// ChatError represents a terminal chat error in persisted chat state or the
Expand Down Expand Up @@ -2025,6 +2027,14 @@ type ChatHookDispatchFailedResponse struct {
Kind ChatErrorKind `json:"kind"`
}

// ChatHookDeniedResponse is the error body returned when a lifecycle hook
// denies a synchronous chat operation. Kind lets clients classify the denial
// without parsing message text.
type ChatHookDeniedResponse struct {
Response
Kind ChatErrorKind `json:"kind"`
}

type chatUsageLimitExceededError struct {
err *Error
response ChatUsageLimitExceededResponse
Expand Down
12 changes: 6 additions & 6 deletions docs/reference/api/chats.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions docs/reference/api/schemas.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions site/src/api/typesGenerated.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 7 additions & 3 deletions site/src/pages/AgentsPage/AgentChatPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ import {
import {
type ChatDetailError,
formatUsageLimitMessage,
isChatHookDeniedResponse,
isChatHookDispatchFailedResponse,
isChatUsageLimitExceededResponse,
} from "./utils/usageLimitMessage";
Expand Down Expand Up @@ -1368,10 +1369,13 @@ const AgentChatPage: FC = () => {
setChatErrorReason(agentId, reason);
} else if (isApiError(error)) {
const detail = error.response?.data?.detail?.trim() || undefined;
const reason: ChatDetailError = {
kind: isChatHookDispatchFailedResponse(error.response?.data)
const kind = isChatHookDeniedResponse(error.response?.data)
? "hook_denied"
Comment on lines +1372 to +1373

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add interaction coverage for existing-chat hook denials

When a lifecycle hook rejects a send or edit in an existing chat, this new branch changes the rendered title to Blocked by policy, but the added stories cover only AgentCreateForm; the existing AgentChatPage story exercises hook_dispatch_failed and has no hook_denied scenario. Add an AgentChatPage.stories.tsx play story that submits a message, returns the structured 403 response, and asserts the policy title and message so this behavior is covered as required by FE1.

AGENTS.md reference: site/AGENTS.md:L9-L10

Useful? React with 👍 / 👎.

: isChatHookDispatchFailedResponse(error.response?.data)
? "hook_dispatch_failed"
: "generic",
: "generic";
const reason: ChatDetailError = {
kind,
message: getErrorMessage(error, "An unexpected error occurred."),
...(detail ? { detail } : {}),
};
Expand Down
78 changes: 78 additions & 0 deletions site/src/pages/AgentsPage/components/AgentCreateForm.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -816,6 +816,84 @@ export const UsageLimitExceeded: Story = {
},
};

export const HookDispatchFailed: Story = {
args: {
...defaultArgs,
createError: Object.assign(
new Error("Request failed with status code 502"),
{
isAxiosError: true,
response: {
status: 502,
statusText: "Bad Gateway",
data: {
kind: "hook_dispatch_failed",
message: "Chat lifecycle hook dispatch failed.",
detail:
"Lifecycle hook dispatch 00000000-0000-0000-0000-000000000001 failed (http_error).",
},
headers: {},
config: {},
},
config: {},
toJSON: () => ({}),
},
),
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getByText("Lifecycle hook failed")).toBeVisible();
await expect(
canvas.getByText("Chat lifecycle hook dispatch failed."),
).toBeVisible();
await expect(
canvas.getByText(
"Lifecycle hook dispatch 00000000-0000-0000-0000-000000000001 failed (http_error).",
),
).toBeVisible();
await expect(canvas.queryByText("Stack Trace")).not.toBeInTheDocument();
await expect(canvas.queryByText("Response data")).not.toBeInTheDocument();
},
};

export const HookDenied: Story = {
args: {
...defaultArgs,
createError: Object.assign(
new Error("Request failed with status code 403"),
{
isAxiosError: true,
response: {
status: 403,
statusText: "Forbidden",
data: {
kind: "hook_denied",
message: "This prompt is blocked by policy.",
},
headers: {},
config: {},
},
config: {},
toJSON: () => ({}),
},
),
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(
canvas.getByText("This prompt is blocked by policy."),
).toBeVisible();
await expect(
canvas.queryByText("Blocked by policy"),
).not.toBeInTheDocument();
await expect(
canvas.queryByText("Go to workspaces"),
).not.toBeInTheDocument();
await expect(canvas.queryByText("Stack Trace")).not.toBeInTheDocument();
await expect(canvas.queryByText("Response data")).not.toBeInTheDocument();
},
};

export const ForbiddenErrorWithRole: Story = {
args: {
...defaultArgs,
Expand Down
29 changes: 28 additions & 1 deletion site/src/pages/AgentsPage/components/AgentCreateForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { isApiError } from "#/api/errors";
import { permittedOrganizations } from "#/api/queries/organizations";
import type * as TypesGen from "#/api/typesGenerated";
import type { AgentChatSendShortcut } from "#/api/typesGenerated";
import { Alert, AlertDescription } from "#/components/Alert/Alert";
import { Alert, AlertDescription, AlertTitle } from "#/components/Alert/Alert";
import { ErrorAlert } from "#/components/Alert/ErrorAlert";
import { Button } from "#/components/Button/Button";
import { ConfirmDialog } from "#/components/Dialogs/ConfirmDialog/ConfirmDialog";
Expand All @@ -27,10 +27,13 @@ import {
} from "../utils/reasoningEffort";
import {
formatUsageLimitMessage,
isChatHookDeniedResponse,
isChatHookDispatchFailedResponse,
isChatUsageLimitExceededResponse,
} from "../utils/usageLimitMessage";
import { AgentChatInput } from "./AgentChatInput";
import { ChatAccessDeniedAlert } from "./ChatAccessDeniedAlert";
import { getErrorTitle } from "./ChatConversation/chatStatusHelpers";
import type { ModelSelectorOption } from "./ChatElements";
import { CompactOrgSelector } from "./ChatElements";
import {
Expand Down Expand Up @@ -527,6 +530,30 @@ export const AgentCreateForm: FC<AgentCreateFormProps> = ({
{formatUsageLimitMessage(createError.response.data)}
</AlertDescription>
</Alert>
) : isApiError(createError) &&
createError.response.status === 502 &&
isChatHookDispatchFailedResponse(createError.response.data) ? (
<Alert severity="error">
<AlertTitle>
{getErrorTitle("hook_dispatch_failed", "error")}
</AlertTitle>
<AlertDescription>
<span>{createError.response.data.message}</span>
{createError.response.data.detail && (
<span className="mt-1 block text-content-secondary">
{createError.response.data.detail}
</span>
)}
</AlertDescription>
</Alert>
) : isApiError(createError) &&
createError.response.status === 403 &&
isChatHookDeniedResponse(createError.response.data) ? (
<Alert severity="info">
<AlertDescription>
{createError.response.data.message}
</AlertDescription>
</Alert>
) : (
<ErrorAlert error={createError} />
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ export const getErrorTitle = (
return "Response blocked";
case "hook_dispatch_failed":
return "Lifecycle hook failed";
case "hook_denied":
return "Blocked by policy";
default:
return mode === "retry" ? "Retrying request" : "Request failed";
}
Expand Down
14 changes: 14 additions & 0 deletions site/src/pages/AgentsPage/utils/usageLimitMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,20 @@ export function isChatHookDispatchFailedResponse(
);
}

/**
* Runtime guard for the structured 403 hook-denial response.
*/
export function isChatHookDeniedResponse(
value: unknown,
): value is TypesGen.ChatHookDeniedResponse {
return (
typeof value === "object" &&
value !== null &&
"kind" in value &&
value.kind === "hook_denied"
);
}

/**
* Build a user-friendly usage-limit message from structured 409
* response data. Falls back to a generic message if structured
Expand Down
Loading