AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
fix(ui): show turn progress while the executive is still working (#261)
Rufus29f634ba9d69
diff --git a/packages/ui/scripts/turnStatus.test.mjs b/packages/ui/scripts/turnStatus.test.mjsnew file mode 100644index 00000000..18b5a442--- /dev/null+++ b/packages/ui/scripts/turnStatus.test.mjs@@ -0,0 +1,85 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ LABEL_WAIT_AFTER_MS,+ SHOW_ELAPSED_AFTER_MS,+ STALL_MS,+ formatElapsed,+ turnStatus,+} from "../src/lib/turnStatus.ts";++const base = {+ isLoading: true,+ hasText: false,+ isConsulting: false,+ activityLabel: null,+ inCommittee: false,+ msSinceTurnStart: 0,+ msSinceLastEvent: 0,+ fallbackLabel: "Working…",+};++test("nothing shows when no turn is running", () => {+ assert.deepEqual(turnStatus({ ...base, isLoading: false, isConsulting: true }), {+ show: false,+ label: null,+ elapsed: null,+ });+});++test("before any event, the dots show alone and then get the fallback label", () => {+ assert.deepEqual(turnStatus(base), { show: true, label: null, elapsed: null });+ const later = turnStatus({ ...base, msSinceTurnStart: LABEL_WAIT_AFTER_MS });+ assert.equal(later.label, "Working…");+});++test("a tool round shows its activity label", () => {+ const s = turnStatus({ ...base, isConsulting: true, activityLabel: "Consulting specialists…" });+ assert.equal(s.show, true);+ assert.equal(s.label, "Consulting specialists…");+});++test("a tool round after text has streamed still shows", () => {+ const s = turnStatus({+ ...base,+ hasText: true,+ isConsulting: true,+ activityLabel: "Searching the web…",+ });+ assert.equal(s.show, true);+ assert.equal(s.label, "Searching the web…");+});++test("a tool round with no label uses the fallback", () => {+ assert.equal(turnStatus({ ...base, isConsulting: true }).label, "Working…");+});++test("flowing text hides the status; stalled text brings it back", () => {+ const flowing = turnStatus({ ...base, hasText: true, msSinceLastEvent: STALL_MS - 1 });+ assert.equal(flowing.show, false);+ const stalled = turnStatus({ ...base, hasText: true, msSinceLastEvent: STALL_MS });+ assert.deepEqual(stalled, { show: true, label: "Working…", elapsed: null });+});++test("committee review shows without a label, even after text", () => {+ const s = turnStatus({ ...base, hasText: true, inCommittee: true, isConsulting: true });+ assert.equal(s.show, true);+ assert.equal(s.label, null);+});++test("elapsed time appears only once the turn has run a while", () => {+ assert.equal(+ turnStatus({ ...base, msSinceTurnStart: SHOW_ELAPSED_AFTER_MS - 1 }).elapsed,+ null,+ );+ assert.equal(turnStatus({ ...base, msSinceTurnStart: 42_300 }).elapsed, "42s");+});++test("formatElapsed", () => {+ assert.equal(formatElapsed(0), "0s");+ assert.equal(formatElapsed(-5), "0s");+ assert.equal(formatElapsed(59_999), "59s");+ assert.equal(formatElapsed(60_000), "1m 00s");+ assert.equal(formatElapsed(65_000), "1m 05s");+ assert.equal(formatElapsed(3_725_000), "62m 05s");+});diff --git a/packages/ui/src/components/Chat.tsx b/packages/ui/src/components/Chat.tsxindex dcf55cc4..5867b032 100644--- a/packages/ui/src/components/Chat.tsx+++ b/packages/ui/src/components/Chat.tsx@@ -4,7 +4,7 @@ import { useEffect, useRef, useState } from "react";import { useSession } from "next-auth/react";import Message from "./Message";import BrandMark from "./BrandMark";-import CommitteePhaseIndicator from "./CommitteePhaseIndicator";+import TurnStatusRow, { useTurnClock } from "./TurnStatusRow";import Icon from "./Icon";import InfoTip from "./InfoTip";import {@@ -24,6 +24,7 @@ import {} from "@/lib/api";import { answerSourcesFrom, type AnswerSources } from "@/lib/answerSources";import { isAbortError, useStoppableTurn } from "@/lib/use-stoppable-turn";+import { turnStatus } from "@/lib/turnStatus";interface ChatProps {onDebugEvent?: (event: DebugEvent) => void;@@ -89,6 +90,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,const [activityLabel, setActivityLabel] = useState<string | null>(null);const [committeeEnabled, setCommitteeEnabled] = useState(false);const [committeePhase, setCommitteePhase] = useState<CommitteePhase | null>(null);+ const turnClock = useTurnClock(isLoading);const [suggested, setSuggested] = useState<string[]>([]);const [subtitle, setSubtitle] = useState<string>(FALLBACK_SUBTITLE);const [isLoadingPrompts, setIsLoadingPrompts] = useState(true);@@ -239,6 +241,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,clearFollowup();setMessages((prev) => [...prev, { role: "user", content: userBubbleContent }]);setIsLoading(true);+ turnClock.start();setStreamingContent("");setStreamingActions([]);setIsConsulting(false);@@ -274,6 +277,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,signal,memoryText: turnMemoryText,})) {+ turnClock.markEvent();if (item.type === "debug_event") {onDebugEvent?.(item);continue;@@ -413,6 +417,19 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,setMessageFeedback(sessionId, target.id, value).catch(() => apply(previous));}+ // The "still working" line: before the reply starts, and again under the+ // partial reply whenever the Executive goes quiet to run a tool.+ const status = turnStatus({+ isLoading,+ hasText: Boolean(streamingContent),+ isConsulting,+ activityLabel,+ inCommittee: committeePhase !== null,+ msSinceTurnStart: turnClock.msSinceTurnStart,+ msSinceLastEvent: turnClock.msSinceLastEvent,+ fallbackLabel: FALLBACK_ACTIVITY_LABEL,+ });+// Fill the composer with the suggestion without sending it, so the user// can edit first. The suggestion is kept: clearing the box shows it again.function acceptFollowup() {@@ -548,34 +565,22 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,content={streamingContent}isStreamingactions={streamingActions.length > 0 ? streamingActions : undefined}+ status={+ status.show ? (+ <TurnStatusRow status={status} committeePhase={committeePhase} />+ ) : undefined+ }/>)}- {isLoading && !streamingContent && (+ {status.show && !streamingContent && (<div className="flex gap-4 mb-8"><div className="flex-shrink-0 mt-1"><BrandMark size="md" /></div><div className="flex-1 pt-1.5"><div className="text-xs text-fg-muted mb-3 font-medium tracking-wide uppercase">Executive</div>- <div className="flex items-center gap-2 flex-wrap">- <div className="flex gap-1.5" aria-label="Thinking">- {[0, 1, 2].map((i) => (- <div- key={i}- className="w-1.5 h-1.5 bg-fg-muted rounded-full animate-bounce motion-reduce:animate-none"- style={{ animationDelay: `${i * 0.15}s` }}- />- ))}- </div>- {committeePhase ? (- <CommitteePhaseIndicator phase={committeePhase} />- ) : isConsulting ? (- <span className="text-xs text-fg-muted italic">- {activityLabel ?? FALLBACK_ACTIVITY_LABEL}- </span>- ) : null}- </div>+ <TurnStatusRow status={status} committeePhase={committeePhase} /></div></div>)}diff --git a/packages/ui/src/components/Message.tsx b/packages/ui/src/components/Message.tsxindex 3d471f01..c5e47bc3 100644--- a/packages/ui/src/components/Message.tsx+++ b/packages/ui/src/components/Message.tsx@@ -1,5 +1,6 @@"use client";+import type { ReactNode } from "react";import Link from "next/link";import ReactMarkdown from "react-markdown";import remarkGfm from "remark-gfm";@@ -28,6 +29,9 @@ interface MessageProps {// given (the reply has a stored id) and the reply has finished streaming.feedback?: "up" | "down" | null;onFeedback?: (value: "up" | "down" | null) => void;+ // Shown under the text while the reply streams, e.g. the "still working"+ // line when the Executive goes quiet mid-reply to run a tool.+ status?: ReactNode;}function FeedbackButtons({@@ -112,6 +116,7 @@ export default function Message({sources,feedback,onFeedback,+ status,}: MessageProps) {if (role === "user") {return (@@ -152,6 +157,8 @@ export default function Message({)}</div>+ {status && <div className="mt-3">{status}</div>}+{actions && actions.length > 0 && (<divclassName="mt-3 flex flex-wrap gap-1.5"diff --git a/packages/ui/src/components/TurnStatusRow.tsx b/packages/ui/src/components/TurnStatusRow.tsxnew file mode 100644index 00000000..6e110dce--- /dev/null+++ b/packages/ui/src/components/TurnStatusRow.tsx@@ -0,0 +1,68 @@+"use client";++import { useEffect, useRef, useState } from "react";+import CommitteePhaseIndicator from "./CommitteePhaseIndicator";+import type { CommitteePhase } from "@/lib/api";+import type { TurnStatus } from "@/lib/turnStatus";++// Re-renders once a second while a turn runs and tracks when it started and+// when its last stream event arrived, for `turnStatus`. Call `start` in the+// same handler that sets the turn loading, so the first render of the turn+// already reads fresh times, and `markEvent` for every streamed item.+export function useTurnClock(isLoading: boolean) {+ const startedAt = useRef(0);+ const lastEventAt = useRef(0);+ const [now, setNow] = useState(0);++ useEffect(() => {+ if (!isLoading) return;+ const id = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(id);+ }, [isLoading]);++ return {+ msSinceTurnStart: now - startedAt.current,+ msSinceLastEvent: now - lastEventAt.current,+ start: () => {+ const t = Date.now();+ startedAt.current = t;+ lastEventAt.current = t;+ setNow(t);+ },+ markEvent: () => {+ lastEventAt.current = Date.now();+ },+ };+}++export default function TurnStatusRow({+ status,+ committeePhase,+}: {+ status: TurnStatus;+ committeePhase: CommitteePhase | null;+}) {+ return (+ <div className="flex items-center gap-2 flex-wrap">+ <div className="flex gap-1.5" aria-label="Thinking">+ {[0, 1, 2].map((i) => (+ <div+ key={i}+ className="w-1.5 h-1.5 bg-fg-muted rounded-full animate-bounce motion-reduce:animate-none"+ style={{ animationDelay: `${i * 0.15}s` }}+ />+ ))}+ </div>+ {committeePhase ? (+ <CommitteePhaseIndicator phase={committeePhase} />+ ) : status.label ? (+ <span className="text-xs text-fg-muted italic" aria-live="polite">+ {status.label}+ </span>+ ) : null}+ {status.elapsed && (+ <span className="text-xs text-fg-muted/70 tabular-nums">· {status.elapsed}</span>+ )}+ </div>+ );+}diff --git a/packages/ui/src/components/askoe/AskOEPanel.tsx b/packages/ui/src/components/askoe/AskOEPanel.tsxindex 049ce5f4..b8ae7576 100644--- a/packages/ui/src/components/askoe/AskOEPanel.tsx+++ b/packages/ui/src/components/askoe/AskOEPanel.tsx@@ -4,10 +4,12 @@ import { useCallback, useEffect, useRef, useState } from "react";import Icon from "@/components/Icon";import Message from "@/components/Message";+import TurnStatusRow, { useTurnClock } from "@/components/TurnStatusRow";import { useAskOE } from "@/components/askoe/AskOEContext";import { answerSourcesFrom, type AnswerSources } from "@/lib/answerSources";import type { ActionTaken, FormPatch } from "@/lib/api";-import { setMessageFeedback, streamChat } from "@/lib/api";+import { FALLBACK_ACTIVITY_LABEL, setMessageFeedback, streamChat } from "@/lib/api";+import { turnStatus } from "@/lib/turnStatus";import { isAbortError, useStoppableTurn } from "@/lib/use-stoppable-turn";// One proposal card per form_patch event: what was applied/skipped, the@@ -95,6 +97,7 @@ export default function AskOEPanel() {const [streaming, setStreaming] = useState(false);const [streamingContent, setStreamingContent] = useState("");const [activityLabel, setActivityLabel] = useState<string | null>(null);+ const turnClock = useTurnClock(streaming);const [sessionId, setSessionId] = useState<string | undefined>(undefined);const [error, setError] = useState<string | null>(null);const scrollRef = useRef<HTMLDivElement>(null);@@ -148,6 +151,7 @@ export default function AskOEPanel() {setInput("");setMessages((prev) => [...prev, { role: "user", content: trimmed }]);setStreaming(true);+ turnClock.start();setStreamingContent("");setActivityLabel(null);const { clientTurnId, signal } = beginTurn();@@ -167,6 +171,7 @@ export default function AskOEPanel() {clientTurnId,signal,})) {+ turnClock.markEvent();if (item.type === "chunk" && item.content) {content += item.content;setActivityLabel(null);@@ -287,6 +292,19 @@ export default function AskOEPanel() {if (!ctx.open) return null;+ // The panel ignores `thinking`: an `activity` label that arrived after the+ // last chunk (a chunk clears it) is what marks a tool round in progress.+ const status = turnStatus({+ isLoading: streaming,+ hasText: Boolean(streamingContent),+ isConsulting: activityLabel !== null,+ activityLabel,+ inCommittee: false,+ msSinceTurnStart: turnClock.msSinceTurnStart,+ msSinceLastEvent: turnClock.msSinceLastEvent,+ fallbackLabel: FALLBACK_ACTIVITY_LABEL,+ });+const emptyPrompts = ["What does this page do?",...(ctx.formMeta ? ["Fill this form in for me: "] : []),@@ -381,8 +399,13 @@ export default function AskOEPanel() {{streaming && (<Messagerole="assistant"- content={streamingContent || activityLabel || "…"}+ content={streamingContent || status.label || activityLabel || "…"}isStreaming+ status={+ streamingContent && status.show ? (+ <TurnStatusRow status={status} committeePhase={null} />+ ) : undefined+ }/>)}diff --git a/packages/ui/src/lib/turnStatus.ts b/packages/ui/src/lib/turnStatus.tsnew file mode 100644index 00000000..7ae882f2--- /dev/null+++ b/packages/ui/src/lib/turnStatus.ts@@ -0,0 +1,73 @@+// What the chat shows while a turn is running, so that a long turn never+// looks like a frozen cursor. The stream only sends an event when a tool round+// starts (`activity` + `thinking`) and while text is coming in. Between those,+// a specialist fan-out, a workflow or the model thinking can run for minutes+// with no bytes at all. This works out the status line from what has arrived+// so far and how long ago it arrived.++// Text that stops coming in for this long is treated as the Executive working+// on something, not a pause between tokens.+export const STALL_MS = 4000;+// The elapsed-time counter appears only once a turn has taken this long, so a+// quick reply isn't cluttered with "· 1s".+export const SHOW_ELAPSED_AFTER_MS = 5000;+// Before the first event, the dots show alone for this long, then get the+// fallback label.+export const LABEL_WAIT_AFTER_MS = 3000;++export interface TurnStatusInput {+ isLoading: boolean;+ // Whether any reply text has streamed yet.+ hasText: boolean;+ // A tool round has started (`thinking`) and no text has come in since.+ isConsulting: boolean;+ activityLabel: string | null;+ // Committee review is running; its own phase indicator takes over.+ inCommittee: boolean;+ msSinceTurnStart: number;+ msSinceLastEvent: number;+ // The label to show when work is going on but nothing has named it.+ fallbackLabel: string;+}++export interface TurnStatus {+ show: boolean;+ // null means the dots show without a label.+ label: string | null;+ // e.g. "42s". null until the turn has run SHOW_ELAPSED_AFTER_MS.+ elapsed: string | null;+}++const HIDDEN: TurnStatus = { show: false, label: null, elapsed: null };++export function turnStatus(input: TurnStatusInput): TurnStatus {+ if (!input.isLoading) return HIDDEN;+ const elapsed =+ input.msSinceTurnStart >= SHOW_ELAPSED_AFTER_MS+ ? formatElapsed(input.msSinceTurnStart)+ : null;++ if (input.inCommittee) return { show: true, label: null, elapsed };+ if (input.isConsulting) {+ return { show: true, label: input.activityLabel ?? input.fallbackLabel, elapsed };+ }+ if (!input.hasText) {+ const label =+ input.msSinceTurnStart >= LABEL_WAIT_AFTER_MS ? input.fallbackLabel : null;+ return { show: true, label, elapsed };+ }+ // Text is on screen: stay out of the way while it flows, speak up once it+ // stalls.+ if (input.msSinceLastEvent >= STALL_MS) {+ return { show: true, label: input.fallbackLabel, elapsed };+ }+ return HIDDEN;+}++export function formatElapsed(ms: number): string {+ const total = Math.max(0, Math.floor(ms / 1000));+ if (total < 60) return `${total}s`;+ const m = Math.floor(total / 60);+ const s = total % 60;+ return `${m}m ${String(s).padStart(2, "0")}s`;+}