Files
nanobot/webui/src/components/thread/ThreadShell.tsx
T

2154 lines
79 KiB
TypeScript
Raw Normal View History

2026-05-06 15:54:15 +00:00
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { PointerEvent as ReactPointerEvent, ReactNode } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext";
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
import { PreviewPane } from "@/components/PreviewPane";
2026-09-23 14:03:37 +08:00
import { FileActionsProvider } from "@/components/FileActions";
import { WebPreviewContext } from "@/components/WebLink";
import { WebPreviewPanel } from "@/components/WebPreviewPanel";
import { parseWebLink } from "@/lib/web-preview";
import { createFilePreviewResource } from "@/lib/file-preview-resource";
2026-08-18 18:28:19 +08:00
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
import { PromptNavigator } from "@/components/thread/PromptNavigator";
import { usePromptHistory } from "@/hooks/usePromptHistory";
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
import { RecoveryNotice } from "@/components/thread/RecoveryNotice";
import { SubagentTasksProvider } from "@/components/thread/SubagentTasks";
import { SessionInfoPopover } from "@/components/thread/SessionInfoPopover";
import type { ComposerDraftStore } from "@/lib/composer-draft";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
import type {
ComposerContextUsage,
ComposerRoundUsage,
} from "@/components/thread/ComposerUsagePopover";
import {
modelPresetOptionsFromSettings,
toModelBadgeInfo,
} from "@/components/thread/model-preset";
import { ThreadHeader } from "@/components/thread/ThreadHeader";
import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice";
import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport";
import { useNanobotStream, type SendAttachment, type SendOptions } from "@/hooks/useNanobotStream";
import { useSessionHistory } from "@/hooks/useSessions";
import { useFilePreviewState, type FilePreviewState, type FilePreviewStore } from "@/hooks/useFilePreviewState";
import {
ApiError,
fetchFilePreviewAvailability,
fetchFilePreview,
2026-09-23 14:03:37 +08:00
fetchFileReferenceMetadata,
fetchInstalledCliApps,
fetchMcpPresets,
fetchSettings,
fetchWorkspaces,
fetchWorkspaceDirectories,
2026-09-12 04:37:37 +08:00
fetchWebuiThreadTraceDetail,
listSlashCommands,
} from "@/lib/api";
import {
CLI_APPS_CHANGED_EVENT,
installedCliAppsFromPayload,
isCliAppsPayload,
} from "@/lib/cli-app-events";
import {
MCP_PRESETS_CHANGED_EVENT,
installedMcpPresetsFromPayload,
isMcpPresetsPayload,
} from "@/lib/mcp-preset-events";
import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client";
import type {
ChatSummary,
FilePreviewPayload,
2026-09-23 14:03:37 +08:00
FileReferenceMetadata,
RoundUsage,
SettingsPayload,
SlashCommand,
2026-07-01 15:52:34 +08:00
SkillSummary,
UIMessage,
WorkspaceScopePayload,
WorkspacesPayload,
ProjectDirectory,
} from "@/lib/types";
import { projectThreadEvents } from "@/lib/thread-event-projection";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import { canonicalRunSnapshot, completedAssistantTurnIds } from "@/lib/canonical-run-snapshot";
import { providerDisplayLabel } from "@/lib/provider-brand";
import { cn } from "@/lib/utils";
import { useClient } from "@/providers/ClientProvider";
type MessageShape = Pick<UIMessage, "role" | "kind" | "content" | "isStreaming" | "turnId">;
interface PendingCanonicalHydrate {
source: "initial" | "refresh";
historyLineage: number;
historyVersion: number;
runGeneration: number;
uiBaseline: MessageShape[];
uiLineage: number | null;
uiRevision: number;
}
interface PendingHistoryLineageCommit {
lineage: number;
messages: UIMessage[];
}
interface PendingCanonicalCommit {
canonicalSnapshot: CanonicalRunSnapshot;
completedTurnIds: string[];
expectedUiRevision: number;
historyLineage: number;
historyVersion: number;
hydrate: PendingCanonicalHydrate;
messages: UIMessage[];
previousMessages: UIMessage[];
}
function sameMessageShape(a: MessageShape, b: MessageShape): boolean {
2026-05-24 20:56:07 +08:00
return (
a.role === b.role
&& (a.kind ?? "") === (b.kind ?? "")
&& a.content === b.content
&& (!a.turnId || !b.turnId || a.turnId === b.turnId)
);
}
2026-08-22 19:41:37 +08:00
function latestComposerContextUsage(messages: UIMessage[]): ComposerContextUsage | null {
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (message.kind === "compaction" && message.compaction?.phase === "succeeded") {
return null;
}
2026-08-22 19:41:37 +08:00
const contextTokens = message.usage?.context_tokens;
if (
message.role !== "assistant"
|| message.kind === "trace"
|| message.isStreaming
|| typeof contextTokens !== "number"
|| !Number.isFinite(contextTokens)
|| contextTokens < 0
) {
continue;
}
return {
contextTokens,
...(typeof message.contextWindowTokens === "number"
? { contextWindowTokens: message.contextWindowTokens }
: {}),
};
}
return null;
}
function recentComposerRoundUsage(messages: UIMessage[]): ComposerRoundUsage[] {
const recent: ComposerRoundUsage[] = [];
const seenTurns = new Set<string>();
for (let index = messages.length - 1; index >= 0 && recent.length < 8; index -= 1) {
const message = messages[index];
const turnKey = message.turnId || message.id;
if (
message.role !== "assistant"
|| message.kind === "trace"
|| message.isStreaming
|| seenTurns.has(turnKey)
) {
continue;
}
seenTurns.add(turnKey);
const rounds: RoundUsage[] = message.roundUsages ?? [];
for (let roundIndex = rounds.length - 1; roundIndex >= 0; roundIndex -= 1) {
const round = rounds[roundIndex];
const inputTokens = round.prompt_tokens;
if (
recent.length >= 8
|| typeof inputTokens !== "number"
|| !Number.isFinite(inputTokens)
|| inputTokens <= 0
) {
continue;
}
const outputTokens = round.completion_tokens;
const cachedTokens = round.cached_tokens;
const estimatedTokens = round.estimated_tokens;
const generationMs = round.generation_ms;
recent.push({
id: `${turnKey}:${roundIndex}`,
timestamp: message.completedAt ?? message.createdAt,
inputTokens,
...(typeof outputTokens === "number" && Number.isFinite(outputTokens)
? { outputTokens }
: {}),
...(typeof cachedTokens === "number" && Number.isFinite(cachedTokens)
? { cachedTokens }
: {}),
...(typeof estimatedTokens === "number" && Number.isFinite(estimatedTokens)
? { estimatedTokens }
: {}),
...(typeof generationMs === "number" && Number.isFinite(generationMs)
? { generationMs }
: {}),
});
}
}
return recent.reverse();
}
function snapshotPreservesMessage(
current: MessageShape,
candidate: MessageShape,
allowCompletedTurnReplacement: boolean,
): boolean {
if (sameMessageShape(current, candidate)) return true;
if (
allowCompletedTurnReplacement
&& current.role === "assistant"
&& candidate.role === current.role
&& (candidate.kind ?? "") === (current.kind ?? "")
&& !!current.turnId
&& candidate.turnId === current.turnId
) {
return true;
}
return (
current.role === "assistant"
&& current.isStreaming === true
&& candidate.role === current.role
&& (candidate.kind ?? "") === (current.kind ?? "")
&& (!current.turnId || !candidate.turnId || candidate.turnId === current.turnId)
&& candidate.content.startsWith(current.content)
2026-05-24 20:56:07 +08:00
);
}
function durableMessageShape(message: UIMessage): MessageShape | null {
if (message.kind === "trace") return null;
if (message.role !== "user" && message.role !== "assistant") return null;
if (message.role === "assistant" && !message.content.trim() && !message.media?.length) {
return null;
}
return {
role: message.role,
kind: message.kind,
content: message.content,
isStreaming: message.isStreaming,
turnId: message.turnId,
};
}
function durableMessageShapes(messages: UIMessage[]): MessageShape[] {
return messages
.map(durableMessageShape)
.filter((message): message is MessageShape => message !== null);
}
function preservesMessageShapes(
expected: MessageShape[],
candidates: MessageShape[],
allowCompletedTurnReplacement: boolean,
): boolean {
let cursor = 0;
let previousCandidate: MessageShape | null = null;
for (const message of expected) {
if (
allowCompletedTurnReplacement
&& previousCandidate?.role === "assistant"
&& message.role === "assistant"
&& !!message.turnId
&& message.turnId === previousCandidate.turnId
) {
// A delayed websocket delta can briefly create a second bubble after an
// HTTP completion snapshot. The completed replay is authoritative for
// that turn, so both local fragments may map to its single assistant row.
continue;
}
let found = false;
while (cursor < candidates.length) {
const candidate = candidates[cursor];
cursor += 1;
if (snapshotPreservesMessage(message, candidate, allowCompletedTurnReplacement)) {
found = true;
previousCandidate = candidate;
break;
}
}
if (!found) return false;
}
return true;
}
function preservesDurableMessages(
current: UIMessage[],
snapshot: UIMessage[],
allowCompletedTurnReplacement = false,
): boolean {
// Canonical history refreshes can race with live websocket messages after fork/send.
// Never accept a refreshed snapshot that drops a user/assistant message already shown.
const expected = durableMessageShapes(current);
if (expected.length === 0) return true;
return preservesMessageShapes(
expected,
durableMessageShapes(snapshot),
allowCompletedTurnReplacement,
);
}
function resetDropsPostRequestDurableTail(
baseline: MessageShape[],
current: UIMessage[],
snapshot: UIMessage[],
): boolean {
const currentDurable = durableMessageShapes(current);
let stablePrefixLength = 0;
while (
stablePrefixLength < baseline.length
&& stablePrefixLength < currentDurable.length
&& sameMessageShape(baseline[stablePrefixLength], currentDurable[stablePrefixLength])
) {
stablePrefixLength += 1;
}
const postRequestTail = currentDurable.slice(stablePrefixLength);
if (postRequestTail.length === 0) return false;
return !preservesMessageShapes(
postRequestTail,
durableMessageShapes(snapshot),
true,
);
}
function isStaleThreadSnapshot(
current: UIMessage[],
snapshot: UIMessage[],
allowCompletedTurnReplacement = false,
): boolean {
if (current.length === 0) return false;
2026-05-24 20:56:07 +08:00
if (snapshot.length === 0) return true;
if (!preservesDurableMessages(current, snapshot, allowCompletedTurnReplacement)) return true;
if (snapshot.length >= current.length) return false;
if (allowCompletedTurnReplacement) return false;
2026-05-24 20:56:07 +08:00
return snapshot.every((message, index) => sameMessageShape(current[index], message));
}
2026-08-13 16:25:37 +08:00
function latestActiveTurnId(messages: UIMessage[], runStartedAt: number | null): string | null {
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (message.isStreaming && message.turnId) return message.turnId;
}
2026-08-13 16:25:37 +08:00
if (runStartedAt === null) return null;
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (
2026-08-13 16:25:37 +08:00
message.role !== "user"
&& message.turnId
2026-08-13 16:25:37 +08:00
&& message.createdAt >= runStartedAt * 1000
) return message.turnId;
}
return null;
}
function hasInlineDeliveryError(
messages: UIMessage[],
error: StreamError | null,
): boolean {
if (!error?.turnId) return false;
return messages.some((message) => (
message.role === "user"
&& message.turnId === error.turnId
&& message.deliveryStatus === "failed"
&& message.deliveryErrorKind === error.kind
));
}
function replaceCanonicalCompletedTurns(
current: UIMessage[],
canonical: UIMessage[],
completedTurnIds: readonly string[],
): UIMessage[] {
const completed = new Set(completedTurnIds);
const represented = new Set(canonical.flatMap((message) => (
message.turnId && completed.has(message.turnId) ? [message.turnId] : []
)));
if (!current.some((message) => message.turnId && represented.has(message.turnId))) {
return current;
}
const retained: UIMessage[] = [];
const originalPositions = new Map<string, number>();
for (const message of current) {
if (message.turnId && represented.has(message.turnId)) {
if (!originalPositions.has(message.turnId)) {
originalPositions.set(message.turnId, retained.length);
}
} else {
retained.push(message);
}
}
// Supplemental inputs may have their own turn identity between two answer
// segments. Match those retained rows as anchors so completed rows keep the
// canonical chronology instead of being grouped at the first turn row.
type AnchorQueue = { indices: number[]; offset: number };
type ShapeAnchors = {
all: AnchorQueue;
byTurnId: Map<string | undefined, AnchorQueue>;
};
const anchorIndex = new Map<string, Map<string, ShapeAnchors>>();
for (let index = 0; index < retained.length; index += 1) {
const message = retained[index];
const shape = JSON.stringify([message.role, message.kind ?? ""]);
let byContent = anchorIndex.get(shape);
if (!byContent) {
byContent = new Map();
anchorIndex.set(shape, byContent);
}
let positions = byContent.get(message.content);
if (!positions) {
positions = {
all: { indices: [], offset: 0 },
byTurnId: new Map(),
};
byContent.set(message.content, positions);
}
positions.all.indices.push(index);
const turnId = message.turnId || undefined;
const queue = positions.byTurnId.get(turnId) ?? { indices: [], offset: 0 };
queue.indices.push(index);
positions.byTurnId.set(turnId, queue);
}
let cursor = 0;
let fallbackBoundary = 0;
const firstAnchor = (queue: AnchorQueue | undefined, minimumIndex: number): number => {
if (!queue) return retained.length;
while (queue.offset < queue.indices.length && queue.indices[queue.offset] < minimumIndex) {
queue.offset += 1;
}
return queue.indices[queue.offset] ?? retained.length;
};
const anchors = canonical.map((message) => {
if (message.turnId && represented.has(message.turnId)) {
// Keep anonymous matches after this turn's retained pagination prefix.
fallbackBoundary = Math.max(fallbackBoundary, originalPositions.get(message.turnId) ?? 0);
return -1;
}
const positions = anchorIndex
.get(JSON.stringify([message.role, message.kind ?? ""]))
?.get(message.content);
const exactIndex = message.turnId
? firstAnchor(positions?.byTurnId.get(message.turnId), cursor)
: retained.length;
const index = exactIndex < retained.length
? exactIndex
: firstAnchor(
message.turnId ? positions?.byTurnId.get(undefined) : positions?.all,
Math.max(cursor, fallbackBoundary),
);
if (index === retained.length) return -1;
cursor = index + 1;
return index;
});
const nextAnchors = new Array<number | undefined>(anchors.length);
let nextAnchor: number | undefined;
for (let index = anchors.length - 1; index >= 0; index -= 1) {
nextAnchors[index] = nextAnchor;
if (anchors[index] >= 0) nextAnchor = anchors[index];
}
const insertions = new Map<number, UIMessage[]>();
let precedingAnchor = 0;
let previousInsertionPosition = 0;
for (let index = 0; index < canonical.length; index += 1) {
if (anchors[index] >= 0) precedingAnchor = anchors[index] + 1;
const message = canonical[index];
if (!message.turnId || !represented.has(message.turnId)) continue;
const position = Math.max(
previousInsertionPosition,
nextAnchors[index] ?? Math.max(
precedingAnchor,
originalPositions.get(message.turnId) ?? precedingAnchor,
),
);
previousInsertionPosition = position;
const rows = insertions.get(position) ?? [];
rows.push(message);
insertions.set(position, rows);
}
return retained.flatMap((message, index) => [
...insertions.get(index) ?? [],
message,
]).concat(insertions.get(retained.length) ?? []);
}
const FILE_PREVIEW_DEFAULT_WIDTH = 544;
const FILE_PREVIEW_MIN_WIDTH = 360;
const FILE_PREVIEW_MAX_WIDTH = 860;
const FILE_PREVIEW_MIN_MAIN_WIDTH = 420;
const FILE_PREVIEW_CLOSE_ANIMATION_MS = 320;
type FilePreviewAvailabilityCacheEntry = {
available?: boolean;
promise: Promise<boolean>;
revision: number;
};
function clampFilePreviewWidth(width: number, maxWidth: number): number {
return Math.min(Math.max(width, FILE_PREVIEW_MIN_WIDTH), maxWidth);
}
function maxFilePreviewWidth(containerWidth: number): number {
return Math.min(
containerWidth > 0 ? containerWidth : FILE_PREVIEW_MIN_WIDTH,
Math.max(
FILE_PREVIEW_MIN_WIDTH,
Math.min(FILE_PREVIEW_MAX_WIDTH, containerWidth - FILE_PREVIEW_MIN_MAIN_WIDTH),
),
);
}
interface ThreadShellProps {
session: ChatSummary | null;
2026-08-02 22:04:59 +08:00
sessions?: ChatSummary[];
title: string;
2026-08-05 19:24:41 +08:00
temporary?: boolean;
2026-08-06 18:29:04 +08:00
temporaryChatIds?: readonly string[];
messageCache?: ThreadMessageCache;
filePreviewStore?: FilePreviewStore;
draftStore?: ComposerDraftStore;
2026-08-06 18:29:04 +08:00
temporaryChatEnabled?: boolean;
onTemporaryChatEnabledChange?: (enabled: boolean) => void;
onToggleSidebar: () => void;
2026-05-06 14:15:36 +00:00
onGoHome?: () => void;
onNewChat?: () => void;
2026-08-06 18:29:04 +08:00
onCreateChat?: (
workspaceScope?: WorkspaceScopePayload | null,
initialMessage?: string,
modelPreset?: string | null,
2026-08-06 18:29:04 +08:00
) => Promise<string | null>;
pendingFirstMessage?: PendingFirstMessage & { id: string; chatId: string } | null;
onPendingFirstMessageConsumed?: (id: string) => void;
onForkChat?: (sourceChatId: string, beforeUserIndex: number) => Promise<string | null>;
2026-05-06 14:15:36 +00:00
onTurnEnd?: () => void;
theme?: "light" | "dark";
onToggleTheme?: () => void;
hideSidebarToggleForHostChrome?: boolean;
hideSidebarToggle?: boolean;
2026-05-31 17:00:42 +08:00
hideThemeButton?: boolean;
hideHeaderTitle?: boolean;
2026-08-25 01:55:58 +08:00
inlineHandle?: boolean;
hideHeader?: boolean;
headerActions?: ReactNode;
headerPortalTarget?: HTMLElement | null;
headerActive?: boolean;
composerPortalTarget?: HTMLElement | null;
composerActive?: boolean;
composerInputAriaLabel?: string;
emptyComposerVariant?: "hero" | "thread";
workspaceScope?: WorkspaceScopePayload | null;
workspaceDefaultScope?: WorkspaceScopePayload | null;
workspaceControls?: WorkspacesPayload["controls"] | null;
workspaceScopeDisabled?: boolean;
workspaceError?: string | null;
onWorkspaceScopeChange?: (scope: WorkspaceScopePayload) => void;
settingsSnapshot?: SettingsPayload | null;
settingsLoading?: boolean;
onOpenModelSettings?: () => void;
2026-07-01 15:52:34 +08:00
skills?: SkillSummary[];
}
const HERO_GREETING_KEYS = [
"thread.empty.greetings.workOn",
"thread.empty.greetings.start",
"thread.empty.greetings.build",
"thread.empty.greetings.tackle",
2026-05-06 14:15:36 +00:00
] as const;
2026-07-23 18:18:34 +08:00
function HeroGreeting({ text }: { text: string }) {
const containerRef = useRef<HTMLDivElement>(null);
const headingRef = useRef<HTMLHeadingElement>(null);
useLayoutEffect(() => {
const container = containerRef.current;
const heading = headingRef.current;
if (!container || !heading) return;
const fitToWidth = () => {
heading.style.removeProperty("font-size");
const availableWidth = container.clientWidth;
if (availableWidth <= 0) return;
const naturalWidth = heading.scrollWidth;
const maximumFontSize = Number.parseFloat(window.getComputedStyle(heading).fontSize);
if (
naturalWidth <= availableWidth
|| !Number.isFinite(maximumFontSize)
|| maximumFontSize <= 0
) {
return;
}
const fittedFontSize = Math.max(
12,
Math.floor(maximumFontSize * ((availableWidth - 2) / naturalWidth) * 100) / 100,
);
heading.style.fontSize = `${fittedFontSize}px`;
};
fitToWidth();
let lastObservedWidth = container.clientWidth;
const resizeObserver = typeof ResizeObserver === "undefined"
? null
: new ResizeObserver(([entry]) => {
const nextWidth = entry?.contentRect.width ?? container.clientWidth;
if (nextWidth === lastObservedWidth) return;
lastObservedWidth = nextWidth;
fitToWidth();
});
resizeObserver?.observe(container);
window.addEventListener("resize", fitToWidth);
let cancelled = false;
void document.fonts?.ready.then(() => {
if (!cancelled) fitToWidth();
});
return () => {
cancelled = true;
resizeObserver?.disconnect();
window.removeEventListener("resize", fitToWidth);
};
}, [text]);
return (
<div ref={containerRef} className="min-w-0 w-full max-w-[44rem]">
<h1
ref={headingRef}
data-testid="hero-greeting"
2026-08-06 18:29:04 +08:00
className="select-none whitespace-nowrap text-[34px] font-normal leading-[1.08] tracking-normal text-foreground sm:text-[48px] sm:leading-tight"
2026-07-23 18:18:34 +08:00
>
{text}
</h1>
</div>
);
}
function randomHeroGreetingKey(): (typeof HERO_GREETING_KEYS)[number] {
const index = Math.floor(Math.random() * HERO_GREETING_KEYS.length);
return HERO_GREETING_KEYS[index] ?? HERO_GREETING_KEYS[0];
}
interface PendingFirstMessage {
finish?: (accepted: boolean) => void;
content: string;
images?: SendAttachment[];
options?: SendOptions;
}
interface InstalledSettingItemsOptions<Payload, Item> {
requestCount: number;
getToken: () => string;
eventName: string;
fetchPayload: (token: string) => Promise<Payload>;
isPayload: (value: unknown) => value is Payload;
selectItems: (payload: Payload) => Item[];
}
function useInstalledSettingItems<Payload, Item>({
requestCount,
getToken,
eventName,
fetchPayload,
isPayload,
selectItems,
}: InstalledSettingItemsOptions<Payload, Item>): Item[] {
const [items, setItems] = useState<Item[]>([]);
const loadedRef = useRef(false);
const pendingRef = useRef<Promise<Payload> | null>(null);
useEffect(() => {
let cancelled = false;
let refreshQueued = false;
let refreshAfterFlight = false;
let refreshing = false;
let payloadVersion = 0;
const refresh = async (): Promise<void> => {
if (refreshing) return;
refreshing = true;
const version = payloadVersion;
const pending = pendingRef.current ?? fetchPayload(getToken());
pendingRef.current = pending;
try {
const payload = await pending;
if (!cancelled && version === payloadVersion) {
loadedRef.current = true;
setItems(selectItems(payload));
}
} catch {
// Keep the last successful catalog during transient refresh failures.
} finally {
if (pendingRef.current === pending) pendingRef.current = null;
refreshing = false;
if (refreshAfterFlight && !cancelled) {
refreshAfterFlight = false;
void refresh();
}
}
};
const queueRefresh = () => {
if (!requestCount || document.visibilityState === "hidden" || refreshQueued) return;
refreshQueued = true;
queueMicrotask(() => {
refreshQueued = false;
if (!cancelled) void refresh();
});
};
if (requestCount && !loadedRef.current) void refresh();
const refreshOnChanged = (event: Event) => {
const payload = (event as CustomEvent<unknown>).detail;
if (isPayload(payload)) {
payloadVersion += 1;
loadedRef.current = true;
setItems(selectItems(payload));
return;
}
if (refreshing) {
refreshAfterFlight = true;
return;
}
queueRefresh();
};
window.addEventListener(eventName, refreshOnChanged);
return () => {
cancelled = true;
window.removeEventListener(eventName, refreshOnChanged);
};
}, [requestCount, eventName, fetchPayload, getToken, isPayload, selectItems]);
return items;
}
export function ThreadShell({
session,
2026-08-02 22:04:59 +08:00
sessions = [],
title,
2026-08-05 19:24:41 +08:00
temporary = false,
2026-08-06 18:29:04 +08:00
temporaryChatIds = [],
messageCache,
filePreviewStore,
draftStore,
2026-08-06 18:29:04 +08:00
temporaryChatEnabled = false,
onTemporaryChatEnabledChange,
onToggleSidebar,
2026-05-06 14:15:36 +00:00
onCreateChat,
pendingFirstMessage = null,
onPendingFirstMessageConsumed,
onForkChat,
2026-05-06 14:15:36 +00:00
onTurnEnd,
theme = "light",
onToggleTheme = () => {},
hideSidebarToggleForHostChrome = false,
hideSidebarToggle = false,
2026-05-31 17:00:42 +08:00
hideThemeButton = false,
hideHeaderTitle = false,
2026-08-25 01:55:58 +08:00
inlineHandle = false,
hideHeader = false,
headerActions,
headerPortalTarget,
headerActive = true,
composerPortalTarget,
composerActive = true,
composerInputAriaLabel,
emptyComposerVariant = "hero",
workspaceScope = null,
workspaceDefaultScope = null,
workspaceControls = null,
workspaceScopeDisabled = false,
workspaceError = null,
onWorkspaceScopeChange,
settingsSnapshot = null,
settingsLoading = false,
onOpenModelSettings,
2026-07-01 15:52:34 +08:00
skills = [],
}: ThreadShellProps) {
const { t } = useTranslation();
const chatId = session?.chatId ?? null;
2026-08-05 19:24:41 +08:00
const historyKey = temporary ? null : session?.key ?? null;
const previewSessionKey = session?.key ?? null;
2026-08-18 18:28:19 +08:00
const mentionSessions = useMemo(
() => sessions.filter((candidate) => candidate.key !== historyKey),
[historyKey, sessions],
2026-08-02 22:04:59 +08:00
);
const {
messages: historical,
loading,
error: historyError,
2026-06-10 18:02:27 +08:00
loadingOlder,
olderError,
2026-06-10 18:02:27 +08:00
loadOlder,
hasMoreBefore,
userMessageOffset,
hasPendingToolCalls,
completedTurnIds,
completionIdsProvided,
continuity: historyContinuity,
lineage: historyLineage,
activeTurnId: historyActiveTurnId,
refresh: refreshHistory,
version: historyVersion,
2026-06-10 02:07:47 +08:00
forkBoundaryMessageCount,
} = useSessionHistory(historyKey);
const { client, getToken, ingressLimits, modelName, token, webuiCapabilities } = useClient();
const favoriteWorkspaceProject = useCallback(
async (path: string, pinned: boolean) => {
const response = await client.requestMutation<{ favorite_projects: ProjectDirectory[] }>("workspace.favorite", { path, pinned });
return response.favorite_projects;
},
[client],
);
const resolveWorkspaceProject = useCallback(
(path: string) => client.requestMutation<ProjectDirectory>("workspace.resolve_project", { path }),
[client],
);
const loadWorkspaceProjects = useCallback(() => fetchWorkspaces(getToken()), [getToken]);
const browseWorkspaceDirectories = useCallback(
(path: string, query: string, showHidden: boolean, allowPartial = false) =>
fetchWorkspaceDirectories(getToken(), path, query, showHidden, allowPartial),
[getToken],
);
const [booting, setBooting] = useState(false);
2026-05-06 15:54:15 +00:00
const [slashCommands, setSlashCommands] = useState<SlashCommand[]>([]);
const [mentionCatalogRequestCount, setMentionCatalogRequestCount] = useState(0);
const requestMentionCatalogs = useCallback(() => setMentionCatalogRequestCount((count) => count + 1), []);
const cliApps = useInstalledSettingItems({
requestCount: mentionCatalogRequestCount,
getToken,
eventName: CLI_APPS_CHANGED_EVENT,
fetchPayload: fetchInstalledCliApps,
isPayload: isCliAppsPayload,
selectItems: installedCliAppsFromPayload,
});
const mcpPresets = useInstalledSettingItems({
requestCount: mentionCatalogRequestCount,
getToken,
eventName: MCP_PRESETS_CHANGED_EVENT,
fetchPayload: fetchMcpPresets,
isPayload: isMcpPresetsPayload,
selectItems: installedMcpPresetsFromPayload,
});
const [settings, setSettings] = useState<SettingsPayload | null>(settingsSnapshot);
const [modelFallback, setModelFallback] = useState<{
chatId: string;
model: string;
reauthProvider?: string;
dismissed: boolean;
} | null>(null);
const [heroGreetingKey, setHeroGreetingKey] = useState(randomHeroGreetingKey);
const [submittedViewportTurnId, setSubmittedViewportTurnId] = useState<string | null>(null);
const { state: previewState, openFile, resolveFile, openWeb, selectTab, closeTab, close: closePreview, setWidth: setFilePreviewWidth } =
useFilePreviewState(previewSessionKey, filePreviewStore);
const [closingPreview, setClosingPreview] = useState<{ key: string; state: FilePreviewState } | null>(null);
const filePreviewClosing = closingPreview?.key === previewSessionKey;
const visiblePreview = filePreviewClosing ? closingPreview.state : previewState;
const activePreview = visiblePreview.tabs.find((tab) => tab.id === visiblePreview.activeId);
const previewOpen = Boolean(activePreview);
const [filePreviewMaxWidth, setFilePreviewMaxWidth] = useState(FILE_PREVIEW_MAX_WIDTH);
const filePreviewWidth = clampFilePreviewWidth(previewState.width, filePreviewMaxWidth);
const draftKey = session?.key ?? (temporaryChatEnabled ? "new:temporary" : "new:chat");
const persistDraft = session ? !temporary : !temporaryChatEnabled;
const [quote, setQuote] = useState<{ key: string; text: string | null } | null>(null);
const quotedContext = quote?.key === draftKey
? quote.text
: draftStore?.get(draftKey, persistDraft)?.quotedContext ?? null;
const setQuotedContext = useCallback((text: string | null) => {
setQuote({ key: draftKey, text });
}, [draftKey]);
const [composerFocusSignal, setComposerFocusSignal] = useState(0);
const shellRef = useRef<HTMLElement | null>(null);
const [conversationElement, setConversationElement] = useState<HTMLDivElement | null>(null);
2026-08-06 18:29:04 +08:00
const composerSurfaceRef = useRef<HTMLDivElement | null>(null);
const filePreviewWidthRef = useRef(FILE_PREVIEW_DEFAULT_WIDTH);
const filePreviewCloseTimerRef = useRef<number | null>(null);
const filePreviewResizeCleanupRef = useRef<(() => void) | null>(null);
const pendingFirstRef = useRef<PendingFirstMessage | null>(null);
const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState<string | null>(null);
const consumedPendingFirstMessageIdRef = useRef<string | null>(null);
const viewportRef = useRef<ThreadViewportHandle | null>(null);
const activeViewportTurnByChatIdRef = useRef<Map<string, string>>(new Map());
const knownTemporaryChatIdsRef = useRef(new Set<string>());
const localMessageCacheRef = useRef(new ThreadMessageCache(
(key) => knownTemporaryChatIdsRef.current.has(key),
));
const messageCacheRef = useRef(messageCache ?? localMessageCacheRef.current);
messageCacheRef.current = messageCache ?? localMessageCacheRef.current;
/** Last chatId we associated with the in-memory thread (for cache-on-switch). */
const prevChatIdForCacheRef = useRef<string | null>(null);
/** Skip one message-cache write right after chatId changes (messages may not match yet). */
const skipLayoutCacheRef = useRef(false);
const pendingCanonicalHydrateRef = useRef<Map<string, PendingCanonicalHydrate>>(new Map());
const pendingCanonicalCommitRef = useRef<Map<string, PendingCanonicalCommit>>(new Map());
const pendingHistoryLineageCommitRef = useRef<Map<string, PendingHistoryLineageCommit>>(
new Map(),
);
const completedCanonicalHydrateVersionRef = useRef<Map<string, number>>(new Map());
const committedHistoryLineageRef = useRef<Map<string, number>>(new Map());
const sessionKeyByChatIdRef = useRef<Map<string, string>>(new Map());
2026-09-12 04:37:37 +08:00
const traceDetailRequestsRef = useRef<Map<string, Promise<void>>>(new Map());
const activeHistoryKeyRef = useRef(historyKey);
activeHistoryKeyRef.current = historyKey;
const currentUiMessagesRef = useRef<UIMessage[] | null>(null);
const uiRevisionRef = useRef(0);
2026-08-06 18:29:04 +08:00
const showTemporaryChatControl =
!hideHeader && !session && !loading && !!onTemporaryChatEnabledChange;
const initial = useMemo(() => {
if (!chatId) return historical;
const cached = messageCacheRef.current.get(chatId);
return cached
? replaceCanonicalCompletedTurns(cached, historical, completedTurnIds)
: historical;
}, [chatId, completedTurnIds, historical]);
const handleTurnEnd = useCallback(() => {
if (chatId) activeViewportTurnByChatIdRef.current.delete(chatId);
setSubmittedViewportTurnId(null);
onTurnEnd?.();
}, [chatId, onTurnEnd]);
const handleStreamDetach = useCallback((snapshot: UIMessage[]) => {
if (chatId) messageCacheRef.current.set(chatId, projectWebuiThreadMessages(snapshot));
}, [chatId]);
const {
messages,
messagesReady,
isStreaming,
runStartedAt,
retryStatus,
goalState,
recoveryState,
continueRecovery,
dismissRecovery,
send,
transcribeAudio,
stop,
reconcileTurnComplete,
setMessages,
streamError,
dismissStreamError,
} = useNanobotStream(
chatId, initial, hasPendingToolCalls, handleTurnEnd, handleStreamDetach, completedTurnIds,
);
const displayMessages = useMemo(() => projectWebuiThreadMessages(messages), [messages]);
const promptNavigation = usePromptHistory(historyKey, historyVersion, displayMessages);
const updateNavigationMessages = promptNavigation.updateMessages;
2026-09-12 04:37:37 +08:00
const loadTraceDetails = useCallback(async (refs: string[]) => {
const requestKey = historyKey;
if (!requestKey) return;
const requests: Promise<void>[] = [];
for (const ref of refs) {
const requestId = `${requestKey}:${ref}`;
const existing = traceDetailRequestsRef.current.get(requestId);
if (existing) {
requests.push(existing);
continue;
}
const request = fetchWebuiThreadTraceDetail(getToken(), requestKey, ref)
.then((detail) => {
if (activeHistoryKeyRef.current !== requestKey) return;
const projected = projectThreadEvents(detail.events);
const hydrate = (current: UIMessage[]) => current.flatMap((message) => {
if (message.traceDetail?.ref !== ref) return [message];
return projected.map((replacement) => ({
...replacement,
activitySegmentId: message.activitySegmentId ?? replacement.activitySegmentId,
}));
});
setMessages(hydrate);
updateNavigationMessages(hydrate);
2026-09-12 04:37:37 +08:00
})
.catch((error: unknown) => {
if (activeHistoryKeyRef.current !== requestKey) return;
throw error;
})
.finally(() => {
traceDetailRequestsRef.current.delete(requestId);
});
traceDetailRequestsRef.current.set(requestId, request);
requests.push(request);
}
await Promise.all(requests);
}, [getToken, historyKey, setMessages, updateNavigationMessages]);
2026-09-12 04:37:37 +08:00
useEffect(() => () => {
activeHistoryKeyRef.current = null;
}, []);
useLayoutEffect(() => {
if (currentUiMessagesRef.current === messages) return;
currentUiMessagesRef.current = messages;
uiRevisionRef.current += 1;
if (!chatId) return;
const lineageCommit = pendingHistoryLineageCommitRef.current.get(chatId);
if (!lineageCommit) return;
pendingHistoryLineageCommitRef.current.delete(chatId);
if (lineageCommit.messages === messages) {
committedHistoryLineageRef.current.set(chatId, lineageCommit.lineage);
}
}, [chatId, messages]);
useEffect(() => {
if (chatId && historyKey) sessionKeyByChatIdRef.current.set(chatId, historyKey);
}, [chatId, historyKey]);
useEffect(() => {
filePreviewWidthRef.current = filePreviewWidth;
}, [filePreviewWidth]);
useEffect(() => {
filePreviewResizeCleanupRef.current?.();
if (filePreviewCloseTimerRef.current !== null) {
window.clearTimeout(filePreviewCloseTimerRef.current);
filePreviewCloseTimerRef.current = null;
}
setClosingPreview(null);
setSubmittedViewportTurnId(null);
}, [previewSessionKey]);
2026-08-05 19:24:41 +08:00
useEffect(() => {
2026-08-06 18:29:04 +08:00
const retained = new Set(temporaryChatIds);
for (const chatId of retained) knownTemporaryChatIdsRef.current.add(chatId);
for (const cachedChatId of knownTemporaryChatIdsRef.current) {
if (!retained.has(cachedChatId)) {
// Shared caches are retained/pruned by the app, not by individual panes.
if (!messageCache) messageCacheRef.current.delete(cachedChatId);
2026-08-06 18:29:04 +08:00
activeViewportTurnByChatIdRef.current.delete(cachedChatId);
knownTemporaryChatIdsRef.current.delete(cachedChatId);
2026-08-06 18:29:04 +08:00
}
}
}, [messageCache, temporaryChatIds]);
2026-08-05 19:24:41 +08:00
const handleQuoteSelection = useCallback((text: string) => {
setQuotedContext(text);
setComposerFocusSignal((value) => value + 1);
}, [setQuotedContext]);
useEffect(() => {
return () => {
filePreviewResizeCleanupRef.current?.();
if (filePreviewCloseTimerRef.current !== null) {
window.clearTimeout(filePreviewCloseTimerRef.current);
}
};
}, []);
const hasAppMentions = displayMessages.some((message) => message.cliApps?.length || message.mcpPresets?.length);
useEffect(() => {
if (hasAppMentions) requestMentionCatalogs();
}, [hasAppMentions, requestMentionCatalogs]);
2026-08-22 19:41:37 +08:00
const composerContextUsage = useMemo(
() => latestComposerContextUsage(displayMessages),
[displayMessages],
);
const composerRoundUsage = useMemo(
() => recentComposerRoundUsage(displayMessages),
[displayMessages],
);
const currentGoalState = messagesReady ? goalState : undefined;
// Decision states freeze the interrupted turn and hand the next action to
// the recovery notice. ``resuming`` remains active; ``recovered`` is only
// historical metadata and must not suppress a later normal turn.
const recoveryNeedsDecision = recoveryState?.status === "awaiting_user"
|| recoveryState?.status === "failed";
const currentRunStartedAt = messagesReady && !recoveryNeedsDecision ? runStartedAt : null;
const turnActive = messagesReady
&& !recoveryNeedsDecision
&& (isStreaming || currentRunStartedAt !== null);
const restoredViewportTurnId = useMemo(
2026-08-13 16:25:37 +08:00
() => turnActive ? latestActiveTurnId(displayMessages, currentRunStartedAt) : null,
[currentRunStartedAt, displayMessages, turnActive],
);
const rememberedViewportTurnId = chatId
? activeViewportTurnByChatIdRef.current.get(chatId) ?? null
: null;
const canonicalRunTurnId = chatId && messagesReady && turnActive
? client.getRunTurnId(chatId)
: null;
const viewportTurnId = messagesReady && turnActive
2026-08-13 16:25:37 +08:00
? canonicalRunTurnId
?? rememberedViewportTurnId
?? historyActiveTurnId
?? restoredViewportTurnId
: null;
const activeTurnStartedHere =
viewportTurnId !== null && viewportTurnId === submittedViewportTurnId;
useEffect(() => {
if (!chatId || !messagesReady || turnActive) return;
activeViewportTurnByChatIdRef.current.delete(chatId);
setSubmittedViewportTurnId((current) =>
current === rememberedViewportTurnId ? null : current,
);
}, [chatId, messagesReady, rememberedViewportTurnId, turnActive]);
const filePreviewAvailabilityCache = useMemo(
() => new Map<string, FilePreviewAvailabilityCacheEntry>(),
[previewSessionKey],
);
const filePreviewAvailabilityRevision = displayMessages.length;
const resolveFilePreviewAvailability = useCallback((path: string) => {
if (!previewSessionKey) return Promise.resolve(false);
const cached = filePreviewAvailabilityCache.get(path);
if (
cached
&& (cached.available !== false || cached.revision === filePreviewAvailabilityRevision)
) {
return cached.promise;
}
const request = temporary
? client.requestMutation<{ available: boolean }>("temporary_chat.file_preview", {
chat_id: chatId, path, probe: true,
}).then((result) => result.available)
: fetchFilePreviewAvailability(getToken(), previewSessionKey, path);
const pending = request.catch(
(error: unknown) => {
if (error instanceof ApiError) {
if (error.status === 404 && /API route not found/i.test(error.message)) {
return true;
}
if ([400, 403, 404, 413, 415].includes(error.status)) return false;
}
return false;
},
);
const entry: FilePreviewAvailabilityCacheEntry = {
promise: pending,
revision: filePreviewAvailabilityRevision,
};
filePreviewAvailabilityCache.set(path, entry);
void pending.then((available) => {
if (filePreviewAvailabilityCache.get(path) === entry) {
entry.available = available;
}
});
return pending;
}, [
filePreviewAvailabilityCache,
filePreviewAvailabilityRevision,
getToken,
previewSessionKey,
temporary,
client,
chatId,
]);
const showHeroComposer = displayMessages.length === 0 && !loading;
const composerVariant = showHeroComposer ? emptyComposerVariant : "thread";
const wasShowingHeroComposerRef = useRef(showHeroComposer);
const sessionModelPreset = session?.modelPreset?.trim() || null;
const [localModelPreset, setLocalModelPreset] = useState<string | null>(null);
useEffect(() => {
setLocalModelPreset(null);
}, [session?.key, sessionModelPreset]);
2026-08-22 19:41:37 +08:00
const configuredPresetNames = useMemo(
() => new Set(settings?.model_presets.map((preset) => preset.name) ?? []),
[settings],
);
const activeModelPreset = (
2026-08-22 19:41:37 +08:00
(localModelPreset && (!settings || configuredPresetNames.has(localModelPreset))
? localModelPreset
: null)
|| (sessionModelPreset && (!settings || configuredPresetNames.has(sessionModelPreset))
? sessionModelPreset
: null)
|| settings?.agent.model_preset
|| "default"
);
useEffect(() => {
setModelFallback(null);
if (!chatId) return;
return client.onChat(chatId, (event) => {
if (event.event !== "turn_model_updated") return;
if (event.fallback !== true) {
// The next turn starts with its configured model, not the previous fallback.
setModelFallback(null);
return;
}
const model = event.model_name.trim();
if (!model) return;
const reauthProvider = typeof event.reauth_provider === "string"
? event.reauth_provider.trim() || undefined : undefined;
// A tool loop may report the same fallback repeatedly. Closing the notice
// lasts until the next turn/model change, without changing the actual preset.
setModelFallback((current) => {
if (current?.chatId === chatId && current.model === model) {
// An explicit auth rejection is actionable even after dismissing a
// generic fallback. A circuit-skipped call must not erase that reason.
return reauthProvider && reauthProvider !== current.reauthProvider
? { ...current, reauthProvider, dismissed: false } : current;
}
return { chatId, model, reauthProvider, dismissed: false };
});
});
}, [activeModelPreset, chatId, client]);
const handleModelPresetChange = useCallback((name: string) => {
setLocalModelPreset(name);
if (chatId) {
void client.sendSystemCommand(chatId, `/model ${name}`).catch(() => {});
}
}, [chatId, client]);
const modelPresetOptions = useMemo(
() => modelPresetOptionsFromSettings(settings),
[settings],
);
2026-08-05 19:24:41 +08:00
const availableSlashCommands = useMemo(
() => temporary
? slashCommands.filter(({ command }) => command === "/model" || command === "/stop")
: slashCommands,
[slashCommands, temporary],
);
const modelBadge = useMemo(
() => toModelBadgeInfo(modelName, settings, activeModelPreset),
[activeModelPreset, modelName, settings],
);
const modelBadgeLabel = modelBadge.needsSetup
2026-09-01 20:18:58 +08:00
? t("thread.composer.chooseAI", { defaultValue: "Choose your AI" })
: modelBadge.label;
useEffect(() => {
if (showHeroComposer && !wasShowingHeroComposerRef.current) {
setHeroGreetingKey(randomHeroGreetingKey());
}
wasShowingHeroComposerRef.current = showHeroComposer;
}, [showHeroComposer]);
const withWorkspaceScope = useCallback(
(options?: SendOptions): SendOptions | undefined => {
if (!workspaceScope) return options;
return {
...(options ?? {}),
workspaceScope,
};
},
[workspaceScope],
);
const refreshModelSettings = useCallback(async () => {
try {
setSettings(await fetchSettings(getToken()));
} catch {
if (!settingsSnapshot) setSettings(null);
}
}, [getToken, settingsSnapshot]);
useEffect(() => {
if (settingsSnapshot) {
setSettings(settingsSnapshot);
return;
}
if (!settingsLoading) void refreshModelSettings();
}, [refreshModelSettings, settingsLoading, settingsSnapshot]);
useEffect(() => {
return client.onRuntimeModelUpdate(() => {
void refreshModelSettings();
});
}, [client, refreshModelSettings]);
useEffect(() => {
if (!historyKey || !chatId) return;
pendingCanonicalHydrateRef.current.set(chatId, {
source: "initial",
historyLineage,
historyVersion,
runGeneration: client.getRunGeneration(chatId),
uiBaseline: durableMessageShapes(initial),
uiLineage: committedHistoryLineageRef.current.get(chatId) ?? null,
uiRevision: uiRevisionRef.current,
});
// Capture the request's run generation when entering a conversation, before
// its history response can race with another send or running event.
}, [chatId, client, historyKey]);
const canonicalCompletedTurnIds = useMemo(() => Array.from(new Set([
...completedTurnIds,
...(!completionIdsProvided && !hasPendingToolCalls && historyActiveTurnId === null
? completedAssistantTurnIds(projectWebuiThreadMessages(historical))
: []),
])), [completedTurnIds, completionIdsProvided, hasPendingToolCalls, historical, historyActiveTurnId]);
const lastRunTurnId = chatId ? client.getRunTurnId(chatId) : null;
const completedRunTurnId = chatId && lastRunTurnId && client.isRunCompleted(chatId, lastRunTurnId)
? lastRunTurnId : null;
const queueCompletedTurnIds = useMemo(() => {
const canonical = hasPendingToolCalls ? [] : canonicalCompletedTurnIds;
// Live terminal facts can release the queue before the history refresh finishes.
return completedRunTurnId && !canonical.includes(completedRunTurnId)
? [...canonical, completedRunTurnId] : canonical;
}, [canonicalCompletedTurnIds, completedRunTurnId, hasPendingToolCalls]);
useEffect(() => {
2026-08-05 19:24:41 +08:00
if (!historyKey || !chatId || loading) return;
const pendingCanonicalHydrate = pendingCanonicalHydrateRef.current.get(chatId);
const shouldReconcileRun = (
pendingCanonicalHydrate !== undefined
&& historyVersion > pendingCanonicalHydrate.historyVersion
&& !hasPendingToolCalls
&& (
pendingCanonicalHydrate.source === "refresh"
|| (
(historical.length > 0 || completedTurnIds.length > 0)
&& (isStreaming || runStartedAt !== null || client.hasUnsettledRun(chatId))
)
)
);
const normalizedHistory = projectWebuiThreadMessages(historical);
// Completion is a fact about a turn, even when a newer local turn prevents
// this snapshot from settling the conversation's current run.
client.fenceCanonicalCompletedTurns(chatId, canonicalCompletedTurnIds);
const keepLiveMessages = (current: UIMessage[]) => {
const reconciled = projectWebuiThreadMessages(
replaceCanonicalCompletedTurns(current, normalizedHistory, canonicalCompletedTurnIds),
);
const firstId = reconciled[0]?.id;
const prefixLength = normalizedHistory.findIndex((message) => message.id === firstId);
return prefixLength > 0
? [...normalizedHistory.slice(0, prefixLength), ...reconciled]
: reconciled;
};
if (shouldReconcileRun && pendingCanonicalHydrate) {
const authoritativeReset = (
pendingCanonicalHydrate.uiLineage !== null
&& historyLineage !== pendingCanonicalHydrate.uiLineage
&& (
historyContinuity === "reset"
|| (
pendingCanonicalHydrate.source === "refresh"
&& historyContinuity === "overlap"
&& historyLineage === pendingCanonicalHydrate.historyLineage
)
)
);
const responseUiRevision = uiRevisionRef.current;
const resetDropsRenderedTail = (
authoritativeReset
&& responseUiRevision !== pendingCanonicalHydrate.uiRevision
&& resetDropsPostRequestDurableTail(
pendingCanonicalHydrate.uiBaseline,
messages,
normalizedHistory,
)
);
if (
authoritativeReset
? resetDropsRenderedTail
: isStaleThreadSnapshot(messages, normalizedHistory, true)
) {
setMessages((current) => keepLiveMessages(current));
return;
}
const canonicalSnapshot = canonicalRunSnapshot(
normalizedHistory,
hasPendingToolCalls,
historyActiveTurnId,
completionIdsProvided,
);
if (!client.canReconcileCanonicalCompletion(
chatId,
pendingCanonicalHydrate.runGeneration,
canonicalCompletedTurnIds,
canonicalSnapshot,
)) {
setMessages((current) => keepLiveMessages(current));
return;
}
pendingCanonicalCommitRef.current.set(chatId, {
canonicalSnapshot,
completedTurnIds: canonicalCompletedTurnIds,
expectedUiRevision: responseUiRevision + 1,
historyLineage,
historyVersion,
hydrate: pendingCanonicalHydrate,
messages: normalizedHistory,
previousMessages: keepLiveMessages(messages),
});
setMessages((current) => {
if (current !== messages) return current;
if (
authoritativeReset
? resetDropsRenderedTail
: isStaleThreadSnapshot(current, normalizedHistory, true)
) {
return keepLiveMessages(current);
}
return normalizedHistory;
});
return;
}
const reconciledMessages = keepLiveMessages(messages);
const adoptsNormalizedHistory = (
(!hasPendingToolCalls || messages.length === 0)
&& !isStaleThreadSnapshot(reconciledMessages, normalizedHistory, true)
);
if (adoptsNormalizedHistory) {
pendingHistoryLineageCommitRef.current.set(chatId, {
lineage: historyLineage,
messages: normalizedHistory,
});
}
setMessages((current) => {
const reconciled = keepLiveMessages(current);
return (hasPendingToolCalls && current.length > 0)
|| isStaleThreadSnapshot(reconciled, normalizedHistory, true)
? reconciled
: normalizedHistory;
});
}, [
loading,
chatId,
client,
completedTurnIds,
canonicalCompletedTurnIds,
completionIdsProvided,
historical,
historyVersion,
historyContinuity,
historyLineage,
historyActiveTurnId,
hasPendingToolCalls,
2026-08-05 19:24:41 +08:00
historyKey,
]);
useLayoutEffect(() => {
2026-08-05 19:24:41 +08:00
if (!historyKey || !chatId) return;
const commit = pendingCanonicalCommitRef.current.get(chatId);
if (!commit) return;
if (
commit.historyVersion !== historyVersion
|| commit.historyLineage !== historyLineage
|| commit.messages !== messages
) {
pendingCanonicalCommitRef.current.delete(chatId);
return;
}
if (pendingCanonicalHydrateRef.current.get(chatId) !== commit.hydrate) {
pendingCanonicalCommitRef.current.delete(chatId);
return;
}
if (
uiRevisionRef.current !== commit.expectedUiRevision
|| !client.reconcileCanonicalCompletion(
chatId,
commit.hydrate.runGeneration,
commit.completedTurnIds,
commit.canonicalSnapshot,
)
) {
pendingCanonicalCommitRef.current.delete(chatId);
const fallback = replaceCanonicalCompletedTurns(
messageCacheRef.current.get(chatId) ?? commit.previousMessages,
commit.messages,
commit.completedTurnIds,
);
messageCacheRef.current.set(chatId, fallback);
setMessages((current) => current === commit.messages ? fallback : current);
return;
}
pendingCanonicalHydrateRef.current.delete(chatId);
pendingCanonicalCommitRef.current.delete(chatId);
committedHistoryLineageRef.current.set(chatId, historyLineage);
completedCanonicalHydrateVersionRef.current.set(chatId, historyVersion);
2026-08-05 19:24:41 +08:00
}, [chatId, client, historyKey, historyLineage, historyVersion, messages, setMessages]);
useEffect(() => {
2026-08-05 19:24:41 +08:00
if (!historyKey || !chatId || hasPendingToolCalls) return;
if (completedCanonicalHydrateVersionRef.current.get(chatId) !== historyVersion) return;
completedCanonicalHydrateVersionRef.current.delete(chatId);
reconcileTurnComplete();
2026-08-05 19:24:41 +08:00
}, [chatId, hasPendingToolCalls, historyKey, historyVersion, messages, reconcileTurnComplete]);
const refreshCanonicalHistory = useCallback(() => {
2026-08-05 19:24:41 +08:00
if (!historyKey || !chatId) return;
pendingCanonicalHydrateRef.current.set(chatId, {
source: "refresh",
historyLineage,
historyVersion,
runGeneration: client.getRunGeneration(chatId),
uiBaseline: durableMessageShapes(currentUiMessagesRef.current ?? []),
uiLineage: committedHistoryLineageRef.current.get(chatId) ?? null,
uiRevision: uiRevisionRef.current,
});
refreshHistory();
2026-08-05 19:24:41 +08:00
}, [chatId, client, historyKey, historyLineage, historyVersion, refreshHistory]);
useEffect(() => {
2026-08-05 19:24:41 +08:00
if (!historyKey || !chatId) return;
return client.onSessionUpdate((updatedChatId, scope) => {
if (updatedChatId !== chatId) return;
if (scope === "metadata") return;
// A turn-end thread refresh can arrive while the viewport is easing the
// final layout change. User-driven scrolling already disables following,
// so keep an active programmatic follow alive across canonical hydration.
refreshCanonicalHistory();
});
2026-08-05 19:24:41 +08:00
}, [chatId, client, historyKey, refreshCanonicalHistory]);
const wasPageHiddenRef = useRef(document.visibilityState === "hidden");
useEffect(() => {
const refreshOnReturn = () => {
if (document.visibilityState === "hidden") {
wasPageHiddenRef.current = true;
return;
}
if (!wasPageHiddenRef.current) return;
wasPageHiddenRef.current = false;
2026-08-05 19:24:41 +08:00
if (!historyKey || !chatId || client.status !== "open" || loading) return;
if (
!turnActive
&& !hasPendingToolCalls
&& !client.hasUnsettledRun(chatId)
&& !historyError
) {
return;
}
refreshCanonicalHistory();
};
document.addEventListener("visibilitychange", refreshOnReturn);
return () => document.removeEventListener("visibilitychange", refreshOnReturn);
}, [
chatId,
client,
hasPendingToolCalls,
2026-08-05 19:24:41 +08:00
historyKey,
historyError,
loading,
refreshCanonicalHistory,
turnActive,
]);
useEffect(() => {
let refreshOnNextOpen = client.status !== "open";
return client.onStatus((status) => {
if (status !== "open") {
refreshOnNextOpen = true;
return;
}
if (refreshOnNextOpen) refreshCanonicalHistory();
refreshOnNextOpen = false;
});
}, [client, refreshCanonicalHistory]);
useEffect(() => {
if (chatId) return;
setMessages(projectWebuiThreadMessages(historical));
}, [chatId, historical, setMessages]);
2026-05-06 15:54:15 +00:00
useLayoutEffect(() => {
if (chatId) {
const prev = prevChatIdForCacheRef.current;
if (prev && prev !== chatId) {
messageCacheRef.current.set(prev, displayMessages);
skipLayoutCacheRef.current = true;
2026-05-06 15:54:15 +00:00
}
prevChatIdForCacheRef.current = chatId;
} else {
if (prevChatIdForCacheRef.current) {
messageCacheRef.current.set(
prevChatIdForCacheRef.current,
displayMessages,
);
skipLayoutCacheRef.current = true;
}
prevChatIdForCacheRef.current = null;
}
}, [chatId, displayMessages]);
// Persist thread to in-memory cache after paint so ``useNanobotStream``'s chat switch
// ``useEffect`` reset has flushed; ``skipLayoutCacheRef`` drops the first run that still
// sees the *previous* chat's ``messages`` (avoids stale rows leaking across sessions).
useEffect(() => {
if (!chatId) {
return;
}
if (skipLayoutCacheRef.current) {
skipLayoutCacheRef.current = false;
return;
}
if (loading) {
return;
}
messageCacheRef.current.set(chatId, displayMessages);
}, [chatId, displayMessages, loading]);
// The landing composer queues the first message while `new_chat` is in flight.
// Only the chat created for that send may consume it; selecting another chat
// while creation is pending must not leak the message there.
useEffect(() => {
if (!chatId || pendingFirstTargetChatId !== chatId) return;
const pending = pendingFirstRef.current;
if (!pending) {
setPendingFirstTargetChatId(null);
return;
}
pendingFirstRef.current = null;
setPendingFirstTargetChatId(null);
const submitted = send(pending.content, pending.images, pending.options);
if (submitted && !submitted.sideChannel) {
activeViewportTurnByChatIdRef.current.set(chatId, submitted.turnId);
setSubmittedViewportTurnId(submitted.turnId);
}
if (submitted?.delivery) {
void submitted.delivery.then(() => pending.finish?.(true), () => pending.finish?.(false));
} else pending.finish?.(submitted !== null);
setBooting(false);
}, [chatId, pendingFirstTargetChatId, send]);
useEffect(() => {
if (
!chatId
|| pendingFirstMessage?.chatId !== chatId
|| consumedPendingFirstMessageIdRef.current === pendingFirstMessage.id
) return;
consumedPendingFirstMessageIdRef.current = pendingFirstMessage.id;
const submitted = send(
pendingFirstMessage.content,
pendingFirstMessage.images,
withWorkspaceScope(pendingFirstMessage.options),
);
if (submitted && !submitted.sideChannel) {
activeViewportTurnByChatIdRef.current.set(chatId, submitted.turnId);
setSubmittedViewportTurnId(submitted.turnId);
}
onPendingFirstMessageConsumed?.(pendingFirstMessage.id);
}, [
chatId,
onPendingFirstMessageConsumed,
pendingFirstMessage,
send,
withWorkspaceScope,
]);
2026-05-06 15:54:15 +00:00
useEffect(() => {
let cancelled = false;
(async () => {
try {
const commands = await listSlashCommands(getToken());
2026-05-06 15:54:15 +00:00
if (!cancelled) setSlashCommands(commands);
} catch {
if (!cancelled) setSlashCommands([]);
}
})();
return () => {
cancelled = true;
};
}, [getToken]);
2026-05-06 15:54:15 +00:00
const handleWelcomeSend = useCallback(
async (content: string, images?: SendAttachment[], options?: SendOptions) => {
if (booting) return false;
setBooting(true);
let finish!: (accepted: boolean) => void;
const delivery = new Promise<boolean>((resolve) => { finish = resolve; });
pendingFirstRef.current = { content, images, options: withWorkspaceScope(options), finish };
setPendingFirstTargetChatId(null);
const newId = await onCreateChat?.(workspaceScope, content, localModelPreset);
if (!newId) {
pendingFirstRef.current = null;
setPendingFirstTargetChatId(null);
setBooting(false);
return false;
}
if (localModelPreset) {
await client.sendSystemCommand(newId, `/model ${localModelPreset}`).catch(() => {});
}
setPendingFirstTargetChatId(newId);
return delivery;
},
2026-08-18 18:28:19 +08:00
[booting, client, localModelPreset, onCreateChat, withWorkspaceScope, workspaceScope],
2026-05-06 14:15:36 +00:00
);
const handleThreadSend = useCallback(
(content: string, images?: SendAttachment[], options?: SendOptions) => {
const submitted = send(content, images, withWorkspaceScope(options));
if (
chatId
&& submitted
&& !submitted.sideChannel
&& options?.continueActiveTurn !== true
) {
activeViewportTurnByChatIdRef.current.set(chatId, submitted.turnId);
setSubmittedViewportTurnId(submitted.turnId);
}
return submitted?.delivery ? submitted.delivery.then(() => true) : submitted !== null;
},
[chatId, send, withWorkspaceScope],
2026-05-06 14:15:36 +00:00
);
const loadTemporaryFilePreview = useCallback((path: string) =>
client.requestMutation<FilePreviewPayload>("temporary_chat.file_preview", {
chat_id: chatId, path,
}).catch((error: unknown) => {
if (error instanceof Error && "status" in error && typeof error.status === "number") {
throw new ApiError(error.status, error.message);
}
throw error;
}), [client, chatId]);
const handleCloseFilePreview = useCallback(() => {
if (!previewSessionKey || !previewState.activeId || filePreviewClosing) return;
filePreviewResizeCleanupRef.current?.();
setClosingPreview({ key: previewSessionKey, state: previewState });
// Record the closed state immediately, even if navigation interrupts the animation.
closePreview();
filePreviewCloseTimerRef.current = window.setTimeout(() => {
filePreviewCloseTimerRef.current = null;
setClosingPreview(null);
}, FILE_PREVIEW_CLOSE_ANIMATION_MS);
}, [previewSessionKey, filePreviewClosing, previewState, closePreview]);
const cancelPreviewClose = useCallback(() => {
filePreviewResizeCleanupRef.current?.();
if (filePreviewCloseTimerRef.current !== null) {
window.clearTimeout(filePreviewCloseTimerRef.current);
filePreviewCloseTimerRef.current = null;
}
setClosingPreview(null);
}, []);
const handleOpenFilePreview = useCallback((path: string) => {
cancelPreviewClose();
openFile(path);
}, [cancelPreviewClose, openFile]);
const handleClosePreviewTab = useCallback((id: string) => {
if (previewState.tabs.length === 1) handleCloseFilePreview();
else {
filePreviewResizeCleanupRef.current?.();
closeTab(id);
}
}, [previewState.tabs.length, handleCloseFilePreview, closeTab]);
// Markdown blocks can retain rendered links while their text is unchanged.
// Keep their callback stable, but always act on the current pane/session state.
const openFilePreviewRef = useRef(handleOpenFilePreview);
openFilePreviewRef.current = handleOpenFilePreview;
const openFilePreview = useCallback((path: string) => openFilePreviewRef.current(path), []);
2026-09-23 14:03:37 +08:00
const resolveFileMetadata = useCallback((path: string) => {
if (!previewSessionKey) return Promise.reject(new Error("No active session"));
return temporary
? client.requestMutation<FileReferenceMetadata>("temporary_chat.file_preview", {
chat_id: chatId, path, metadata: true,
})
: fetchFileReferenceMetadata(getToken(), previewSessionKey, path);
}, [chatId, client, getToken, previewSessionKey, temporary]);
const loadFilePreview = useCallback((path: string) => {
if (!previewSessionKey) return Promise.reject(new Error("No active session"));
return temporary ? loadTemporaryFilePreview(path) : fetchFilePreview(getToken(), previewSessionKey, path);
}, [previewSessionKey, temporary, loadTemporaryFilePreview, getToken]);
const filePreviews = useMemo(() => createFilePreviewResource(loadFilePreview), [loadFilePreview]);
2026-09-23 14:03:37 +08:00
const fileActions = useMemo(() => ({
resolveMetadata: resolveFileMetadata,
loadPreview: filePreviews.load,
}), [resolveFileMetadata, filePreviews]);
const openWebPreview = useCallback((url: string) => {
const parsed = parseWebLink(url);
if (!parsed) return;
cancelPreviewClose();
openWeb(parsed.href);
}, [cancelPreviewClose, openWeb]);
useEffect(() => {
if (!previewOpen || !headerActive) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Escape" || event.defaultPrevented || event.isComposing) return;
// Let a dialog/menu above the pane consume Escape without closing this preview.
if (document.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"], [data-radix-popper-content-wrapper]')) return;
event.preventDefault();
handleCloseFilePreview();
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [previewOpen, headerActive, handleCloseFilePreview]);
const handleFilePreviewResizeStart = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
filePreviewResizeCleanupRef.current?.();
event.preventDefault();
event.stopPropagation();
const panel = event.currentTarget.closest<HTMLElement>("[data-file-preview-panel]");
const shellRect = shellRef.current?.getBoundingClientRect();
const rightEdge = shellRect?.right ?? window.innerWidth;
const maxWidth = maxFilePreviewWidth(shellRect?.width ?? window.innerWidth);
const originalBodyCursor = document.body.style.cursor;
const originalBodyUserSelect = document.body.style.userSelect;
const originalPanelTransition = panel?.style.transition ?? "";
const frameElement = panel?.querySelector("iframe");
const originalFramePointerEvents = frameElement?.style.pointerEvents ?? "";
let nextWidth = filePreviewWidthRef.current;
let frame: number | null = null;
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
if (panel) panel.style.transition = "none";
if (frameElement) frameElement.style.pointerEvents = "none";
const applyWidth = (clientX: number) => {
nextWidth = clampFilePreviewWidth(rightEdge - clientX, maxWidth);
filePreviewWidthRef.current = nextWidth;
if (frame !== null) return;
frame = window.requestAnimationFrame(() => {
frame = null;
panel?.style.setProperty("--file-preview-width", `${nextWidth}px`);
panel?.style.setProperty("--file-preview-slot-width", `${nextWidth}px`);
});
};
const handlePointerMove = (moveEvent: PointerEvent) => {
moveEvent.preventDefault();
applyWidth(moveEvent.clientX);
};
const stopResize = (commit: boolean) => {
if (frame !== null) {
window.cancelAnimationFrame(frame);
frame = null;
}
panel?.style.setProperty("--file-preview-width", `${nextWidth}px`);
panel?.style.setProperty("--file-preview-slot-width", `${nextWidth}px`);
if (panel) panel.style.transition = originalPanelTransition;
if (frameElement) frameElement.style.pointerEvents = originalFramePointerEvents;
if (commit) setFilePreviewWidth(nextWidth);
document.body.style.cursor = originalBodyCursor;
document.body.style.userSelect = originalBodyUserSelect;
window.removeEventListener("pointermove", handlePointerMove);
window.removeEventListener("pointerup", handlePointerUp);
window.removeEventListener("pointercancel", handlePointerUp);
filePreviewResizeCleanupRef.current = null;
};
const handlePointerUp = () => stopResize(true);
filePreviewResizeCleanupRef.current = () => stopResize(false);
applyWidth(event.clientX);
window.addEventListener("pointermove", handlePointerMove);
window.addEventListener("pointerup", handlePointerUp);
window.addEventListener("pointercancel", handlePointerUp);
}, [setFilePreviewWidth]);
useEffect(() => {
if (!previewOpen) return;
const clampToShell = () => {
const shellWidth = shellRef.current?.getBoundingClientRect().width ?? window.innerWidth;
const maxWidth = maxFilePreviewWidth(shellWidth);
setFilePreviewMaxWidth(maxWidth);
};
clampToShell();
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(clampToShell);
if (shellRef.current) observer?.observe(shellRef.current);
window.addEventListener("resize", clampToShell);
return () => {
observer?.disconnect();
window.removeEventListener("resize", clampToShell);
};
}, [previewOpen]);
const handleForkFromMessage = useCallback(
async (beforeUserIndex: number) => {
if (!chatId || !onForkChat) return;
const forkedChatId = await onForkChat(chatId, beforeUserIndex);
2026-06-10 02:54:19 +08:00
if (!forkedChatId) return;
messageCacheRef.current.delete(forkedChatId);
pendingCanonicalHydrateRef.current.delete(forkedChatId);
completedCanonicalHydrateVersionRef.current.delete(forkedChatId);
},
2026-06-10 02:54:19 +08:00
[chatId, onForkChat],
);
2026-05-06 14:15:36 +00:00
const composer = (
<>
{modelFallback?.chatId === chatId && !modelFallback.dismissed ? (
<ModelFallbackNotice
model={modelFallback.model}
reauthProvider={modelFallback.reauthProvider}
reauthProviderLabel={modelFallback.reauthProvider
? providerDisplayLabel(settings?.providers ?? [], modelFallback.reauthProvider)
: undefined}
onOpenSettings={onOpenModelSettings}
onDismiss={() => setModelFallback((current) => current && { ...current, dismissed: true })}
/>
) : null}
{recoveryState ? (
<RecoveryNotice
state={recoveryState}
onContinue={continueRecovery}
onDismiss={dismissRecovery}
/>
) : null}
{streamError && !hasInlineDeliveryError(messages, streamError) ? (
2026-05-06 14:15:36 +00:00
<StreamErrorNotice
error={streamError}
onDismiss={dismissStreamError}
/>
) : null}
{session ? (
<ThreadComposer
key={draftKey}
draftKey={draftKey}
draftStore={draftStore}
persistDraft={persistDraft}
onSend={handleThreadSend}
2026-06-10 02:54:19 +08:00
disabled={!chatId}
inputAriaLabel={composerInputAriaLabel}
isStreaming={turnActive}
activeTurnId={turnActive && chatId ? client.getRunTurnId(chatId) ?? historyActiveTurnId : null}
completedTurnIds={messagesReady && !recoveryNeedsDecision
&& chatId && !client.hasUnsettledRun(chatId) ? queueCompletedTurnIds : undefined}
2026-05-06 14:15:36 +00:00
placeholder={
composerVariant === "hero"
2026-05-06 14:15:36 +00:00
? t("thread.composer.placeholderHero")
: t("thread.composer.placeholderThread")
}
modelLabel={modelBadgeLabel}
2026-08-22 19:41:37 +08:00
modelDetail={modelBadge.model}
modelPreset={activeModelPreset}
modelPresets={modelPresetOptions}
onModelPresetChange={handleModelPresetChange}
modelProvider={modelBadge.provider}
modelProviderLabel={modelBadge.providerLabel}
modelNeedsSetup={modelBadge.needsSetup}
onModelBadgeClick={modelBadge.needsSetup ? onOpenModelSettings : undefined}
2026-08-25 19:32:07 +08:00
onManageModels={onOpenModelSettings}
2026-08-22 19:41:37 +08:00
contextUsage={composerContextUsage}
recentRoundUsage={composerRoundUsage}
variant={composerVariant}
2026-08-05 19:24:41 +08:00
slashCommands={availableSlashCommands}
onMentionSearch={requestMentionCatalogs}
2026-05-22 22:25:12 +08:00
cliApps={cliApps}
mcpPresets={mcpPresets}
2026-08-18 18:28:19 +08:00
sessions={mentionSessions}
2026-07-01 15:52:34 +08:00
skills={skills}
onStop={stop}
onTranscribeAudio={transcribeAudio}
goalState={currentGoalState}
onFavoriteWorkspaceProject={favoriteWorkspaceProject}
onResolveWorkspaceProject={resolveWorkspaceProject}
onLoadWorkspaceProjects={loadWorkspaceProjects}
workspacePickerLayoutAnchor={conversationElement}
onBrowseWorkspaceDirectories={browseWorkspaceDirectories}
workspaceScope={workspaceScope}
2026-08-06 18:29:04 +08:00
workspaceControlsHidden={temporary}
workspaceDefaultScope={workspaceDefaultScope}
workspaceControls={workspaceControls}
workspaceScopeDisabled={workspaceScopeDisabled}
workspaceError={workspaceError}
onWorkspaceScopeChange={onWorkspaceScopeChange}
pendingQueueKey={temporary ? null : chatId}
transcriptionProvider={settingsSnapshot?.transcription?.provider}
ingressLimits={ingressLimits}
quotedContext={quotedContext}
focusRequest={composerFocusSignal}
onQuotedContextChange={setQuotedContext}
2026-05-06 14:15:36 +00:00
/>
) : (
<ThreadComposer
key={draftKey}
draftKey={draftKey}
draftStore={draftStore}
persistDraft={persistDraft}
2026-05-06 14:15:36 +00:00
onSend={handleWelcomeSend}
disabled={booting}
inputAriaLabel={composerInputAriaLabel}
isStreaming={turnActive}
2026-05-06 14:15:36 +00:00
placeholder={
booting
? t("thread.composer.placeholderOpening")
: t("thread.composer.placeholderHero")
}
modelLabel={modelBadgeLabel}
2026-08-22 19:41:37 +08:00
modelDetail={modelBadge.model}
modelPreset={activeModelPreset}
modelPresets={modelPresetOptions}
onModelPresetChange={handleModelPresetChange}
modelProvider={modelBadge.provider}
modelProviderLabel={modelBadge.providerLabel}
modelNeedsSetup={modelBadge.needsSetup}
onModelBadgeClick={modelBadge.needsSetup ? onOpenModelSettings : undefined}
2026-08-25 19:32:07 +08:00
onManageModels={onOpenModelSettings}
2026-08-22 19:41:37 +08:00
contextUsage={composerContextUsage}
recentRoundUsage={composerRoundUsage}
2026-05-06 14:15:36 +00:00
variant="hero"
2026-08-05 19:24:41 +08:00
slashCommands={availableSlashCommands}
onMentionSearch={requestMentionCatalogs}
2026-05-22 22:25:12 +08:00
cliApps={cliApps}
mcpPresets={mcpPresets}
2026-08-18 18:28:19 +08:00
sessions={mentionSessions}
2026-07-01 15:52:34 +08:00
skills={skills}
2026-08-06 18:29:04 +08:00
surfaceRef={composerSurfaceRef}
onTranscribeAudio={transcribeAudio}
goalState={currentGoalState}
onFavoriteWorkspaceProject={favoriteWorkspaceProject}
onResolveWorkspaceProject={resolveWorkspaceProject}
onLoadWorkspaceProjects={loadWorkspaceProjects}
workspacePickerLayoutAnchor={conversationElement}
onBrowseWorkspaceDirectories={browseWorkspaceDirectories}
workspaceScope={workspaceScope}
2026-08-06 18:29:04 +08:00
workspaceControlsHidden={temporary}
workspaceDefaultScope={workspaceDefaultScope}
workspaceControls={workspaceControls}
workspaceScopeDisabled={workspaceScopeDisabled}
workspaceError={workspaceError}
onWorkspaceScopeChange={onWorkspaceScopeChange}
transcriptionProvider={settingsSnapshot?.transcription?.provider}
ingressLimits={ingressLimits}
quotedContext={quotedContext}
onQuotedContextChange={setQuotedContext}
2026-05-06 14:15:36 +00:00
/>
)}
</>
);
const emptyState = loading ? (
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
{t("thread.loadingConversation")}
</div>
) : (
2026-08-06 18:26:13 +08:00
<div className="flex w-full flex-col items-center text-center animate-in fade-in-0 slide-in-from-bottom-2 [animation-duration:220ms] motion-reduce:animate-none">
2026-07-23 18:18:34 +08:00
<HeroGreeting text={t(heroGreetingKey)} />
</div>
);
const sessionInfoAction = historyKey ? (
<SessionInfoPopover client={client} sessionKey={historyKey} token={token} title={title} />
) : undefined;
const promptNavigatorAction = historyKey ? (
<PromptNavigator
messages={displayMessages}
prompts={promptNavigation.prompts}
onJumpToPrompt={(promptId) => viewportRef.current?.jumpToUserPrompt(promptId)}
/>
) : undefined;
const threadHeader = !hideHeader ? (
<ThreadHeader
className={previewOpen ? "h-10" : undefined}
title={title}
onToggleSidebar={onToggleSidebar}
theme={theme}
onToggleTheme={onToggleTheme}
hideSidebarToggleForHostChrome={hideSidebarToggleForHostChrome}
hideSidebarToggle={hideSidebarToggle}
hideThemeButton={hideThemeButton}
hideTitle={hideHeaderTitle}
actions={headerActions}
minimal={!session && !loading}
promptNavigatorAction={promptNavigatorAction}
sessionInfoAction={sessionInfoAction}
temporaryChatEnabled={temporaryChatEnabled}
temporaryChatDisabled={booting || turnActive}
onTemporaryChatEnabledChange={
showTemporaryChatControl ? onTemporaryChatEnabledChange : undefined
}
/>
) : null;
return (
<SubagentTasksProvider client={client} token={token}
sessionKey={session?.key ?? null}
liveEvents={webuiCapabilities.includes("webui.subagents.events.v1")}
historyEnabled={webuiCapabilities.includes("webui.subagents.history.v1")}
active={composerActive}
enabled={!temporary && !!session?.key.startsWith("websocket:") && webuiCapabilities.includes("webui.subagents.v1")}>
<section ref={shellRef} data-preview-open={previewOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">
<div ref={setConversationElement} className={cn(
"thread-conversation relative flex min-w-0 flex-1 flex-col overflow-hidden",
headerPortalTarget === undefined && !hideHeader && "thread-workspace",
)}>
2026-08-25 01:55:58 +08:00
{hideHeaderTitle && inlineHandle && !temporary && session?.handle ? (
<div
aria-label={`Session @${session.handle.name}`}
className="flex h-8 shrink-0 items-center px-3 text-[12px]"
>
<span
className="shrink-0"
>
2026-08-18 18:28:19 +08:00
<SessionHandleLabel id={session.handle.id}>
@{session.handle.name}
2026-08-18 18:28:19 +08:00
</SessionHandleLabel>
</span>
</div>
) : null}
{headerPortalTarget === undefined ? threadHeader : null}
<FilePreviewAvailabilityProvider
resolve={previewSessionKey ? resolveFilePreviewAvailability : undefined}
>
2026-09-23 14:03:37 +08:00
<FileActionsProvider value={previewSessionKey ? fileActions : undefined}>
<WebPreviewContext.Provider value={previewSessionKey ? openWebPreview : undefined}>
<ThreadViewport
ref={viewportRef}
messages={displayMessages}
navigation={promptNavigation}
2026-08-06 18:29:04 +08:00
temporary={temporary}
isStreaming={turnActive}
runStartedAt={currentRunStartedAt}
retryStatus={retryStatus}
emptyState={emptyState}
composer={composerPortalTarget === undefined ? composer : null}
activeTurnId={viewportTurnId}
activeTurnStartedHere={activeTurnStartedHere}
conversationKey={historyKey}
conversationReady={messagesReady}
showScrollToBottomButton={!!session}
cliApps={cliApps}
mcpPresets={mcpPresets}
2026-08-05 19:24:41 +08:00
slashCommands={availableSlashCommands}
forkBoundaryMessageCount={forkBoundaryMessageCount}
hasMoreBefore={hasMoreBefore}
loadingOlder={loadingOlder}
olderError={olderError}
userMessageOffset={userMessageOffset}
onLoadOlder={loadOlder}
2026-09-12 04:37:37 +08:00
traceDetailScope={historyKey}
onLoadTraceDetails={messagesReady ? loadTraceDetails : undefined}
onOpenFilePreview={previewSessionKey ? openFilePreview : undefined}
onForkFromMessage={onForkChat ? handleForkFromMessage : undefined}
onQuoteSelection={session ? handleQuoteSelection : undefined}
/>
</WebPreviewContext.Provider>
2026-09-23 14:03:37 +08:00
</FileActionsProvider>
</FilePreviewAvailabilityProvider>
</div>
{headerPortalTarget && headerActive
? createPortal(threadHeader, headerPortalTarget)
: null}
{composerPortalTarget ? createPortal(
<div
hidden={!composerActive}
aria-hidden={!composerActive}
data-testid={composerActive ? "active-pane-composer" : undefined}
>
{composer}
</div>,
composerPortalTarget,
) : null}
{activePreview && previewSessionKey ? (
<FileActionsProvider key={previewSessionKey} value={fileActions}>
<PreviewPane
key={previewSessionKey}
tabs={visiblePreview.tabs}
activeId={activePreview.id}
width={filePreviewWidth}
isClosing={filePreviewClosing}
onSelect={selectTab}
onCloseTab={handleClosePreviewTab}
onClose={handleCloseFilePreview}
onResizeStart={handleFilePreviewResizeStart}
>
{activePreview.kind === "file" ? (
<FilePreviewPanel
key={activePreview.id}
sessionKey={previewSessionKey}
path={activePreview.value}
token={token}
loadPreview={filePreviews.load}
initialPreview={filePreviews.peek(activePreview.value)}
onOpenFilePreview={openFilePreview}
onResolvePath={resolveFile}
/>
) : <WebPreviewPanel key={activePreview.id} url={activePreview.value} />}
</PreviewPane>
</FileActionsProvider>
) : null}
</section>
</SubagentTasksProvider>
);
}