From 34ac9768925411cc0e51668de6a4913082379765 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:54:12 +0000 Subject: [PATCH 1/2] fix(ui): let an analysis arrive smoothly - The fresh-answer reveal now covers an AADI analysis's sections (.analysis-document > *), not only a template's lines; 60 ms apart, capped at the eighth block, fixed nth-child delays instead of sibling-index(). - The answer's arrival (wait card out, answer and document pane in) runs in one named view transition: chat column, composer and header tools glide to their new width instead of snapping. CLS is unchanged because the layout change is intended; what changes is how it is drawn. - A fresh answer is scrolled to its top, so on a phone its first lines are no longer cut off; opened encounters and new questions still go to the bottom. - Soft pulse for the wait dot; removed keyframes and comments left from the old typing reveal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ta9C8RaPJ5eAJ3QcD1cHP --- src/app/globals.css | 40 +++++++++++---- src/components/smooth.ts | 8 ++- src/components/workspace-views.tsx | 19 +++++-- src/components/workspace.tsx | 19 +++++-- tests/ui/answer-arrival.test.tsx | 81 ++++++++++++++++++++++++++++++ 5 files changed, 144 insertions(+), 23 deletions(-) create mode 100644 tests/ui/answer-arrival.test.tsx diff --git a/src/app/globals.css b/src/app/globals.css index e78d3f3..085af01 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -299,15 +299,11 @@ label.button:has(input:focus-visible) { outline: 2px solid var(--workspace-focus .guideline-citation-tag { font-size: var(--text-xs); font-weight: var(--weight-medium); color: var(--workspace-accent-ink); } .guideline-citation-text { margin: 0; font-size: var(--text-base); line-height: 1.54; color: var(--color-text-secondary); } .cite-link { color: var(--workspace-accent-ink); text-decoration: none; } -/* A new section unfolds like a submenu (the branch line draws down), then types. */ +/* A new section's branch line, beside the section body. */ .diagnosis-section-body { position: relative; padding-left: 16px; } .diagnosis-section-body::before { content: ""; position: absolute; left: 3px; top: 2px; bottom: 2px; border-left: 1px solid var(--color-border-subtle); transform-origin: top; transition: border-color 320ms ease-out; } -/* A typing answer streams in word by word like a chat reply (Gaffer, 2026-10-20: "seperti claude.ai"): no fade or - rise on its lines, which arrived every few tens of milliseconds and read as a jitter. */ @keyframes text-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } } @keyframes section-heading-in { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: translateY(0); } } -@keyframes section-unfold { to { grid-template-rows: 1fr; } } -@keyframes typing-caret { 50% { opacity: 0; } } /* While the analysis runs, its steps fold in one after another. */ .thinking-steps { list-style: none; margin: 0 0 10px; padding: 0 0 0 14px; position: relative; } .thinking-steps li { position: relative; display: flex; align-items: center; gap: 8px; height: 28px; font-size: var(--text-base); color: var(--color-text-secondary); animation: section-heading-in 280ms cubic-bezier(.23, 1, .32, 1); } @@ -317,7 +313,8 @@ label.button:has(input:focus-visible) { outline: 2px solid var(--workspace-focus .thinking-steps li[data-done="true"] svg { color: var(--workspace-accent-ink); } .thinking-steps li[data-done="false"] > span:last-child { font-weight: var(--weight-semibold); background: linear-gradient(90deg, var(--color-text-secondary) 0%, var(--color-text-primary) 45%, var(--color-text-secondary) 90%) 0 0 / 200% 100%; -webkit-background-clip: text; background-clip: text; color: transparent; animation: thinking-shimmer 1.6s linear infinite; } .thinking-dot { width: 12px; height: 12px; display: inline-flex; align-items: center; justify-content: center; } -.thinking-dot::after { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--color-action-primary); animation: typing-caret 900ms steps(1) infinite; } +.thinking-dot::after { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--color-action-primary); animation: thinking-pulse 1.2s ease-in-out infinite; } +@keyframes thinking-pulse { 50% { opacity: .35; transform: scale(.7); } } @keyframes thinking-shimmer { to { background-position: -200% 0; } } @media (max-width: 900px) { .header-left .workspace-greeting, .header-left .workspace-greeting + .header-divider { display: none; } @@ -325,7 +322,7 @@ label.button:has(input:focus-visible) { outline: 2px solid var(--workspace-focus } @media (prefers-reduced-motion: reduce) { .diagnosis-section-heading h3::after { transition: none; } - .diagnosis-section-body::before, .thinking-steps li, .thinking-steps li > span:last-child { animation: none; } + .diagnosis-section-body::before, .thinking-steps li, .thinking-steps li > span:last-child, .thinking-dot::after { animation: none; } } .draft-task { display: flex; gap: 7px; align-items: flex-start; margin: 7px 0; } .draft-task input { accent-color: var(--workspace-accent-ink); margin-top: 4px; } @@ -709,14 +706,35 @@ label.button:has(input:focus-visible) { outline: 2px solid var(--workspace-focus .chip-row, .dialog[open], .dialog[open]::backdrop, .toast, .home-content, .home-bottom, .conversation, .chat-composer, .user-message, .assistant-message, .header-left > :not(.expand-sidebar), .export-encounter, .panel-scroll, .document-studio > *, .draft-editor, .dialog-inner > :not(.dialog-header), .theoracle-detail, .template-preview, .workflow-form, .form-warning, .studio-columns, .aadi-result, .queue-card, .composer-analysis, .slash-picker, .context-status > span, .storage-warning { animation: fade-in 160ms ease-out; } @starting-style { .submenu-section[data-open="true"] .submenu-item { opacity: 0; } } /* Every fresh answer arrives the same way (Gaffer, 2026-10-17: smooth and simple): the card rises softly into focus, - then a still document's blocks follow one by one. An analysis keeps its own typing reveal; a reopened answer appears at once. */ + then the document's blocks follow one by one: a template's lines, an AADI analysis's sections. The whole answer is + in the page from the first frame (reading aids, copy and print see all of it); only its opacity and offset ease in, + 60 ms apart and capped at the eighth block, so the last block settles within 0.9 s. A reopened answer appears at once. */ .assistant-message[data-reveal] { animation: answer-in 520ms cubic-bezier(.16, 1, .3, 1) both; } -.document-studio[data-reveal] :where(.document-studio > .draft-content > *) { animation: text-in 480ms cubic-bezier(.16, 1, .3, 1) 160ms both; } -@supports (animation-delay: calc(sibling-index() * 1ms)) { .document-studio[data-reveal] :where(.document-studio > .draft-content > *) { animation-delay: calc(100ms + min(sibling-index(), 12) * 60ms); } } +.document-studio[data-reveal] :where(.draft-content, .analysis-document) > * { animation: text-in 480ms cubic-bezier(.16, 1, .3, 1) 100ms both; } +.document-studio[data-reveal] :where(.draft-content, .analysis-document) > :nth-child(2) { animation-delay: 160ms; } +.document-studio[data-reveal] :where(.draft-content, .analysis-document) > :nth-child(3) { animation-delay: 220ms; } +.document-studio[data-reveal] :where(.draft-content, .analysis-document) > :nth-child(4) { animation-delay: 280ms; } +.document-studio[data-reveal] :where(.draft-content, .analysis-document) > :nth-child(5) { animation-delay: 340ms; } +.document-studio[data-reveal] :where(.draft-content, .analysis-document) > :nth-child(6) { animation-delay: 400ms; } +.document-studio[data-reveal] :where(.draft-content, .analysis-document) > :nth-child(7) { animation-delay: 460ms; } +.document-studio[data-reveal] :where(.draft-content, .analysis-document) > :nth-child(n + 8) { animation-delay: 520ms; } @keyframes answer-in { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } } -@media (prefers-reduced-motion: reduce) { .assistant-message[data-reveal], .document-studio[data-reveal] :where(.document-studio > .draft-content > *) { animation: none; } } +@media (prefers-reduced-motion: reduce) { .assistant-message[data-reveal], .document-studio[data-reveal] :where(.draft-content, .analysis-document) > * { animation: none; } } ::view-transition { pointer-events: none; } ::view-transition-group(root), ::view-transition-old(root), ::view-transition-new(root) { animation-duration: 160ms; animation-timing-function: ease-out; } +/* An answer arriving (wait card out, answer and document pane in): the chat column, its composer and the header tools + glide to their new width and place instead of cross-fading as one picture, which showed both layouts at once. Each + picture keeps its size, pinned top left, so text is never stretched; the pane fades in beside them. */ +:root[data-transition="arrive"] .conversation { view-transition-name: arrive-conversation; } +:root[data-transition="arrive"] .chat-composer { view-transition-name: arrive-composer; } +:root[data-transition="arrive"] .header-right { view-transition-name: arrive-tools; } +:root[data-transition="arrive"] .document-pane { view-transition-name: arrive-pane; } +:root[data-transition="arrive"]::view-transition-group(*) { animation-duration: 280ms; animation-timing-function: cubic-bezier(.23, 1, .32, 1); } +:root[data-transition="arrive"]::view-transition-old(*), :root[data-transition="arrive"]::view-transition-new(*) { animation-duration: 200ms; } +:root[data-transition="arrive"]::view-transition-old(arrive-conversation), :root[data-transition="arrive"]::view-transition-new(arrive-conversation), +:root[data-transition="arrive"]::view-transition-old(arrive-composer), :root[data-transition="arrive"]::view-transition-new(arrive-composer), +:root[data-transition="arrive"]::view-transition-old(arrive-tools), :root[data-transition="arrive"]::view-transition-new(arrive-tools) { height: 100%; width: auto; object-fit: none; object-position: left top; overflow: clip; } +:root[data-transition="arrive"]::view-transition-new(arrive-tools), :root[data-transition="arrive"]::view-transition-old(arrive-tools) { object-position: right top; } /* Design audit fixes (Gaffer, 2026-10-11). */ /* D-04: the Encounter title is the page heading in chat view, in the header's own type. */ diff --git a/src/components/smooth.ts b/src/components/smooth.ts index ec1d54c..063f5a1 100644 --- a/src/components/smooth.ts +++ b/src/components/smooth.ts @@ -2,7 +2,11 @@ import { flushSync } from "react-dom"; // A short cross-fade for changes that remove or reflow content (dialogs closing, sidebar, panels), // which CSS alone cannot fade out. Opacity only; reduced motion and older browsers apply the change at once. -export function smooth(update: () => void) { +// kind names a transition with its own timing in globals.css (:root[data-transition]); it is cleared when the fade ends. +export function smooth(update: () => void, kind?: "arrive") { if (typeof document.startViewTransition !== "function" || window.matchMedia("(prefers-reduced-motion: reduce)").matches) { update(); return; } - document.startViewTransition(() => flushSync(update)); + const root = document.documentElement; + if (kind && root) root.dataset.transition = kind; + const transition = document.startViewTransition(() => flushSync(update)); + if (kind && root) void transition?.finished?.finally(() => { if (root.dataset.transition === kind) delete root.dataset.transition; }); } diff --git a/src/components/workspace-views.tsx b/src/components/workspace-views.tsx index c732568..f70c1cb 100644 --- a/src/components/workspace-views.tsx +++ b/src/components/workspace-views.tsx @@ -43,8 +43,6 @@ export function HomeFooter({ onLegal }: { onLegal: (label: string) => void }) { ; } -// Like a chat: a growing conversation keeps the view at the bottom unless the reader has scrolled up; an answer that -// types out is read from its top instead. // The person's place in the analysis line while their case waits for a slot (src/lib/aadi/queue.ts). Nothing is // shown once the analysis runs (0) or when no place is known. export function QueueNotice({ position }: { position?: number | null }) { @@ -56,13 +54,24 @@ export function Conversation({ encounter, pendingQuestion, queuePosition, dispat const conversation = useRef(null); const conversationInner = useRef(null); const stickToBottom = useRef(true); - // A new turn scrolls the bottom into view unless the reader has scrolled up; afterwards a growing conversation keeps - // to the bottom. The answer itself lives in the pane, so nothing types in the chat any more. + const shownCount = useRef(null); + const shownEncounter = useRef(undefined); + // Like a chat, a new question or an opened encounter scrolls the bottom into view and a growing conversation keeps + // to the bottom. A fresh answer is read from its top instead: on a phone the bottom would cut its first lines off. + const encounterId = encounter?.id; + const count = encounter?.messages.length ?? 0; + const lastRole = encounter?.messages.at(-1)?.role; useEffect(() => { const behavior = window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth"; + // The same conversation grew by an answer; a new encounter's first answer counts too (it had no id while waiting). + const sameConversation = shownCount.current !== null && (shownEncounter.current === encounterId || shownEncounter.current === undefined); + const answered = sameConversation && count > (shownCount.current ?? 0) && lastRole === "assistant"; + shownCount.current = count; shownEncounter.current = encounterId; + const answer = answered ? [...conversationInner.current?.querySelectorAll(".assistant-message") ?? []].at(-1) : undefined; + if (answer) { stickToBottom.current = false; answer.scrollIntoView({ behavior, block: "start" }); return; } stickToBottom.current = true; end.current?.scrollIntoView({ behavior, block: "nearest" }); - }, [encounter?.messages.length, pendingQuestion]); + }, [encounterId, count, lastRole, pendingQuestion]); useEffect(() => { const inner = conversationInner.current, box = conversation.current; if (!inner || !box) return; diff --git a/src/components/workspace.tsx b/src/components/workspace.tsx index f2425cb..7f7423d 100644 --- a/src/components/workspace.tsx +++ b/src/components/workspace.tsx @@ -154,17 +154,26 @@ function WorkspaceState({ principalId, onSignOut, userButton }: { principalId: s setBusy(true); setAnalysisError(""); pendingText.current = text.trim(); setPendingQuestion(text.trim()); setPrompt(""); // The home composer gives way to the chat composer; keep typing where the reader is. requestAnimationFrame(() => document.querySelector(".chat-composer textarea")?.focus()); + const finish = () => { if (analysisController.current === controller) { analysisController.current = null; setBusy(false); setPendingQuestion(null); setQueuePosition(null); pendingText.current = null; } }; + let arriving = false; try { const analysis = await requestAadiAnalysis(composerCase(text, current.context, casePatient, caseFields), { signal: controller.signal, onQueuePosition: place => { if (analysisController.current === controller) setQueuePosition(place); } }); if (controller.signal.aborted || analysisController.current !== controller) return; - if (isNew) dispatch({ type: "encounter.add", encounter: { ...current, title: text.trim().slice(0, 48) } }); - dispatch({ type: "message.add", encounterId: current.id, messages: composerAadiMessages(analysis, text, selectedMode, state.reviewDefaults) }); - resetCaseFields(); - dispatch({ type: "encounter.select", id: current.id }); + // The wait card leaves and the answer (with its document pane) arrives in one cross-fade, so the chat column's + // change of width reads as one soft step instead of a jump. A cancel in the frame before the fade still wins. + arriving = true; + smooth(() => { + if (controller.signal.aborted || analysisController.current !== controller) return; + if (isNew) dispatch({ type: "encounter.add", encounter: { ...current, title: text.trim().slice(0, 48) } }); + dispatch({ type: "message.add", encounterId: current.id, messages: composerAadiMessages(analysis, text, selectedMode, state.reviewDefaults) }); + resetCaseFields(); + dispatch({ type: "encounter.select", id: current.id }); + finish(); + }, "arrive"); } catch (error) { if (!controller.signal.aborted) { failedIntoNew.current = isNew; setAnalysisError(error instanceof Error ? error.message : "Analisis belum tersedia. Keluhan tetap tersedia."); setPrompt(text); } } finally { - if (analysisController.current === controller) { analysisController.current = null; setBusy(false); setPendingQuestion(null); setQueuePosition(null); pendingText.current = null; } + if (!arriving) finish(); } } // confirmed: the doctor already chose where a mismatching case goes; fresh: it starts its own encounter, without a patient. diff --git a/tests/ui/answer-arrival.test.tsx b/tests/ui/answer-arrival.test.tsx new file mode 100644 index 0000000..94d795b --- /dev/null +++ b/tests/ui/answer-arrival.test.tsx @@ -0,0 +1,81 @@ +// @vitest-environment jsdom +import { readFileSync } from "node:fs"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { cleanup, render } from "@testing-library/react"; +import { Conversation } from "../../src/components/workspace-views"; +import { smooth } from "../../src/components/smooth"; +import type { Encounter, Message } from "../../src/lib/workspace"; + +const now = new Date().toISOString(); +const question: Message = { id: "q1", role: "user", content: "Batuk dan demam sejak 3 hari", mode: "question", createdAt: now }; +const answer: Message = { id: "a1", role: "assistant", content: "Jawaban singkat.", mode: "question", createdAt: now }; +const encounter = (messages: Message[], id = "enc-1"): Encounter => ({ id, patientId: null, title: "Kasus", createdAt: now, messages, context: "" }); +const props = { queuePosition: null, dispatch: () => undefined, onToast: () => undefined, onReuse: () => undefined, onCancel: () => undefined, onOpenDocument: () => undefined }; + +let scrolled: { element: Element; options: ScrollIntoViewOptions | undefined }[] = []; +beforeEach(() => { + scrolled = []; + Element.prototype.scrollIntoView = function (this: Element, options?: boolean | ScrollIntoViewOptions) { scrolled.push({ element: this, options: typeof options === "object" ? options : undefined }); }; + vi.stubGlobal("matchMedia", (query: string) => ({ matches: false, media: query, addEventListener: () => undefined, removeEventListener: () => undefined })); + vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} }); +}); +afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); + +describe("an answer arriving in the conversation", () => { + it("is read from its top when it lands in a new encounter, not from the bottom", () => { + const view = render(); + scrolled = []; + view.rerender(); + const last = scrolled.at(-1); + expect(last?.element.classList.contains("assistant-message")).toBe(true); + expect(last?.options?.block).toBe("start"); + }); + + it("is read from its top when it lands in an open encounter", () => { + const view = render(); + view.rerender(); + scrolled = []; + const next = [question, answer, { ...question, id: "q2" }, { ...answer, id: "a2" }]; + view.rerender(); + const answers = view.container.querySelectorAll(".assistant-message"); + expect(scrolled.at(-1)?.element).toBe(answers[answers.length - 1]); + expect(scrolled.at(-1)?.options?.block).toBe("start"); + }); + + it("keeps an opened encounter and a new question at the bottom", () => { + const view = render(); + expect(scrolled.at(-1)?.element.classList.contains("assistant-message")).toBe(false); + view.rerender(); + expect(scrolled.at(-1)?.options?.block).toBe("nearest"); + view.rerender(); + expect(scrolled.at(-1)?.options?.block).toBe("nearest"); + }); +}); + +describe("the arrival cross-fade", () => { + it("names its transition while it runs and clears the name when it ends", async () => { + let finish!: () => void; + const finished = new Promise((resolve) => { finish = resolve; }); + let update: (() => void) | undefined; + Object.defineProperty(document, "startViewTransition", { configurable: true, value: (callback: () => void) => { update = callback; return { finished }; } }); + let applied = false; + smooth(() => { applied = true; }, "arrive"); + expect(document.documentElement.dataset.transition).toBe("arrive"); + update?.(); + expect(applied).toBe(true); + finish(); await finished; await Promise.resolve(); + expect(document.documentElement.dataset.transition).toBeUndefined(); + delete (document as { startViewTransition?: unknown }).startViewTransition; + }); +}); + +describe("the reveal of a fresh document", () => { + const css = readFileSync("src/app/globals.css", "utf8"); + it("lets an AADI analysis's sections follow one another in, not only a template's lines", () => { + expect(css).toContain(".document-studio[data-reveal] :where(.draft-content, .analysis-document) > * { animation: text-in"); + expect(css).toContain(":nth-child(n + 8) { animation-delay: 520ms; }"); + }); + it("switches the reveal off under reduced motion", () => { + expect(css).toMatch(/prefers-reduced-motion: reduce\) \{ \.assistant-message\[data-reveal\], \.document-studio\[data-reveal\] :where\(\.draft-content, \.analysis-document\) > \* \{ animation: none; \}/); + }); +}); From e2eecee78f82773ddc18e740abc53fb96f7cec76 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:59:48 +0000 Subject: [PATCH 2/2] feat(aadi): show the analysis's real stages while it runs The wait card no longer shows one generic line for up to 65 s. When the workspace asks for it (Accept: application/x-ndjson), POST /api/aadi streams one line per gateway stage start and end (retrieve_dx, aadi_dx, retrieve_tx, aadi_tx, gate), then the exact reply (status and body) as its last line. Stage lines carry a stage name and state only: no case text, model output, cost, codes or timings. The answer is still sent once, validated and dose-gated exactly as before; model text is not streamed, because streamed text would show ungated doses. Without the header the route is unchanged, and the client falls back to plain JSON when a gateway does not stream. The wait card lists only the stages the gateway reported. Not verified here: that Cloudflare Access in front of the beta server passes lines through unbuffered. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ta9C8RaPJ5eAJ3QcD1cHP --- docs/aadi-integration.md | 25 +++++++ docs/sentrapedia-ui.md | 2 +- src/app/api/aadi/route.ts | 6 +- src/app/globals.css | 1 + src/components/thinking-card.tsx | 32 +++++++-- src/components/workspace-views.tsx | 5 +- src/components/workspace.tsx | 13 ++-- src/lib/aadi/client.ts | 19 +++-- src/lib/aadi/gateway.ts | 8 ++- src/lib/aadi/stage-stream.ts | 70 +++++++++++++++++++ tests/aadi-stage-stream.test.ts | 108 +++++++++++++++++++++++++++++ tests/ui/thinking-card.test.tsx | 20 +++++- 12 files changed, 287 insertions(+), 22 deletions(-) create mode 100644 src/lib/aadi/stage-stream.ts create mode 100644 tests/aadi-stage-stream.test.ts diff --git a/docs/aadi-integration.md b/docs/aadi-integration.md index 392ac9d..2fb742a 100644 --- a/docs/aadi-integration.md +++ b/docs/aadi-integration.md @@ -60,3 +60,28 @@ under `AADI_DATA_POLICY=openai-standard-retention` and input must carry no patie packaging does not add production authentication or establish clinical accuracy. Historical inference timings predate this packaging change. See the dated verification report for fresh install/build/run evidence and remaining limits. + +## Analysis progress + +Since 2026-11-26 (Gaffer: "A + B: tahap nyata + reveal halus") the workspace shows the gateway's real stages while an +analysis runs. Model text is deliberately not streamed: the engine returns one structured result per step, and the +gateway and then the browser validate it and run the dose evidence gate before anything is shown. Streaming text +would put unvalidated, ungated doses on screen. + +- Opt-in: the workspace sends `Accept: application/x-ndjson, application/json` to `POST /api/aadi`. Without that + header the reply is unchanged. +- Streamed reply: status 200, `Content-Type: application/x-ndjson`, `Cache-Control: no-store, no-transform`, + `X-Accel-Buffering: no`; one JSON object per line. + - `{"type":"stage","stage":S,"state":"running"|"done"|"failed"}`, S one of `retrieve_dx`, `aadi_dx`, `retrieve_tx`, + `aadi_tx`, `gate`. Nothing else: no case text, output, cost, error codes or timings. + - Last line `{"type":"final","status":N,"body":B}`: exactly the status and body the plain reply would carry, + refusals included. The browser validates and gates B as before. +- Code: `src/lib/aadi/stage-stream.ts` (writer and reader), `step(request, principal, onStage)` in + `src/lib/aadi/gateway.ts`, wait card `src/components/thinking-card.tsx`. Tests: `tests/aadi-stage-stream.test.ts`, + `tests/ui/thinking-card.test.tsx`. +- Not yet verified: that Cloudflare Access in front of the beta server passes the lines through as they are written. + If it buffers, all stage lines arrive with the answer and the card behaves as before. + +On arrival the answer and the document pane come in through one view transition (`smooth(update, "arrive")`): the chat +column, composer and header tools glide to their new width, and the analysis's sections rise in 60 ms apart. A fresh +answer is scrolled to its top. Under reduced motion everything appears at once (`tests/ui/answer-arrival.test.tsx`). diff --git a/docs/sentrapedia-ui.md b/docs/sentrapedia-ui.md index 9a4ee81..df773a3 100644 --- a/docs/sentrapedia-ui.md +++ b/docs/sentrapedia-ui.md @@ -150,7 +150,7 @@ Terapi Farmakologi: "Untuk ()", satu obat per baris dengan dos ## Workspace berbentuk Glass (2026-11-04) -Menggantikan Clinical Cockpit, rail "Alur kasus", jawaban diketik, dan dialog Pengaturan Agent di atas. Sidebar mengikuti urutan Glass; kanvas terbagi antara chat dan panel dokumen di atas 1200 px (sheet "Dokumen encounter" di bawahnya). Chat berisi prosa, ringkasan dokter, dan kartu dokumen; panel berisi tab Ringkasan encounter dan satu tab per dokumen. Analisis AADI dirender dari hasil mesin yang tersimpan dalam bentuk diferensial Glass (`src/lib/aadi/analysis-view.ts`, `src/components/analysis-document.tsx`): Pembahasan kasus, Kemungkinan utama, Alternatif, Jangan terlewat, Langkah diagnostik berikutnya, Rencana tata laksana (lewat gerbang bukti; dosis yang tidak terverifikasi diberi tanda "Cek dosis obat"), Edukasi dan tindak lanjut, Kutipan pedoman (kartu bernomor, tautan `[n]`). Kartu berpikir hanya melaporkan yang terjadi (permintaan diterima, detik menunggu); jejak pipeline disimpan bersama jawaban. Komposer memakai satu baris chip (8 mode) dan `/` sebagai pemilih penuh. Pengaturan Agent menjadi halaman `/agent` dengan tab Preferensi, Mode dan templat, Pengetahuan; `settings.environment` tampil sebagai pil beranda, `settings.modeInstructions` hanya dipakai draf lokal. Token radius: `--radius-control` 8 px, `--radius-structure` 12 px. Bukti: `docs/verification/glass-redesign-2026-11-04/` (1440, 1024, 375 px; axe 0 pelanggaran). +Menggantikan Clinical Cockpit, rail "Alur kasus", jawaban diketik, dan dialog Pengaturan Agent di atas. Sidebar mengikuti urutan Glass; kanvas terbagi antara chat dan panel dokumen di atas 1200 px (sheet "Dokumen encounter" di bawahnya). Chat berisi prosa, ringkasan dokter, dan kartu dokumen; panel berisi tab Ringkasan encounter dan satu tab per dokumen. Analisis AADI dirender dari hasil mesin yang tersimpan dalam bentuk diferensial Glass (`src/lib/aadi/analysis-view.ts`, `src/components/analysis-document.tsx`): Pembahasan kasus, Kemungkinan utama, Alternatif, Jangan terlewat, Langkah diagnostik berikutnya, Rencana tata laksana (lewat gerbang bukti; dosis yang tidak terverifikasi diberi tanda "Cek dosis obat"), Edukasi dan tindak lanjut, Kutipan pedoman (kartu bernomor, tautan `[n]`). Kartu berpikir hanya melaporkan yang terjadi (permintaan diterima, tahap gateway yang benar-benar dilaporkan sejak 2026-11-26, detik menunggu); jejak pipeline disimpan bersama jawaban. Komposer memakai satu baris chip (8 mode) dan `/` sebagai pemilih penuh. Pengaturan Agent menjadi halaman `/agent` dengan tab Preferensi, Mode dan templat, Pengetahuan; `settings.environment` tampil sebagai pil beranda, `settings.modeInstructions` hanya dipakai draf lokal. Token radius: `--radius-control` 8 px, `--radius-structure` 12 px. Bukti: `docs/verification/glass-redesign-2026-11-04/` (1440, 1024, 375 px; axe 0 pelanggaran). ## Alur kasus yang lebih aman (2026-11-26) diff --git a/src/app/api/aadi/route.ts b/src/app/api/aadi/route.ts index a84c4b5..4c13dfd 100644 --- a/src/app/api/aadi/route.ts +++ b/src/app/api/aadi/route.ts @@ -7,6 +7,7 @@ import { syncPrincipal } from "../../../lib/sync/principal"; import { analysisLimits, analysisQueue } from "../../../lib/aadi/server-guards"; import { parseDailyQuota } from "../../../lib/aadi/limits"; import { loadCatalogue } from "../../../lib/theoracle-catalogue"; +import { stageStreamType, streamAnalysis } from "../../../lib/aadi/stage-stream"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; @@ -43,5 +44,8 @@ export async function POST(request: Request) { // The evidence gate reads the catalogue index; loading it here keeps a broken data folder from failing silently later. loadCatalogue(); // The verified session is the principal the line, the daily quota and the budget count against. - return gateway.step(request, syncPrincipal(access.userId) ?? undefined); + const principal = syncPrincipal(access.userId) ?? undefined; + // A workspace that asks for progress gets each stage as it happens, then the same reply as its last line. + if (request.headers.get("accept")?.includes(stageStreamType)) return streamAnalysis(onStage => gateway.step(request, principal, onStage)); + return gateway.step(request, principal); } diff --git a/src/app/globals.css b/src/app/globals.css index 085af01..1505c90 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -312,6 +312,7 @@ label.button:has(input:focus-visible) { outline: 2px solid var(--workspace-focus .thinking-steps li[data-done="true"] { color: var(--color-text-muted); } .thinking-steps li[data-done="true"] svg { color: var(--workspace-accent-ink); } .thinking-steps li[data-done="false"] > span:last-child { font-weight: var(--weight-semibold); background: linear-gradient(90deg, var(--color-text-secondary) 0%, var(--color-text-primary) 45%, var(--color-text-secondary) 90%) 0 0 / 200% 100%; -webkit-background-clip: text; background-clip: text; color: transparent; animation: thinking-shimmer 1.6s linear infinite; } +.thinking-skip { width: 12px; text-align: center; color: var(--color-text-muted); } .thinking-dot { width: 12px; height: 12px; display: inline-flex; align-items: center; justify-content: center; } .thinking-dot::after { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--color-action-primary); animation: thinking-pulse 1.2s ease-in-out infinite; } @keyframes thinking-pulse { 50% { opacity: .35; transform: scale(.7); } } diff --git a/src/components/thinking-card.tsx b/src/components/thinking-card.tsx index 21a76ff..036701e 100644 --- a/src/components/thinking-card.tsx +++ b/src/components/thinking-card.tsx @@ -2,10 +2,27 @@ import { Check } from "lucide-react"; import { useEffect, useState } from "react"; +import type { AnalysisStage, StageEvent } from "../lib/aadi/stage-stream"; -/** The answer's place while the analysis runs. It reports only what has happened: the request went out, and - * how long the workspace has been waiting. The gateway's stages arrive with the answer (Jejak analisis). */ -export function ThinkingCard({ onCancel, startedAt }: { onCancel: () => void; startedAt?: number }) { +// What each gateway stage is doing, in the doctor's words. Only stages the gateway reports are shown. +export const stageLabels: Record = { + retrieve_dx: "Mencari referensi Oracle", + aadi_dx: "Menyusun diagnosis banding", + retrieve_tx: "Mencari referensi terapi", + aadi_tx: "Menyusun usulan terapi", + gate: "Memeriksa dosis terhadap referensi", +}; + +/** The latest state of each reported stage, in the order the stages first appeared. */ +export function stageProgress(events: readonly StageEvent[]): StageEvent[] { + const latest = new Map(); + for (const event of events) latest.set(event.stage, event); + return [...latest.values()]; +} + +/** The answer's place while the analysis runs. It reports only what has happened: the request went out, each stage the + * gateway has reported (when it streams them), and how long the workspace has been waiting. Nothing is predicted. */ +export function ThinkingCard({ onCancel, startedAt, stages = [] }: { onCancel: () => void; startedAt?: number; stages?: readonly StageEvent[] }) { // The card mounts when the request goes out, so its mount is the start unless the caller knows better. const [started] = useState(() => startedAt ?? performance.now()); const [seconds, setSeconds] = useState(() => elapsed(started)); @@ -13,10 +30,17 @@ export function ThinkingCard({ onCancel, startedAt }: { onCancel: () => void; st const timer = setInterval(() => setSeconds(elapsed(started)), 1000); return () => clearInterval(timer); }, [started]); + const progress = stageProgress(stages); + const running = progress.some((step) => step.state === "running"); return
  1. -
  2. + {progress.map((step) => step.state === "running" + ?
  3. + :
  4. {step.state === "done" ?
  5. )} + {/* Before the first stage (or from a gateway that sends none) the wait itself is the step; after the last one the + gateway is assembling the reply. */} + {!running &&
  6. }
; diff --git a/src/components/workspace-views.tsx b/src/components/workspace-views.tsx index f70c1cb..7841ce3 100644 --- a/src/components/workspace-views.tsx +++ b/src/components/workspace-views.tsx @@ -3,6 +3,7 @@ import { ArrowDownToLine, ChevronDown, Command, FileText, Maximize2, Menu, Minimize2 } from "lucide-react"; import { useEffect, useRef, type ComponentProps } from "react"; import type { Encounter, WorkspaceAction } from "../lib/workspace"; +import type { StageEvent } from "../lib/aadi/stage-stream"; import { Composer } from "./composer"; import { MessageCard } from "./message-card"; import { ThinkingCard } from "./thinking-card"; @@ -49,7 +50,7 @@ export function QueueNotice({ position }: { position?: number | null }) { return position && position >= 1 ?

Posisi antrean: {position}

: null; } -export function Conversation({ encounter, pendingQuestion, queuePosition, dispatch, onToast, onReuse, onCancel, onOpenDocument }: { encounter?: Encounter; pendingQuestion: string | null; queuePosition?: number | null; dispatch: (action: WorkspaceAction) => void; onToast: (text: string, tone?: "error") => void; onReuse: (content: string) => void; onCancel: () => void; onOpenDocument: (id: string) => void }) { +export function Conversation({ encounter, pendingQuestion, queuePosition, stages, dispatch, onToast, onReuse, onCancel, onOpenDocument }: { encounter?: Encounter; pendingQuestion: string | null; queuePosition?: number | null; stages?: readonly StageEvent[]; dispatch: (action: WorkspaceAction) => void; onToast: (text: string, tone?: "error") => void; onReuse: (content: string) => void; onCancel: () => void; onOpenDocument: (id: string) => void }) { const end = useRef(null); const conversation = useRef(null); const conversationInner = useRef(null); @@ -82,7 +83,7 @@ export function Conversation({ encounter, pendingQuestion, queuePosition, dispat return
{ const box = event.currentTarget; stickToBottom.current = box.scrollHeight - box.scrollTop - box.clientHeight < 80; }} aria-label="Percakapan Encounter">
{encounter?.messages.map((message) => dispatch({ type: "message.edit", encounterId: encounter.id, messageId: message.id, content })} onToast={onToast} onReuse={onReuse} onOpenDocument={onOpenDocument}/>)} - {pendingQuestion !== null && <>
{pendingQuestion}
} + {pendingQuestion !== null && <>
{pendingQuestion}
}
; diff --git a/src/components/workspace.tsx b/src/components/workspace.tsx index 7f7423d..7051d32 100644 --- a/src/components/workspace.tsx +++ b/src/components/workspace.tsx @@ -26,6 +26,7 @@ import { paneDocuments } from "../lib/document-pane"; import type { AadiAnalysis } from "../lib/aadi/contract"; import { caseMismatch, composerCase, composerUsesAadi, composerAadiMessages, emptyCaseFields, knownCaseFields, readCaseFields, type CaseFields } from "../lib/aadi/composer"; import { requestAadiAnalysis } from "../lib/aadi/client"; +import type { StageEvent } from "../lib/aadi/stage-stream"; import { smooth } from "./smooth"; import { useMediaQuery, useToast, useWorkspacePersistence } from "./workspace-hooks"; import { WorkspaceUnlock } from "./workspace-unlock"; @@ -77,6 +78,8 @@ function WorkspaceState({ principalId, onSignOut, userButton }: { principalId: s const failedIntoNew = useRef(false); // The question being analysed: shown at once as the user's message, saved only with its answer. const [pendingQuestion, setPendingQuestion] = useState(null); + // The pipeline stages the gateway has reported for the running analysis, oldest first. + const [stages, setStages] = useState([]); const [queuePosition, setQueuePosition] = useState(null); const pendingText = useRef(null); const analysisController = useRef(null); @@ -105,7 +108,7 @@ function WorkspaceState({ principalId, onSignOut, userButton }: { principalId: s // A cancelled question goes back into the composer, whatever cancelled it. if (pendingText.current) setPrompt(pendingText.current); pendingText.current = null; - setBusy(false); setAnalysisError(""); setPendingQuestion(null); + setBusy(false); setAnalysisError(""); setPendingQuestion(null); setStages([]); }, []); // A mode or template picked while an analysis runs leaves it running: the request carries the mode it was sent with, // and the chips are disabled while busy; the / picker and the Command Center must behave the same (review, 2026-11-04). @@ -151,13 +154,13 @@ function WorkspaceState({ principalId, onSignOut, userButton }: { principalId: s async function analyzeMain(text: string, selectedMode: ModeId, current: Encounter, isNew: boolean, casePatient?: Patient) { if (analysisController.current) return; const controller = new AbortController(); analysisController.current = controller; - setBusy(true); setAnalysisError(""); pendingText.current = text.trim(); setPendingQuestion(text.trim()); setPrompt(""); + setBusy(true); setAnalysisError(""); pendingText.current = text.trim(); setPendingQuestion(text.trim()); setStages([]); setPrompt(""); // The home composer gives way to the chat composer; keep typing where the reader is. requestAnimationFrame(() => document.querySelector(".chat-composer textarea")?.focus()); - const finish = () => { if (analysisController.current === controller) { analysisController.current = null; setBusy(false); setPendingQuestion(null); setQueuePosition(null); pendingText.current = null; } }; + const finish = () => { if (analysisController.current === controller) { analysisController.current = null; setBusy(false); setPendingQuestion(null); setQueuePosition(null); setStages([]); pendingText.current = null; } }; let arriving = false; try { - const analysis = await requestAadiAnalysis(composerCase(text, current.context, casePatient, caseFields), { signal: controller.signal, onQueuePosition: place => { if (analysisController.current === controller) setQueuePosition(place); } }); + const analysis = await requestAadiAnalysis(composerCase(text, current.context, casePatient, caseFields), { signal: controller.signal, onQueuePosition: place => { if (analysisController.current === controller) setQueuePosition(place); }, onStage: event => { if (analysisController.current === controller) setStages(list => [...list, event]); } }); if (controller.signal.aborted || analysisController.current !== controller) return; // The wait card leaves and the answer (with its document pane) arrives in one cross-fade, so the chat column's // change of width reads as one soft step instead of a jump. A cancel in the frame before the fade still wins. @@ -243,7 +246,7 @@ function WorkspaceState({ principalId, onSignOut, userButton }: { principalId: s
{!hasMessages ? : <>
- +
{split && paneFor(() => smooth(() => setPane({ open: false })))} diff --git a/src/lib/aadi/client.ts b/src/lib/aadi/client.ts index 7f68c06..378751d 100644 --- a/src/lib/aadi/client.ts +++ b/src/lib/aadi/client.ts @@ -4,6 +4,7 @@ import { validTheOracleGrounding } from "../theoracle-grounding-types"; import { applyTherapyGate, gateEvidence, validGate } from "../theoracle-evidence-gate"; import { addCatalogueRecords, validDisease } from "../theoracle"; import { ensureCatalogueIndex } from "../theoracle-client"; +import { readAnalysisStream, stageStreamType, type StageEvent } from "./stage-stream"; /** A failed analysis request; `code` is the gateway's error code when the server sent one. */ export class AadiRequestError extends Error { @@ -15,12 +16,14 @@ export class AadiRequestError extends Error { // How often the browser asks for its place in line while the analysis request is waiting. export const QUEUE_POLL_MS = 2000; -/** onQueuePosition receives the caller's place while the request waits: 1 is first in line, 0 means it is running. */ -export async function requestAadiAnalysis(caseData: CaseState, options: { signal?: AbortSignal; fetchFn?: typeof fetch; onQueuePosition?: (position: number) => void } = {}): Promise { +/** onQueuePosition receives the caller's place while the request waits: 1 is first in line, 0 means it is running. + * onStage receives each pipeline stage as the gateway reports it (stage-stream.ts); a gateway that answers with plain + * JSON simply reports none. Either way the answer is validated and gated the same way below. */ +export async function requestAadiAnalysis(caseData: CaseState, options: { signal?: AbortSignal; fetchFn?: typeof fetch; onQueuePosition?: (position: number) => void; onStage?: (event: StageEvent) => void } = {}): Promise { if (!validCase(caseData)) throw new Error("Keluhan atau konteks tidak valid atau terlalu panjang."); options.signal?.throwIfAborted(); const snapshot = structuredClone(caseData); - let response: Response; + let status: number; let data: unknown; const fetchFn = options.fetchFn ?? fetch; // The place is informational: a failed or late reading is dropped and never fails the analysis. @@ -31,16 +34,20 @@ export async function requestAadiAnalysis(caseData: CaseState, options: { signal if (waiting && body && typeof body === "object" && "position" in body && typeof body.position === "number" && Number.isInteger(body.position) && body.position >= 0) onPlace(body.position); }).catch(() => undefined); }, QUEUE_POLL_MS) : undefined; + const onStage = options.onStage; try { - response = await fetchFn("/api/aadi", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ case: snapshot }), signal: options.signal }); - data = await response.json(); + const response = await fetchFn("/api/aadi", { method: "POST", headers: { "Content-Type": "application/json", ...(onStage ? { Accept: `${stageStreamType}, application/json` } : {}) }, body: JSON.stringify({ case: snapshot }), signal: options.signal }); + if (onStage && response.headers.get("content-type")?.startsWith(stageStreamType)) { + const final = await readAnalysisStream(response, event => { if (!options.signal?.aborted) onStage(event); }); + status = final.status; data = final.body; + } else { status = response.status; data = await response.json(); } } catch (error) { // A cancel stays a cancel; a lost connection or unreadable body gets the same wording as the server's 502. if (options.signal?.aborted) throw error; throw new Error("Layanan analisis tidak dapat dihubungi atau respons tidak dapat dibaca."); } finally { waiting = false; clearInterval(poll); } options.signal?.throwIfAborted(); - if (!response.ok) { + if (status < 200 || status > 299) { const error = data && typeof data === "object" && "error" in data && data.error && typeof data.error === "object" ? data.error : {}; const message = "message" in error && typeof error.message === "string" ? error.message : "Analisis belum tersedia. Keluhan tetap tersedia."; throw new AadiRequestError(message, "code" in error && typeof error.code === "string" ? error.code : undefined); diff --git a/src/lib/aadi/gateway.ts b/src/lib/aadi/gateway.ts index a256609..805dd1d 100644 --- a/src/lib/aadi/gateway.ts +++ b/src/lib/aadi/gateway.ts @@ -6,6 +6,7 @@ import { THEORACLE_GROUNDING_CAPABILITY, TheOracleGroundingError, validTheOracle import type { CaseState } from "./types"; import type { AnalysisQueue, QueueRefusal } from "./queue"; import type { AnalysisLimits } from "./limits"; +import { isAnalysisStage, type StageEvent } from "./stage-stream"; type Options = { queue?: AnalysisQueue; limits?: AnalysisLimits; fetchFn?: typeof fetch; baseUrl?: string; token?: string; timeoutMs?: number; model?: string; maxCostUsd?: number; retrieveGrounding?: (caseData: CaseState) => Promise; retrieveTherapyGrounding?: (caseData: CaseState, diagnosis: { icd10: string; label: string }) => Promise; targetedTherapy?: boolean; retrievalTimeoutMs?: number; publicOrigin?: string; maxConcurrent?: number; log?: (entry: StageLog) => void; catalogue?: () => readonly Disease[] }; export interface StageLog { traceId: string; stage: string; ms: number; ok: boolean; code?: string } @@ -74,7 +75,8 @@ export function createAadiGateway(options: Options = {}) { return reply({ reachable: status.reachable, modelReady: status.modelReady, groundingReady: status.groundingReady, configured: !!base && !!token, model: selectedModel ?? null, maxCostUsd: selectedModel ? maxCostUsd : null }); }, // principal is the verified session's id (src/app/api/aadi/route.ts), never a value from the request body. - async step(request: Request, principal?: string): Promise { + // onStage hears each pipeline stage start and end (stage-stream.ts); the reply is the same with or without it. + async step(request: Request, principal?: string, onStage?: (event: StageEvent) => void): Promise { const origin = request.headers.get("origin"); if (publicOrigin && origin === publicOrigin) { // The browser's Origin is the guard here; Host is the public name, or loopback when the tunnel rewrites it. @@ -127,9 +129,11 @@ export function createAadiGateway(options: Options = {}) { const traceId = crypto.randomUUID(); const createdAt = new Date().toISOString(); const stages: StageLog[] = []; const log = options.log ?? (entry => console.info(JSON.stringify({ event: "aadi.stage", ...entry }))); - const record = (stage: string, started: number, ok: boolean, code?: string) => { const entry = { traceId, stage, ms: Math.round(performance.now() - started), ok, ...(code ? { code } : {}) }; stages.push(entry); log(entry); }; + const notify = (stage: string, state: StageEvent["state"]) => { if (onStage && isAnalysisStage(stage)) try { onStage({ stage, state }); } catch { /* progress never fails the analysis */ } }; + const record = (stage: string, started: number, ok: boolean, code?: string) => { const entry = { traceId, stage, ms: Math.round(performance.now() - started), ok, ...(code ? { code } : {}) }; stages.push(entry); log(entry); notify(stage, ok ? "done" : "failed"); }; const timed = async (stage: string, run: () => Promise, limitMs?: number): Promise => { const started = performance.now(); + notify(stage, "running"); let timer: ReturnType | undefined; try { const value = await (limitMs ? Promise.race([run(), new Promise((_, fail) => { timer = setTimeout(() => fail(stage.startsWith("retrieve") ? new TheOracleGroundingError("THEORACLE_UNAVAILABLE", "Pencarian Oracle melewati batas waktu.") : new ServiceFailure("TIMEOUT")), limitMs); })]) : run()); diff --git a/src/lib/aadi/stage-stream.ts b/src/lib/aadi/stage-stream.ts new file mode 100644 index 0000000..dc5e6d8 --- /dev/null +++ b/src/lib/aadi/stage-stream.ts @@ -0,0 +1,70 @@ +// Progress of one analysis, sent while it runs (docs/aadi-integration.md, "Analysis progress"). +// A stage line carries a stage name and its state only: never case text, model output, cost or timing. The answer itself +// travels once, in the final line, exactly as the JSON reply would carry it, and is validated and gated as before. + +/** The gateway stages a doctor sees, in pipeline order (src/lib/aadi/gateway.ts). */ +export const analysisStages = ["retrieve_dx", "aadi_dx", "retrieve_tx", "aadi_tx", "gate"] as const; +export type AnalysisStage = typeof analysisStages[number]; +export type StageState = "running" | "done" | "failed"; +export interface StageEvent { stage: AnalysisStage; state: StageState } + +export const stageStreamType = "application/x-ndjson"; +// The final line holds the whole reply (the gateway caps the engine body at 1 MiB); anything larger is refused. +const STREAM_LIMIT = 2 * 1048576; + +export const isAnalysisStage = (value: unknown): value is AnalysisStage => typeof value === "string" && (analysisStages as readonly string[]).includes(value); +const isState = (value: unknown): value is StageState => value === "running" || value === "done" || value === "failed"; + +/** Server: runs one analysis and streams its stage events, then its reply (status and body) as the last line. */ +export function streamAnalysis(run: (onStage: (event: StageEvent) => void) => Promise): Response { + const encoder = new TextEncoder(); + const body = new ReadableStream({ + async start(controller) { + let open = true; + const send = (line: unknown) => { if (!open) return; try { controller.enqueue(encoder.encode(`${JSON.stringify(line)}\n`)); } catch { open = false; } }; + let final: { status: number; body: unknown }; + try { + const reply = await run((event) => send({ type: "stage", stage: event.stage, state: event.state })); + final = { status: reply.status, body: await reply.json().catch(() => null) }; + } catch { + final = { status: 502, body: { error: { code: "NETWORK", message: "Layanan analisis tidak dapat dihubungi atau respons tidak dapat dibaca." } } }; + } + send({ type: "final", ...final }); + if (open) { open = false; try { controller.close(); } catch { /* the reader already left */ } } + }, + }); + // no-transform and X-Accel-Buffering ask proxies on the way not to hold the lines back until the end. + return new Response(body, { status: 200, headers: { "Content-Type": `${stageStreamType}; charset=utf-8`, "Cache-Control": "no-store, no-transform", "X-Accel-Buffering": "no" } }); +} + +/** Browser: reads a stage stream, reporting each valid stage event, and returns the final reply. Lines it does not know + * are skipped; a stream that ends without a final line, or grows past the limit, throws. */ +export async function readAnalysisStream(response: Response, onStage: (event: StageEvent) => void): Promise<{ status: number; body: unknown }> { + const reader = response.body?.getReader(); + if (!reader) throw new Error("STREAM"); + const decoder = new TextDecoder(); + let buffer = ""; let size = 0; + let final: { status: number; body: unknown } | null = null; + const take = (line: string) => { + if (!line.trim()) return; + let value: unknown; + try { value = JSON.parse(line); } catch { return; } + if (!value || typeof value !== "object" || !("type" in value)) return; + if (value.type === "stage" && "stage" in value && isAnalysisStage(value.stage) && "state" in value && isState(value.state)) onStage({ stage: value.stage, state: value.state }); + else if (value.type === "final" && "status" in value && typeof value.status === "number" && Number.isInteger(value.status)) final = { status: value.status, body: "body" in value ? value.body : null }; + }; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + size += value.length; + if (size > STREAM_LIMIT) throw new Error("STREAM_LIMIT"); + buffer += decoder.decode(value, { stream: true }); + let at: number; + while ((at = buffer.indexOf("\n")) >= 0) { take(buffer.slice(0, at)); buffer = buffer.slice(at + 1); } + } + take(buffer + decoder.decode()); + } catch (error) { await reader.cancel().catch(() => undefined); throw error; } + if (!final) throw new Error("STREAM"); + return final; +} diff --git a/tests/aadi-stage-stream.test.ts b/tests/aadi-stage-stream.test.ts new file mode 100644 index 0000000..3bd824b --- /dev/null +++ b/tests/aadi-stage-stream.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from "vitest"; +import { selectedAadiModel } from "../src/lib/aadi/model-profile"; +import { createAadiGateway } from "../src/lib/aadi/gateway"; +import { emptyCase } from "../src/lib/aadi/contract"; +import { requestAadiAnalysis } from "../src/lib/aadi/client"; +import { readAnalysisStream, streamAnalysis, stageStreamType, type StageEvent } from "../src/lib/aadi/stage-stream"; +import { THEORACLE_GROUNDING_CAPABILITY, type TheOracleGroundingBundle } from "../src/lib/theoracle-grounding-types"; + +const version = `aadi-service/test+contract=1+provider=openai+data=synthetic-only+plan=${selectedAadiModel}+assess=${selectedAadiModel}+experimental`; +const meta = { version, model: `${selectedAadiModel}+${selectedAadiModel}`, costUsd: 0.01 }; +const complaint = "Batuk demam fiktif"; +const input = () => new Request("http://127.0.0.1:3104/api/aadi", { method: "POST", headers: { Origin: "http://127.0.0.1:3104", "Content-Type": "application/json" }, body: JSON.stringify({ case: { ...emptyCase(), chiefComplaint: complaint } }) }); +const bundle = (text: string): TheOracleGroundingBundle => ({ version: THEORACLE_GROUNDING_CAPABILITY, corpus: { name: "TheOracle", indexSha256: "a".repeat(64), embeddingModel: { id: "onnx-community/embeddinggemma-300m-ONNX", revision: "e".repeat(40), dtype: "fp32", dims: 768 }, retrievedAt: "2026-10-11T12:00:00.000Z", reviewProvenance: "fixture" }, queryDigest: "b".repeat(64), evidence: [{ evidenceId: "E1", text, retrievalRank: 1, similarity: 0.6, source: { title: "ppk.pdf", docSource: "uji", origin: "fixture", textSha256: "c".repeat(64) } }] }); +const therapy = { forDiagnosis: { icd10: "J18.9", label: "Pneumonia" }, regimen: [{ drug: "Amoxicillin", dose: "3x500mg", route: "PO", duration: "5 hari", note: "" }], interactions: [], contraindications: [] }; +const engine: typeof fetch = async (url) => { + const path = new URL(String(url)).pathname; + if (path === "/healthz") return Response.json({ status: "ok", contractVersion: "1", version, capabilities: [THEORACLE_GROUNDING_CAPABILITY, "theoracle-targeted-therapy-v1"] }); + if (path === "/v1/therapy/step") return Response.json({ contractVersion: "1", status: "ok", therapy, meta }); + return Response.json({ contractVersion: "1", status: "ok", differential: { likely: [{ icd10: "J18.9", label: "Pneumonia", confidenceTier: "low" }], alternatives: [], cannotMiss: [] }, evidence: [], missingInformation: [], nextBestActions: [], disposition: null, unfilled: [], meta }); +}; +const gateway = () => createAadiGateway({ model: selectedAadiModel, maxCostUsd: 0.1, token: "test-only", fetchFn: engine, targetedTherapy: true, log: () => undefined, + retrieveGrounding: async () => bundle("Batuk dan demam."), retrieveTherapyGrounding: async () => bundle("Pneumonia: amoksisilin 500 mg 3 kali sehari.") }); +const lines = async (response: Response) => (await response.text()).trim().split("\n").map(line => JSON.parse(line) as Record); +// traceId and createdAt differ per request; everything else in the reply must match. +const stable = (body: Record) => ({ ...body, traceId: "", createdAt: "", pipeline: { ...(body.pipeline as object), stages: ((body.pipeline as { stages: { stage: string; ok: boolean }[] }).stages).map(s => [s.stage, s.ok]) } }); + +describe("analysis stage progress from the gateway", () => { + it("reports each stage as it starts and ends, in pipeline order, without changing the reply", async () => { + const events: StageEvent[] = []; + const withProgress = await (await gateway().step(input(), undefined, event => events.push(event))).json(); + const plain = await (await gateway().step(input())).json(); + expect(events.map(e => `${e.stage}:${e.state}`)).toEqual(["retrieve_dx:running", "retrieve_dx:done", "aadi_dx:running", "aadi_dx:done", "retrieve_tx:running", "retrieve_tx:done", "aadi_tx:running", "aadi_tx:done", "gate:running", "gate:done"]); + expect(stable(withProgress)).toEqual(stable(plain)); + }); + + it("streams stage lines that carry only a stage name and state, then the same reply as its last line", async () => { + const response = streamAnalysis(onStage => gateway().step(input(), undefined, onStage)); + expect(response.headers.get("content-type")).toContain(stageStreamType); + expect(response.headers.get("cache-control")).toBe("no-store, no-transform"); + const all = await lines(response); + const stages = all.slice(0, -1); + expect(stages).toHaveLength(10); + for (const line of stages) expect(Object.keys(line).sort()).toEqual(["stage", "state", "type"]); + expect(JSON.stringify(stages)).not.toMatch(/Batuk|Pneumonia|Amoxicillin|mg/); + const final = all.at(-1)!; + expect(final.type).toBe("final"); + expect(final.status).toBe(200); + expect(stable(final.body as Record)).toEqual(stable(await (await gateway().step(input())).json())); + }); + + it("carries a refusal as the final line with its status, before any stage", async () => { + const refused = new Request("http://127.0.0.1:3104/api/aadi", { method: "POST", headers: { Origin: "http://evil.example", "Content-Type": "application/json" }, body: "{}" }); + const all = await lines(streamAnalysis(onStage => gateway().step(refused, undefined, onStage))); + expect(all).toHaveLength(1); + expect(all[0]).toMatchObject({ type: "final", status: 403, body: { error: { code: "ORIGIN" } } }); + }); +}); + +const ndjson = (text: string) => new Response(text, { headers: { "Content-Type": `${stageStreamType}; charset=utf-8` } }); + +describe("reading the stage stream in the browser", () => { + it("reports valid stage lines, skips unknown or malformed ones, and returns the final reply", async () => { + const seen: StageEvent[] = []; + const text = [ + JSON.stringify({ type: "stage", stage: "retrieve_dx", state: "running" }), + "not json", + JSON.stringify({ type: "stage", stage: "route", state: "failed" }), + JSON.stringify({ type: "stage", stage: "aadi_dx", state: "thinking" }), + JSON.stringify({ type: "stage", stage: "retrieve_dx", state: "done" }), + JSON.stringify({ type: "final", status: 200, body: { ok: true } }), + ].join("\n"); + const final = await readAnalysisStream(ndjson(text), event => seen.push(event)); + expect(seen).toEqual([{ stage: "retrieve_dx", state: "running" }, { stage: "retrieve_dx", state: "done" }]); + expect(final).toEqual({ status: 200, body: { ok: true } }); + }); + it("throws when the stream ends without a final line", async () => { + await expect(readAnalysisStream(ndjson(JSON.stringify({ type: "stage", stage: "aadi_dx", state: "running" })), () => undefined)).rejects.toThrow(); + }); +}); + +describe("the workspace client with stage progress", () => { + const caseData = { ...emptyCase(), chiefComplaint: "Kasus fiktif untuk pengujian" }; + const grounding = bundle("Kutipan TheOracle"); + const reply = { traceId: "test-trace", createdAt: "2026-10-09T00:00:00Z", grounding, result: { contractVersion: "1", status: "ok", differential: { likely: [{ icd10: "R51", label: "Hipotesis uji fiktif", confidenceTier: "low" }], alternatives: [], cannotMiss: [] }, evidence: [], missingInformation: [], nextBestActions: [], disposition: null, unfilled: [], meta: { version: "test", model: "test", costUsd: 0.01 } } }; + it("asks for progress, reports the stages and returns the same analysis as the JSON reply", async () => { + const seen: StageEvent[] = []; + let accept = ""; + const streamed = await requestAadiAnalysis(caseData, { onStage: event => seen.push(event), fetchFn: async (url, init) => { + if (url !== "/api/aadi") return Response.json(reply); + accept = new Headers(init?.headers).get("accept") ?? ""; + return ndjson(`${JSON.stringify({ type: "stage", stage: "aadi_dx", state: "running" })}\n${JSON.stringify({ type: "final", status: 200, body: reply })}\n`); + } }); + const plain = await requestAadiAnalysis(caseData, { fetchFn: async () => Response.json(reply) }); + expect(accept).toContain(stageStreamType); + expect(seen).toEqual([{ stage: "aadi_dx", state: "running" }]); + expect(streamed).toEqual(plain); + }); + it("reports a streamed refusal with the server's message and code", async () => { + const refusal = { error: { code: "BUSY", message: "Antrean analisis sedang penuh. Coba kembali sebentar lagi." } }; + await expect(requestAadiAnalysis(caseData, { onStage: () => undefined, fetchFn: async () => ndjson(`${JSON.stringify({ type: "final", status: 429, body: refusal })}\n`) })).rejects.toMatchObject({ message: refusal.error.message, code: "BUSY" }); + }); + it("still works with a gateway that answers in plain JSON", async () => { + const seen: StageEvent[] = []; + const analysis = await requestAadiAnalysis(caseData, { onStage: event => seen.push(event), fetchFn: async () => Response.json(reply) }); + expect(seen).toEqual([]); + expect(analysis.traceId).toBe("test-trace"); + }); +}); diff --git a/tests/ui/thinking-card.test.tsx b/tests/ui/thinking-card.test.tsx index 2d7c9e6..16745bc 100644 --- a/tests/ui/thinking-card.test.tsx +++ b/tests/ui/thinking-card.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from "vitest"; import { cleanup, render, screen, within } from "@testing-library/react"; -import { ThinkingCard } from "../../src/components/thinking-card"; +import { ThinkingCard, stageProgress } from "../../src/components/thinking-card"; afterEach(cleanup); @@ -19,3 +19,21 @@ describe("ThinkingCard", () => { expect(screen.getByText(/Menunggu jawaban AADI · 7 dtk/)).toBeTruthy(); }); }); + +describe("the wait card with stage progress", () => { + it("shows only the stages the gateway reported, done ones ticked and the running one with the time", () => { + render( undefined} stages={[{ stage: "retrieve_dx", state: "running" }, { stage: "retrieve_dx", state: "done" }, { stage: "aadi_dx", state: "running" }]}/>); + const items = screen.getAllByRole("listitem").map(item => item.textContent); + expect(items).toEqual(["Permintaan diterima", "Mencari referensi Oracle", expect.stringMatching(/^Menyusun diagnosis banding · \d+ dtk$/)]); + expect(screen.queryByText(/Menyusun usulan terapi/)).toBeNull(); + expect(screen.queryByText(/Menunggu jawaban AADI/)).toBeNull(); + }); + it("says a failed stage did not succeed, and that the reply is being assembled once no stage runs", () => { + render( undefined} stages={[{ stage: "retrieve_tx", state: "running" }, { stage: "retrieve_tx", state: "failed" }]}/>); + expect(screen.getByText("Mencari referensi terapi · tidak berhasil")).toBeTruthy(); + expect(screen.getByText(/Menyelesaikan jawaban · \d+ dtk/)).toBeTruthy(); + }); + it("keeps each stage once, in the order it first appeared", () => { + expect(stageProgress([{ stage: "aadi_dx", state: "running" }, { stage: "gate", state: "running" }, { stage: "aadi_dx", state: "done" }])).toEqual([{ stage: "aadi_dx", state: "done" }, { stage: "gate", state: "running" }]); + }); +});