Production AI Interface
Thiết kế streaming UI, state machine, cancellation và trust signals cho giao diện AI.
AI response là một tiến trình có thể phát token, gọi tool, chờ approval, lỗi giữa chừng hoặc bị người dùng hủy — không phải một payload xuất hiện tức thì.
Những điều cần nắm chắc
Dùng state machine thay cho một biến isLoading.
Batch token updates để tránh render quá dày.
AbortController cho phép dừng stream mà không reload trang.
Render structured blocks theo allowlist thay vì HTML tự do từ model.
Nội dung bài viết
UI phải biểu diễn trạng thái thật của agent
Một run thực tế có thể đi qua submitted, streaming, awaiting-tool, awaiting-approval, completed, cancelled và failed. Mỗi trạng thái cần copy, control và recovery khác nhau.
Trust không đến từ animation đẹp. Người dùng cần biết nội dung còn đang sinh, tool nào vừa chạy, nguồn nào hỗ trợ kết luận và phần nào chưa được xác minh.
Code & cấu trúc tham khảo
State contract cho AI message
1type AssistantRun =2 | { status: 'submitted' }3 | { status: 'streaming'; text: string }4 | { status: 'awaiting-tool'; toolName: string }5 | { status: 'completed'; text: string; sources: Source[] }6 | { status: 'cancelled'; partialText: string }7 | { status: 'failed'; message: string; retryable: boolean };Takeaway: Discriminated union buộc UI xử lý đầy đủ từng trạng thái thay vì ghép nhiều boolean có thể mâu thuẫn.
Tài liệu đọc thêm
Repo, đặc tả và bài viết gốc để đi sâu sau bài học.
Streaming API responses
Sự kiện streaming và cách xử lý response tăng dần.
Structured model outputs
Biến output model thành UI contract có thể validate.
Vercel AI SDK
TypeScript toolkit cho streaming messages, tools và generative UI.
assistant-ui
Composable React primitives cho thread, tool state, edit, retry và streaming UX.
MDN AbortController
Browser primitive để cancel stream, fetch và async operation.
WAI-ARIA live regions
Accessible announcement cho nội dung cập nhật bất đồng bộ.