-
Notifications
You must be signed in to change notification settings - Fork 9
feat(api): split chat-workflow resume into GET /api/chat/[chatId]/stream #596
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
arpitgupta1214
wants to merge
4
commits into
test
Choose a base branch
from
feat/api-chat-workflow-stream-resume
base: test
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
baf01fa
feat(api): split chat-workflow resume into GET /api/chat/[chatId]/stream
arpitgupta1214 1eea16d
fix(chat): address review — retryable 503 on indeterminate stream, UU…
arpitgupta1214 7130bd4
Merge remote-tracking branch 'origin/test' into feat/api-chat-workflo…
arpitgupta1214 ac7cfba
Merge remote-tracking branch 'origin/test' into feat/api-chat-workflo…
arpitgupta1214 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import type { NextRequest } from "next/server"; | ||
| import { NextResponse } from "next/server"; | ||
| import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; | ||
| import { handleChatStreamResume } from "@/lib/chat/handleChatStreamResume"; | ||
|
|
||
| export const maxDuration = 800; | ||
|
|
||
| /** | ||
| * OPTIONS handler for CORS preflight requests. | ||
| * | ||
| * @returns A NextResponse with CORS headers. | ||
| */ | ||
| export async function OPTIONS() { | ||
| return new NextResponse(null, { | ||
| status: 200, | ||
| headers: getCorsHeaders(), | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * GET /api/chat/[chatId]/stream | ||
| * | ||
| * Resume/reconnect endpoint for the durable chat-workflow agent loop. Returns | ||
| * the live UIMessage stream when a run is still in flight, or 204 when there | ||
| * is nothing to resume. This is the only resume path — POST /api/chat/workflow | ||
| * never resumes. | ||
| * | ||
| * Authentication: x-api-key or Authorization bearer (caller must own the chat). | ||
| * | ||
| * @param request - The incoming request. | ||
| * @param context - Next.js route context. | ||
| * @param context.params - Async route params containing the chat id. | ||
| * @returns A streaming Response (200), an empty 204, or an error response. | ||
| */ | ||
| export async function GET( | ||
| request: NextRequest, | ||
| context: { params: Promise<{ chatId: string }> }, | ||
| ): Promise<Response> { | ||
| const { chatId } = await context.params; | ||
| return handleChatStreamResume(request, chatId); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
|
|
||
| import { handleChatStreamResume } from "@/lib/chat/handleChatStreamResume"; | ||
| import { validateGetChatStreamRequest } from "@/lib/chat/validateGetChatStreamRequest"; | ||
| import { reconcileExistingActiveStream } from "@/lib/chat/reconcileExistingActiveStream"; | ||
|
|
||
| vi.mock("@/lib/chat/validateGetChatStreamRequest", () => ({ | ||
| validateGetChatStreamRequest: vi.fn(), | ||
| })); | ||
| vi.mock("@/lib/chat/reconcileExistingActiveStream", () => ({ | ||
| reconcileExistingActiveStream: vi.fn(), | ||
| })); | ||
| vi.mock("@/lib/networking/getCorsHeaders", () => ({ | ||
| getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), | ||
| })); | ||
|
|
||
| const ACCOUNT_ID = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"; | ||
| const CHAT_ID = "11111111-1111-1111-1111-111111111111"; | ||
|
|
||
| function makeRequest(): NextRequest { | ||
| return new NextRequest(`http://localhost/api/chat/${CHAT_ID}/stream`, { | ||
| method: "GET", | ||
| headers: { "x-api-key": "test-key" }, | ||
| }); | ||
| } | ||
|
|
||
| function mockValidatedChat(activeStreamId: string | null) { | ||
| vi.mocked(validateGetChatStreamRequest).mockResolvedValue({ | ||
| chat: { id: CHAT_ID, active_stream_id: activeStreamId } as never, | ||
| accountId: ACCOUNT_ID, | ||
| }); | ||
| } | ||
|
|
||
| beforeEach(() => vi.clearAllMocks()); | ||
|
|
||
| describe("handleChatStreamResume", () => { | ||
| it("passes through the validator's error response", async () => { | ||
| vi.mocked(validateGetChatStreamRequest).mockResolvedValue( | ||
| NextResponse.json({ status: "error", error: "Forbidden" }, { status: 403 }), | ||
| ); | ||
| const res = await handleChatStreamResume(makeRequest(), CHAT_ID); | ||
| expect(res.status).toBe(403); | ||
| expect(reconcileExistingActiveStream).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns 204 when the chat has no active stream id", async () => { | ||
| mockValidatedChat(null); | ||
| const res = await handleChatStreamResume(makeRequest(), CHAT_ID); | ||
| expect(res.status).toBe(204); | ||
| expect(reconcileExistingActiveStream).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns 200 with the live stream and x-workflow-run-id when resumable", async () => { | ||
| mockValidatedChat("wrun_live"); | ||
| vi.mocked(reconcileExistingActiveStream).mockResolvedValue({ | ||
| action: "resume", | ||
| runId: "wrun_live", | ||
| stream: new ReadableStream(), | ||
| }); | ||
| const res = await handleChatStreamResume(makeRequest(), CHAT_ID); | ||
| expect(res.status).toBe(200); | ||
| expect(res.headers.get("content-type") ?? "").toMatch(/text\/event-stream/); | ||
| expect(res.headers.get("x-workflow-run-id")).toBe("wrun_live"); | ||
| }); | ||
|
|
||
| it("returns 204 when the run is terminal (reconcile=ready, stale id cleared)", async () => { | ||
| mockValidatedChat("wrun_done"); | ||
| vi.mocked(reconcileExistingActiveStream).mockResolvedValue({ action: "ready" }); | ||
| const res = await handleChatStreamResume(makeRequest(), CHAT_ID); | ||
| expect(res.status).toBe(204); | ||
| }); | ||
|
|
||
| it("returns 204 when the probe is indeterminate (reconcile=conflict)", async () => { | ||
| mockValidatedChat("wrun_unknown"); | ||
| vi.mocked(reconcileExistingActiveStream).mockResolvedValue({ action: "conflict" }); | ||
| const res = await handleChatStreamResume(makeRequest(), CHAT_ID); | ||
| expect(res.status).toBe(204); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
112 changes: 112 additions & 0 deletions
112
lib/chat/__tests__/validateGetChatStreamRequest.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
|
|
||
| import { validateGetChatStreamRequest } from "@/lib/chat/validateGetChatStreamRequest"; | ||
| import { validateAuthContext } from "@/lib/auth/validateAuthContext"; | ||
| import { selectChats } from "@/lib/supabase/chats/selectChats"; | ||
| import { selectSessions } from "@/lib/supabase/sessions/selectSessions"; | ||
|
|
||
| vi.mock("@/lib/auth/validateAuthContext", () => ({ validateAuthContext: vi.fn() })); | ||
| vi.mock("@/lib/supabase/chats/selectChats", () => ({ selectChats: vi.fn() })); | ||
| vi.mock("@/lib/supabase/sessions/selectSessions", () => ({ selectSessions: vi.fn() })); | ||
| vi.mock("@/lib/networking/getCorsHeaders", () => ({ | ||
| getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), | ||
| })); | ||
|
|
||
| const ACCOUNT_ID = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"; | ||
| const OTHER_ACCOUNT_ID = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"; | ||
| const SESSION_ID = "22222222-2222-4222-8222-222222222222"; | ||
| const CHAT_ID = "11111111-1111-4111-8111-111111111111"; | ||
|
|
||
| function makeRequest(): NextRequest { | ||
| return new NextRequest(`http://localhost/api/chat/${CHAT_ID}/stream`, { | ||
| method: "GET", | ||
| headers: { "x-api-key": "test-key" }, | ||
| }); | ||
| } | ||
|
|
||
| function mockAuthed() { | ||
| vi.mocked(validateAuthContext).mockResolvedValue({ | ||
| accountId: ACCOUNT_ID, | ||
| orgId: null, | ||
| authToken: "test-key", | ||
| }); | ||
| } | ||
|
|
||
| beforeEach(() => vi.clearAllMocks()); | ||
|
|
||
| describe("validateGetChatStreamRequest", () => { | ||
| it("returns 400 when chatId is empty", async () => { | ||
| const res = await validateGetChatStreamRequest(makeRequest(), ""); | ||
| expect(res).toBeInstanceOf(NextResponse); | ||
| expect((res as NextResponse).status).toBe(400); | ||
| }); | ||
|
|
||
| it("returns 400 when chatId is not a valid UUID", async () => { | ||
| const res = await validateGetChatStreamRequest(makeRequest(), "not-a-uuid"); | ||
| expect((res as NextResponse).status).toBe(400); | ||
| }); | ||
|
|
||
| it("passes through the auth error response", async () => { | ||
| vi.mocked(validateAuthContext).mockResolvedValue( | ||
| NextResponse.json({ status: "error", error: "Unauthorized" }, { status: 401 }), | ||
| ); | ||
| const res = await validateGetChatStreamRequest(makeRequest(), CHAT_ID); | ||
| expect((res as NextResponse).status).toBe(401); | ||
| }); | ||
|
|
||
| it("returns 404 when the chat does not exist", async () => { | ||
| mockAuthed(); | ||
| vi.mocked(selectChats).mockResolvedValue([]); | ||
| const res = await validateGetChatStreamRequest(makeRequest(), CHAT_ID); | ||
| expect((res as NextResponse).status).toBe(404); | ||
| }); | ||
|
|
||
| it("returns 500 when the chat lookup errors (selectChats null)", async () => { | ||
| mockAuthed(); | ||
| vi.mocked(selectChats).mockResolvedValue(null); | ||
| const res = await validateGetChatStreamRequest(makeRequest(), CHAT_ID); | ||
| expect((res as NextResponse).status).toBe(500); | ||
| }); | ||
|
|
||
| it("returns 500 when the session lookup errors", async () => { | ||
| mockAuthed(); | ||
| vi.mocked(selectChats).mockResolvedValue([{ id: CHAT_ID, session_id: SESSION_ID } as never]); | ||
| vi.mocked(selectSessions).mockResolvedValue(null); | ||
| const res = await validateGetChatStreamRequest(makeRequest(), CHAT_ID); | ||
| expect((res as NextResponse).status).toBe(500); | ||
| }); | ||
|
|
||
| it("returns 404 when the session does not exist", async () => { | ||
| mockAuthed(); | ||
| vi.mocked(selectChats).mockResolvedValue([{ id: CHAT_ID, session_id: SESSION_ID } as never]); | ||
| vi.mocked(selectSessions).mockResolvedValue([]); | ||
| const res = await validateGetChatStreamRequest(makeRequest(), CHAT_ID); | ||
| expect((res as NextResponse).status).toBe(404); | ||
| }); | ||
|
|
||
| it("returns 403 when the caller does not own the session", async () => { | ||
| mockAuthed(); | ||
| vi.mocked(selectChats).mockResolvedValue([{ id: CHAT_ID, session_id: SESSION_ID } as never]); | ||
| vi.mocked(selectSessions).mockResolvedValue([ | ||
| { id: SESSION_ID, account_id: OTHER_ACCOUNT_ID } as never, | ||
| ]); | ||
| const res = await validateGetChatStreamRequest(makeRequest(), CHAT_ID); | ||
| expect((res as NextResponse).status).toBe(403); | ||
| }); | ||
|
|
||
| it("returns the chat row when the caller owns it", async () => { | ||
| mockAuthed(); | ||
| vi.mocked(selectChats).mockResolvedValue([ | ||
| { id: CHAT_ID, session_id: SESSION_ID, active_stream_id: "wrun_x" } as never, | ||
| ]); | ||
| vi.mocked(selectSessions).mockResolvedValue([ | ||
| { id: SESSION_ID, account_id: ACCOUNT_ID } as never, | ||
| ]); | ||
| const res = await validateGetChatStreamRequest(makeRequest(), CHAT_ID); | ||
| expect(res).not.toBeInstanceOf(NextResponse); | ||
| if (res instanceof NextResponse) return; | ||
| expect(res.chat.id).toBe(CHAT_ID); | ||
| expect(res.accountId).toBe(ACCOUNT_ID); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P3: Custom agent: Enforce Clear Code Style and Maintainability Practices
New test file reaches the repository's maximum size threshold instead of staying under 100 lines.
Prompt for AI agents