2026-06-05 19:49:34 +08:00
import { act , fireEvent , render , screen , waitFor , within } from "@testing-library/react" ;
2026-10-21 13:10:05 +08:00
import { Profiler , StrictMode , type ReactNode } from "react" ;
2026-04-18 18:51:53 +00:00
import { beforeEach , describe , expect , it , vi } from "vitest" ;
2026-07-22 22:35:39 +08:00
import { preloadMarkdownText } from "@/components/MarkdownText" ;
2026-07-26 00:18:24 +08:00
import { ThreadCameraController } from "@/components/thread/thread-camera" ;
2026-04-18 18:51:53 +00:00
import { ThreadShell } from "@/components/thread/ThreadShell" ;
2026-10-25 20:22:20 +08:00
import { SessionSearchDialog } from "@/components/SessionSearchDialog" ;
2026-11-18 16:10:02 +08:00
import { ToastProvider } from "@/components/ui/toast" ;
2026-09-07 15:12:39 +08:00
import i18n from "@/i18n" ;
2026-09-25 23:42:01 +08:00
import { ComposerDraftStore , clearStoredComposerDrafts } from "@/lib/composer-draft" ;
2026-05-23 00:59:54 +08:00
import { CLI_APPS_CHANGED_EVENT } from "@/lib/cli-app-events" ;
2026-07-29 23:15:45 +08:00
import type { CanonicalRunSnapshot , StreamError } from "@/lib/nanobot-client" ;
2026-09-12 04:37:37 +08:00
import { webuiThreadCache } from "@/lib/webui-thread-cache" ;
2026-10-16 11:38:05 +08:00
import { ThreadMessageCache } from "@/lib/thread-message-cache" ;
2026-10-21 18:33:53 +08:00
import { ThreadTranscript } from "@/lib/thread-transcript" ;
import { persistedCanonicalRunState } from "@/lib/canonical-run-snapshot" ;
2026-04-18 18:51:53 +00:00
import { ClientProvider } from "@/providers/ClientProvider" ;
2026-09-12 04:37:37 +08:00
import type {
CliAppsPayload ,
ConnectionStatus ,
SettingsPayload ,
2026-10-26 13:16:44 +08:00
SubagentTaskSnapshot ,
2026-10-21 18:33:53 +08:00
ThreadProjectionEvent ,
2026-09-12 04:37:37 +08:00
UIMessage ,
WebuiThreadPersistedPayload ,
} from "@/lib/types" ;
2026-09-20 16:48:13 +08:00
import { canonicalThreadPayload } from "./thread-test-payload" ;
2026-10-24 00:43:34 +08:00
import { createStreamClient } from "./stream-client" ;
2026-05-29 03:42:53 +08:00
2026-09-22 16:37:35 +08:00
async function openMessageActions ( text : string ) : Promise < HTMLElement > {
const message = await screen . findByText ( text );
const block = message . closest < HTMLElement >( "[data-thread-display-unit]" ) ! ;
fireEvent . click ( within ( block ). getByRole ( "button" , { name : "Message actions" }));
return screen . findByRole ( "dialog" , { name : "Message actions" });
}
2026-04-18 18:51:53 +00:00
function makeClient() {
2026-10-24 00:43:34 +08:00
const { client : lifecycle , receive } = createStreamClient ();
2026-07-29 23:15:45 +08:00
const errorHandlers = new Set < ( err : StreamError ) => void > ();
2026-07-28 11:40:01 +08:00
const statusHandlers = new Set < ( status : ConnectionStatus ) => void > ();
2026-07-23 15:57:13 +08:00
const runtimeModelHandlers = new Set <
( modelName : string | null , modelPreset? : string | null ) => void
> ();
2026-05-17 23:52:50 +08:00
const sessionUpdateHandlers = new Set < ( chatId : string , scope? : string ) => void > ();
2026-07-28 11:40:01 +08:00
let status : ConnectionStatus = "open" ;
2026-10-24 00:43:34 +08:00
const sendMessage = vi . fn ( lifecycle . sendMessage . bind ( lifecycle ));
const canReconcileCanonicalCompletion = vi . fn ( lifecycle . canReconcileCanonicalCompletion . bind ( lifecycle ));
2026-07-28 11:40:01 +08:00
const reconcileCanonicalCompletion = vi . fn ((
chatId : string ,
expectedRunGeneration : number ,
completedTurnIds : readonly string [],
snapshot? : CanonicalRunSnapshot ,
) => {
if ( ! canReconcileCanonicalCompletion (
chatId ,
expectedRunGeneration ,
completedTurnIds ,
snapshot ,
)) {
return false ;
}
2026-10-24 00:43:34 +08:00
return lifecycle . reconcileCanonicalCompletion ( chatId , expectedRunGeneration , completedTurnIds , snapshot );
2026-07-28 11:40:01 +08:00
});
2026-04-18 18:51:53 +00:00
return {
2026-07-28 11:40:01 +08:00
get status() {
return status ;
},
2026-04-18 18:51:53 +00:00
defaultChatId : null as string | null ,
2026-11-18 15:46:16 +08:00
preferenceScope : lifecycle.preferenceScope ,
2026-07-28 11:40:01 +08:00
onStatus : ( handler : ( nextStatus : ConnectionStatus ) => void ) => {
statusHandlers . add ( handler );
handler ( status );
return () => {
statusHandlers . delete ( handler );
};
},
2026-10-24 00:43:34 +08:00
onRunStatus : lifecycle.onRunStatus.bind ( lifecycle ),
onRunCompletion : lifecycle.onRunCompletion.bind ( lifecycle ),
2026-07-23 15:57:13 +08:00
onRuntimeModelUpdate : (
handler : ( modelName : string | null , modelPreset? : string | null ) => void ,
) => {
runtimeModelHandlers . add ( handler );
return () => {
runtimeModelHandlers . delete ( handler );
};
},
2026-10-24 00:43:34 +08:00
getRunState : lifecycle.getRunState.bind ( lifecycle ),
restorePendingRun : lifecycle.restorePendingRun.bind ( lifecycle ),
getRunTurnId : lifecycle.getRunTurnId.bind ( lifecycle ),
isRunCompleted : lifecycle.isRunCompleted.bind ( lifecycle ),
finishRunLocally : vi.fn ( lifecycle . finishRunLocally . bind ( lifecycle )),
hasUnsettledRun : lifecycle.hasUnsettledRun.bind ( lifecycle ),
getRunGeneration : lifecycle.getRunGeneration.bind ( lifecycle ),
2026-07-28 11:40:01 +08:00
canReconcileCanonicalCompletion ,
reconcileCanonicalCompletion ,
2026-11-17 14:50:34 +08:00
settleCompletedRunLifecycle : vi.fn ( lifecycle . settleCompletedRunLifecycle . bind ( lifecycle )),
2026-10-24 00:43:34 +08:00
fenceCanonicalCompletedTurns : lifecycle.fenceCanonicalCompletedTurns.bind ( lifecycle ),
getGoalState : lifecycle.getGoalState.bind ( lifecycle ),
onTranscript : lifecycle.onTranscript.bind ( lifecycle ),
onChat : lifecycle.onChat.bind ( lifecycle ),
2026-07-29 23:15:45 +08:00
onError : ( handler : ( err : StreamError ) => void ) => {
2026-04-21 10:29:47 +00:00
errorHandlers . add ( handler );
return () => {
errorHandlers . delete ( handler );
};
},
2026-05-17 23:52:50 +08:00
onSessionUpdate : ( handler : ( chatId : string , scope? : string ) => void ) => {
2026-05-13 16:39:07 +00:00
sessionUpdateHandlers . add ( handler );
return () => {
sessionUpdateHandlers . delete ( handler );
};
},
2026-07-29 23:15:45 +08:00
_emitError ( err : StreamError ) {
2026-10-24 00:43:34 +08:00
if ( err . chatId && err . turnId ) receive ({
event : "error" , chat_id : err.chatId , turn_id : err.turnId , detail : err.kind ,
});
2026-04-21 10:29:47 +00:00
for ( const h of errorHandlers ) h ( err );
},
2026-07-28 11:40:01 +08:00
_emitStatus ( nextStatus : ConnectionStatus ) {
status = nextStatus ;
for ( const h of statusHandlers ) h ( status );
},
2026-10-24 00:43:34 +08:00
_emitChat ( _chatId : string , ev : import ( "@/lib/types" ). InboundEvent ) { receive ( ev ); },
2026-07-23 15:57:13 +08:00
_emitRuntimeModelUpdate ( modelName : string | null , modelPreset? : string | null ) {
for ( const h of runtimeModelHandlers ) h ( modelName , modelPreset );
},
2026-05-17 23:52:50 +08:00
_emitSessionUpdate ( chatId : string , scope? : string ) {
for ( const h of sessionUpdateHandlers ) h ( chatId , scope );
2026-05-13 16:39:07 +00:00
},
2026-07-28 11:40:01 +08:00
sendMessage ,
2026-07-24 17:34:26 +08:00
sendSystemCommand : vi.fn (). mockResolvedValue ( undefined ),
2026-04-18 18:51:53 +00:00
newChat : vi.fn (),
2026-06-05 19:49:34 +08:00
forkChat : vi.fn (),
2026-04-18 18:51:53 +00:00
attach : vi.fn (),
connect : vi.fn (),
close : vi.fn (),
updateUrl : vi.fn (),
};
}
2026-07-30 10:25:22 +08:00
function wrap (
client : ReturnType < typeof makeClient >,
children : ReactNode ,
modelName? : string | null ,
token = "tok" ,
2026-10-05 05:16:33 +08:00
webuiCapabilities : string [] = [],
2026-07-30 10:25:22 +08:00
) {
2026-04-18 18:51:53 +00:00
return (
< ClientProvider
client = { client as unknown as import ( "@/lib/nanobot-client" ). NanobotClient }
2026-07-30 10:25:22 +08:00
token = { token }
2026-05-29 03:42:53 +08:00
modelName = { modelName ?? null }
2026-10-05 05:16:33 +08:00
webuiCapabilities = { webuiCapabilities }
2026-04-18 18:51:53 +00:00
>
{ children }
</ ClientProvider >
);
}
2026-06-06 19:49:33 +08:00
function expectSendMessageWithTurn (
client : ReturnType < typeof makeClient >,
chatId : string ,
content : string ,
options : unknown = undefined ,
) {
expect ( client . sendMessage ). toHaveBeenCalledWith (
chatId ,
content ,
options ,
expect . objectContaining ({ turnId : expect.any ( String ) }),
);
}
2026-07-23 00:38:49 +08:00
function session ( chatId : string , modelPreset? : string | null ) {
2026-04-18 18:51:53 +00:00
return {
key : `websocket: ${ chatId } ` ,
channel : "websocket" as const ,
chatId ,
createdAt : null ,
updatedAt : null ,
preview : "" ,
2026-07-23 00:38:49 +08:00
modelPreset ,
2026-04-18 18:51:53 +00:00
};
}
2026-05-16 01:14:11 +08:00
function transcriptFromSimpleMessages (
2026-10-21 18:33:53 +08:00
rows : Array < { id? : string ; role : "user" | "assistant" ; content : string ; turnId? : string } > ,
2026-09-20 16:48:13 +08:00
) : WebuiThreadPersistedPayload {
return canonicalThreadPayload ({
2026-05-16 01:14:11 +08:00
schemaVersion : 3 ,
messages : rows.map (( m , i ) => ({
2026-10-21 18:33:53 +08:00
id : m.id ?? `m- ${ i } ` ,
2026-05-16 01:14:11 +08:00
role : m.role ,
content : m.content ,
2026-07-28 11:40:01 +08:00
...( m . turnId ? { turnId : m.turnId } : {}),
2026-05-16 01:14:11 +08:00
createdAt : 1000 + i ,
})),
2026-09-20 16:48:13 +08:00
}) ! ;
2026-05-16 01:14:11 +08:00
}
2026-10-21 18:33:53 +08:00
type StreamedFixtureRow =
| ({
role : "user" ;
content : string ;
startsTurn? : boolean ;
activeTurnId? : string ;
} & (
| { turnId : string ; sessionMessage? : never }
| { turnId? : never ; sessionMessage : NonNullable < UIMessage [ "sessionMessage" ] > }
))
| {
role : "assistant" ;
content : string ;
turnId : string ;
streamId : string ;
textSeq? : number ;
endSeq? : number ;
mergeNext? : boolean ;
};
// Stream replacement requires the actual input and wire sources, not display IDs.
function streamedThreadPayload (
chatId : string ,
rows : StreamedFixtureRow [],
completedTurnIds : string [] = [],
) : WebuiThreadPersistedPayload {
const events : ThreadProjectionEvent [] = [];
rows . forEach (( row , index ) => {
if ( row . role === "user" ) {
events . push ({
event : "user_message" , chat_id : chatId ,
projection_id : `input: ${ row . turnId ?? row . sessionMessage . message_id } ` ,
text : row.content , starts_turn : row.startsTurn ?? true ,
...( row . turnId ? { turn_id : row.turnId , turn_seq : 1 } : {}),
...( row . activeTurnId ? { active_turn_id : row.activeTurnId } : {}),
...( row . sessionMessage ? { provenance : { session_message : row.sessionMessage } } : {}),
});
} else {
const textSeq = row . textSeq ?? 2 ;
const endSeq = row . endSeq ?? 3 ;
events . push ({
event : "stream_end" , chat_id : chatId ,
projection_id : `answer: ${ row . turnId } : ${ row . streamId } : ${ endSeq } ` ,
turn_id : row.turnId , turn_phase : "answer" , turn_seq : endSeq ,
stream_id : row.streamId , text : row.content ,
2026-11-11 17:32:47 +08:00
text_from_seq : textSeq ,
2026-10-21 18:33:53 +08:00
...( row . mergeNext ? { resuming : true , merge_next : true } : {}),
});
}
if ( row . turnId && completedTurnIds . includes ( row . turnId )
&& ! rows . slice ( index + 1 ). some (( later ) => later . turnId === row . turnId )) {
events . push ({
event : "turn_end" , chat_id : chatId , turn_id : row.turnId ,
projection_id : `complete: ${ row . turnId } ` ,
turn_seq : row.role === "assistant" ? ( row . endSeq ?? 3 ) + 1 : 2 ,
});
}
});
return { schemaVersion : 3 , projection : "events" , events , completed_turn_ids : completedTurnIds };
}
function publishReconnectCompletion (
client : ReturnType < typeof makeClient >,
chatId : string ,
body : WebuiThreadPersistedPayload ,
) {
const generation = client . getRunGeneration ( chatId );
const { completedTurnIds , snapshot } = persistedCanonicalRunState ( body );
expect ( client . canReconcileCanonicalCompletion ( chatId , generation , completedTurnIds , snapshot )). toBe ( true );
2026-11-17 14:50:34 +08:00
// A mounted transcript takes over reconciliation from the recovery reader.
2026-10-21 18:33:53 +08:00
webuiThreadCache . set ( `websocket: ${ chatId } ` , body );
}
2026-04-18 18:51:53 +00:00
function httpJson ( body : unknown ) {
2026-09-20 16:48:13 +08:00
const normalized = body && typeof body === "object"
&& "schemaVersion" in body
&& "messages" in body
? canonicalThreadPayload ( body as never )
: body ;
2026-10-20 14:26:54 +08:00
return Response . json ( normalized );
2026-04-18 18:51:53 +00:00
}
2026-09-12 04:37:37 +08:00
function traceDetailThread (
deferred : boolean ,
answer : string ,
revision? : string ,
) : WebuiThreadPersistedPayload {
2026-09-20 16:48:13 +08:00
return canonicalThreadPayload ({
2026-09-12 04:37:37 +08:00
schemaVersion : 3 ,
...( revision ? { revision } : {}),
messages : [
{
id : "trace-shared" ,
role : "tool" ,
kind : "trace" ,
content : deferred ? "exec(…)" : 'exec({"command":"echo full"})' ,
traces : [ deferred ? "exec(…)" : 'exec({"command":"echo full"})' ],
...( deferred
2026-09-20 16:48:13 +08:00
? {
traceDetail : {
ref : "1.history-aaaaaaaaaaaaaaaaaaaa" ,
bytes : 40_000 ,
traceCount : 1 ,
},
}
2026-09-12 04:37:37 +08:00
: {}),
createdAt : 1_000 ,
},
{
id : "answer-shared" ,
role : "assistant" ,
content : answer ,
createdAt : 2_000 ,
},
],
2026-09-20 16:48:13 +08:00
}) ! ;
2026-09-12 04:37:37 +08:00
}
2026-07-30 10:25:22 +08:00
function setDocumentVisibility ( value : DocumentVisibilityState ) : void {
Object . defineProperty ( document , "visibilityState" , {
configurable : true ,
value ,
});
document . dispatchEvent ( new Event ( "visibilitychange" ));
}
function restoreDocumentVisibility (
descriptor : PropertyDescriptor | undefined ,
) : void {
if ( descriptor ) {
Object . defineProperty ( document , "visibilityState" , descriptor );
} else {
2026-10-20 14:26:54 +08:00
Reflect . deleteProperty ( document , "visibilityState" );
2026-07-30 10:25:22 +08:00
}
}
2026-07-26 00:18:24 +08:00
interface ThreadResizeObserverInstance {
elements : Element [];
callback : ResizeObserverCallback ;
}
function stubThreadResizeObserver() {
const original = globalThis . ResizeObserver ;
const observers : ThreadResizeObserverInstance [] = [];
class MockResizeObserver {
elements : Element [] = [];
callback : ResizeObserverCallback ;
constructor ( callback : ResizeObserverCallback ) {
this . callback = callback ;
observers . push ( this );
}
observe ( element : Element ) {
this . elements . push ( element );
}
disconnect() { }
}
vi . stubGlobal ( "ResizeObserver" , MockResizeObserver );
return {
observers ,
restore : () => vi . stubGlobal ( "ResizeObserver" , original ),
};
}
2026-05-29 03:42:53 +08:00
function modelSettings ( model : string , provider : string ) : SettingsPayload {
return {
agent : {
model ,
provider ,
resolved_provider : provider ,
has_api_key : true ,
model_preset : "default" ,
max_tokens : 4096 ,
context_window_tokens : 65536 ,
temperature : 0.7 ,
reasoning_effort : null ,
timezone : "UTC" ,
tool_hint_max_length : 40 ,
},
model_presets : [{
name : "default" ,
label : "Default" ,
active : true ,
is_default : true ,
model ,
provider ,
max_tokens : 4096 ,
context_window_tokens : 65536 ,
temperature : 0.7 ,
reasoning_effort : null ,
}],
2026-07-24 00:55:06 +08:00
model_call_order : [],
model_call_order_editable : false ,
2026-05-29 03:42:53 +08:00
providers : [
{ name : "deepseek" , label : "DeepSeek" , configured : true },
{ name : "openai_codex" , label : "OpenAI Codex" , configured : true },
],
web_search : {
provider : "duckduckgo" ,
api_key_hint : null ,
base_url : null ,
max_results : 5 ,
timeout : 30 ,
providers : [],
},
web : {
enable : true ,
2026-10-22 15:49:27 +08:00
use_proxy : false ,
2026-05-29 03:42:53 +08:00
user_agent : null ,
search : { max_results : 5 , timeout : 30 },
fetch : { use_jina_reader : true },
},
image_generation : {
enabled : false ,
provider : "openrouter" ,
provider_configured : false ,
model : "openai/gpt-5.4-image-2" ,
default_aspect_ratio : "1:1" ,
default_image_size : "1K" ,
max_images_per_turn : 4 ,
save_dir : "generated" ,
providers : [],
},
runtime : {
config_path : "/tmp/config.json" ,
workspace_path : "/tmp/workspace" ,
gateway_host : "127.0.0.1" ,
gateway_port : 18790 ,
heartbeat : {
enabled : true ,
interval_s : 1800 ,
},
dream : {
schedule : "every 2h" ,
},
},
advanced : {
restrict_to_workspace : false ,
webui_allow_local_service_access : true ,
webui_default_access_mode : "default" ,
private_service_protection_enabled : true ,
ssrf_whitelist_count : 0 ,
mcp_server_count : 0 ,
exec_enabled : true ,
exec_sandbox : null ,
2026-06-10 15:50:24 +08:00
exec_path_prepend_set : false ,
2026-05-29 03:42:53 +08:00
exec_path_append_set : false ,
},
requires_restart : false ,
};
}
2026-07-23 00:38:49 +08:00
function settingsWithFastPreset () : SettingsPayload {
const settings = modelSettings ( "deepseek-v4-pro" , "deepseek" );
settings . model_presets . push ({
... settings . model_presets [ 0 ] ! ,
name : "fast" ,
label : "Fast" ,
active : false ,
is_default : false ,
model : "openai-codex/gpt-5.5" ,
provider : "openai_codex" ,
});
return settings ;
}
2026-04-18 18:51:53 +00:00
describe ( "ThreadShell" , () => {
2026-11-18 15:46:16 +08:00
function optionsSettings() {
const settings = settingsWithFastPreset ();
for ( const preset of settings . model_presets ) preset . model_options = {
reasoning_effort : { default : "low" , values : [ "low" , "high" ] }, codex_fast_mode : { default : true },
};
settings . providers = settings . providers . map (( provider ) => ({ ... provider , model_catalog : "unsupported" }));
return settings ;
}
async function changeOptions() {
fireEvent . click ( await screen . findByRole ( "button" , { name : "Default" }));
fireEvent . change ( screen . getByRole ( "slider" , { name : "Reasoning effort" }), { target : { value : "1" } });
fireEvent . click ( screen . getByRole ( "button" , { name : "Fast" }));
fireEvent . keyDown ( screen . getByRole ( "dialog" , { name : "Switch model" }), { key : "Escape" });
}
it ( "keeps model option choices local until sending, includes explicit false, and clears them on preset switch" , async () => {
localStorage . clear ();
const client = makeClient ();
render ( wrap ( client , < ThreadShell session = { session ( "model-options" )} title = "Options" onToggleSidebar = {() => {}}
settingsSnapshot = { optionsSettings ()} />, null , "tok" , [ "webui.model-options.v1" ]));
await changeOptions ();
expect ( client . sendMessage ). not . toHaveBeenCalled ();
expect ( client . sendSystemCommand ). not . toHaveBeenCalled ();
fireEvent . change ( screen . getByLabelText ( "Message input" ), { target : { value : "selected options" } });
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( client . sendMessage ). toHaveBeenCalledWith ( "model-options" , "selected options" , undefined ,
expect . objectContaining ({ modelOptions : { reasoning_effort : "high" , codex_fast_mode : false } })));
fireEvent . click ( screen . getByRole ( "button" , { name : "Default" }));
fireEvent . click ( await screen . findByRole ( "option" , { name : "fast" }));
fireEvent . click ( screen . getByRole ( "button" , { name : "fast" }));
expect ( screen . getByRole ( "slider" , { name : "Reasoning effort" })). toHaveAttribute ( "aria-valuetext" , "low" );
expect ( screen . getByRole ( "button" , { name : "Fast" })). toHaveAttribute ( "aria-pressed" , "true" );
expect ( client . sendSystemCommand ). toHaveBeenCalledWith ( "model-options" , "/model fast" );
expect ( client . sendMessage ). toHaveBeenCalledTimes ( 1 );
});
it ( "sends and migrates the landing selection with the first ordinary message" , async () => {
localStorage . clear ();
const client = makeClient ();
const settings = optionsSettings ();
const view = ( currentSession : ReturnType < typeof session > | null ) => wrap ( client , < ThreadShell session = { currentSession }
title = "Options" onToggleSidebar = {() => {}} settingsSnapshot = { settings } onCreateChat = { async () => "options-created" } />,
null , "tok" , [ "webui.model-options.v1" ]);
const rendered = render ( view ( null ));
await changeOptions ();
fireEvent . change ( screen . getByLabelText ( "Message input" ), { target : { value : "first selection" } });
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await act ( async () => {});
rendered . rerender ( view ( session ( "options-created" )));
await waitFor (() => expect ( client . sendMessage ). toHaveBeenCalledWith ( "options-created" , "first selection" , undefined ,
expect . objectContaining ({ modelOptions : { reasoning_effort : "high" , codex_fast_mode : false } })));
fireEvent . click ( await screen . findByRole ( "button" , { name : "Default" }));
expect ( screen . getByRole ( "slider" , { name : "Reasoning effort" })). toHaveAttribute ( "aria-valuetext" , "high" );
expect ( screen . getByRole ( "button" , { name : "Fast" })). toHaveAttribute ( "aria-pressed" , "false" );
});
it ( "sends edited queued prompts using current options, while cancelling the queue sends nothing" , async () => {
localStorage . clear ();
const client = makeClient ();
const chatId = "options-queue" ;
render ( wrap ( client , < ThreadShell session = { session ( chatId )} title = "Options" onToggleSidebar = {() => {}}
settingsSnapshot = { optionsSettings ()} />, null , "tok" , [ "webui.model-options.v1" ]));
await screen . findByLabelText ( "Message input" );
act (() => client . _emitChat ( chatId , { event : "goal_status" , chat_id : chatId , turn_id : "owner" , status : "running" , started_at : 1_000 }));
const input = screen . getByLabelText ( "Message input" );
fireEvent . change ( input , { target : { value : "queued options" } });
fireEvent . keyDown ( input , { key : "Enter" });
fireEvent . click ( screen . getByRole ( "button" , { name : "Delete message" }));
expect ( client . sendMessage ). not . toHaveBeenCalled ();
fireEvent . change ( input , { target : { value : "queued options again" } });
fireEvent . keyDown ( input , { key : "Enter" });
await changeOptions ();
fireEvent . click ( screen . getByRole ( "button" , { name : "Edit message" }));
fireEvent . change ( input , { target : { value : "edited options" } });
fireEvent . keyDown ( input , { key : "Enter" });
fireEvent . click ( screen . getByRole ( "button" , { name : "Send now" }));
await waitFor (() => expect ( client . sendMessage ). toHaveBeenCalledWith ( chatId , "edited options" , undefined ,
expect . objectContaining ({ modelOptions : { reasoning_effort : "high" , codex_fast_mode : false } })));
});
2026-04-18 18:51:53 +00:00
beforeEach (() => {
2026-09-12 04:37:37 +08:00
webuiThreadCache . clear ();
2026-09-25 23:42:01 +08:00
clearStoredComposerDrafts ();
2026-04-18 18:51:53 +00:00
vi . stubGlobal (
"fetch" ,
vi . fn (). mockResolvedValue ({
ok : false ,
status : 404 ,
json : async () => ({}),
}),
);
});
2026-10-25 20:22:20 +08:00
it ( "publishes received and live body text to local search without search-driven reads" , async () => {
const client = makeClient ();
const cache = new ThreadMessageCache (() => false );
const chatId = "loaded-search" ;
const fetch = vi . fn ( async ( input : RequestInfo | URL ) => String ( input ). includes ( "/webui-thread" )
? httpJson ( transcriptFromSimpleMessages ([{ role : "assistant" , content : "Seeded history" }]))
: new Response ( null , { status : 404 }));
vi . stubGlobal ( "fetch" , fetch );
render ( wrap ( client , <>
< ThreadShell session = { session ( chatId )} title = "Loaded topic" messageCache = { cache } onToggleSidebar = {() => {}} />
< SessionSearchDialog open sessions = {[ session ( chatId )]} activeKey = { null } loading = { false }
messageCache = { cache } onOpenChange = {() => {}} onSelect = {() => {}} />
</>));
const dialog = await screen . findByRole ( "dialog" , { name : "Search" });
const input = within ( dialog ). getByRole ( "textbox" , { name : "Search" });
fireEvent . change ( input , { target : { value : "seeded history" } });
await within ( dialog ). findByText ( "Seeded history" );
const readsBeforeSearch = fetch . mock . calls . length ;
fireEvent . change ( input , { target : { value : "fresh needle" } });
expect ( within ( dialog ). getByText ( "No matching topics." )). toBeInTheDocument ();
act (() => client . _emitChat ( chatId , { event : "message" , chat_id : chatId , text : "Fresh needle from the live stream" }));
await within ( dialog ). findByText ( "Fresh needle from the live stream" );
expect ( fetch ). toHaveBeenCalledTimes ( readsBeforeSearch );
});
2026-10-21 18:30:52 +08:00
it . each ([ "callback" , "cached return" ] as const )( "keeps closed answer segments in order after %s" , async ( path ) => {
const client = makeClient ();
const messageCache = new ThreadMessageCache (() => false );
const chatId = "answer-order" ;
const turnId = "answer-order-turn" ;
const source = { provider : "fixture" , model : "fixture" , preset : "fixture" };
const shell = ( id : string , onTurnEnd = () => {}) => wrap ( client , < ThreadShell
session = { session ( id )} title = "Answer order" messageCache = { messageCache }
onToggleSidebar = {() => {}} onTurnEnd = { onTurnEnd } />);
const view = render ( shell ( chatId ));
act (() => {
client . _emitChat ( chatId , { event : "goal_status" , chat_id : chatId , turn_id : turnId , status : "running" , started_at : 100 });
client . _emitChat ( chatId , { event : "delta" , chat_id : chatId , turn_id : turnId , stream_id : "first" , turn_seq : 1 , text : "Earlier answer" });
client . _emitChat ( chatId , { event : "stream_end" , chat_id : chatId , turn_id : turnId , stream_id : "first" , turn_seq : 2 , resuming : true , response_sources : [ source ] });
client . _emitChat ( chatId , { event : "message" , chat_id : chatId , turn_id : turnId , turn_seq : 3 , kind : "tool_hint" , text : "read_file(earlier)" });
client . _emitChat ( chatId , { event : "delta" , chat_id : chatId , turn_id : turnId , stream_id : "second" , turn_seq : 4 , text : "Later answer" });
client . _emitChat ( chatId , { event : "stream_end" , chat_id : chatId , turn_id : turnId , stream_id : "second" , turn_seq : 5 , resuming : true , response_sources : [ source ] });
client . _emitChat ( chatId , { event : "message" , chat_id : chatId , turn_id : turnId , turn_seq : 6 , kind : "tool_hint" , text : "read_file(later)" });
});
await screen . findByText ( "Later answer" );
if ( path === "cached return" ) {
view . rerender ( shell ( "other-chat" ));
expect ( screen . queryByText ( "Earlier answer" )). not . toBeInTheDocument ();
}
view . rerender ( shell ( chatId ));
await screen . findByText ( "Earlier answer" );
act (() => {
client . _emitChat ( chatId , { event : "stream_end" , chat_id : chatId , turn_id : turnId , stream_id : "empty-one" , turn_seq : 7 , resuming : true , response_sources : [ source ] });
client . _emitChat ( chatId , { event : "stream_end" , chat_id : chatId , turn_id : turnId , stream_id : "empty-two" , turn_seq : 8 , resuming : true , response_sources : [ source ] });
});
const earlier = screen . getByText ( "Earlier answer" );
const later = screen . getByText ( "Later answer" );
expect ( earlier . compareDocumentPosition ( later ) & Node . DOCUMENT_POSITION_FOLLOWING ). toBeTruthy ();
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
});
2026-11-12 21:37:08 +08:00
it ( "queries only rendered task history as loaded pages and navigation windows change" , async () => {
const client = makeClient ();
const chatId = "task-window-pages" ;
const rows = ( prefix : string , count : number ) => Array . from ({ length : count }, ( _ , index ) => ({
id : ` ${ prefix }${ index } ` , role : "user" as const , content : ` ${ prefix } prompt ${ index } ` , turnId : ` ${ prefix } t ${ index } ` ,
}));
let resolveInitial !: ( response : Response ) => void ;
const seen : URL [] = [];
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => {
const url = new URL ( String ( input ), "http://localhost" );
if ( url . pathname . endsWith ( "/subagents" )) {
seen . push ( url );
return Promise . resolve ( httpJson ({ tasks : [] }));
}
if ( url . pathname . endsWith ( "/prompts" )) return Promise . resolve ( httpJson ({ prompts : [{
id : "nav2" , preview : "nav prompt 2" , answerPreview : "" , createdAt : 1 ,
cursor : "nav" , turnId : "navt2" ,
}] }));
if ( url . pathname . endsWith ( "/webui-thread" )) {
if ( url . searchParams . get ( "before" ) === "older" ) return Promise . resolve ( httpJson ({
... transcriptFromSimpleMessages ( rows ( "old" , 5 )),
page : { has_more_before : false , user_message_offset : 0 },
}));
if ( url . searchParams . get ( "after" ) === "nav" ) return Promise . resolve ( httpJson ({
... transcriptFromSimpleMessages ( rows ( "nav" , 3 )),
page : { has_more_before : false , has_more_after : true },
}));
return new Promise < Response >(( resolve ) => { resolveInitial = resolve ; });
}
return Promise . resolve ( new Response ( null , { status : 404 }));
}));
const { container } = render (< StrictMode >{ wrap ( client , < ThreadShell session = { session ( chatId )} title = "Task pages"
onToggleSidebar = {() => {}} />, null , "tok" , [ "webui.prompt-navigation.v1" , "webui.subagents.v1" , "webui.subagents.events.v1" ])}</ StrictMode >);
await waitFor (() => expect ( resolveInitial ). toBeTypeOf ( "function" ));
expect ( seen ). toHaveLength ( 0 );
act (() => client . _emitChat ( chatId , { event : "subagent_task" , chat_id : chatId , task : {
task_id : "live-during-load" , revision : 1 , label : "Live during load" , task_description : "Background work" ,
origin_turn_id : "elsewhere" , origin_message_id : null , created_at : 100 , completed_at : null ,
state : "running" , phase : "awaiting_model" , elapsed_seconds : 2 , iteration : 1 , tool_events : [],
usage : null , receipts : {}, result : null , partial : false , stop_reason : null , error : null ,
} }));
expect ( await screen . findByTestId ( "subagent-task-dock-trigger" )). toHaveTextContent ( "Running: 1" );
await act ( async () => resolveInitial ( httpJson ({ ... transcriptFromSimpleMessages ( rows ( "new" , 5 )),
page : { before_cursor : "older" , has_more_before : true , user_message_offset : 5 },
})));
await screen . findByText ( "new prompt 4" );
await waitFor (() => expect ( seen ). toHaveLength ( 1 ));
expect ( seen [ 0 ]. searchParams . getAll ( "turn_id" )). toEqual ( rows ( "new" , 5 ). map ( row => row . turnId ));
expect ( seen [ 0 ]. searchParams . getAll ( "track" )). toEqual ([ "live-during-load" ]);
const scroller = container . querySelector ( ".thread-message-viewport" ) as HTMLElement ;
Object . defineProperties ( scroller , {
scrollHeight : { configurable : true , value : 2400 }, clientHeight : { configurable : true , value : 600 },
scrollTop : { configurable : true , writable : true , value : 0 },
});
fireEvent . keyDown ( scroller , { key : "Home" });
await screen . findByText ( "old prompt 0" );
await waitFor (() => expect ( seen ). toHaveLength ( 2 ));
expect ( seen [ 1 ]. searchParams . getAll ( "turn_id" )). toEqual ( rows ( "old" , 5 ). map ( row => row . turnId ));
fireEvent . click ( await screen . findByRole ( "button" , { name : "Message navigation" }));
fireEvent . click ( within ( screen . getByRole ( "dialog" )). getByRole ( "button" , { name : "Jump to message: nav prompt 2" }));
await screen . findByText ( "nav prompt 2" );
await waitFor (() => expect ( seen ). toHaveLength ( 3 ));
expect ( seen [ 2 ]. searchParams . getAll ( "turn_id" )). toEqual ( rows ( "nav" , 3 ). map ( row => row . turnId ));
fireEvent . click ( screen . getByRole ( "button" , { name : "Scroll to bottom" }));
await screen . findByText ( "new prompt 4" );
await act ( async () => { await Promise . resolve (); });
expect ( seen ). toHaveLength ( 3 );
fireEvent ( window , new Event ( "focus" ));
await waitFor (() => expect ( seen ). toHaveLength ( 4 ));
const latest = [... rows ( "old" , 5 ), ... rows ( "new" , 5 )];
expect ( seen [ 3 ]. searchParams . getAll ( "turn_id" )). toEqual ( latest . map ( row => row . turnId ));
});
2026-10-26 13:16:44 +08:00
it ( "keeps the dock and task events alive after the parent response finishes" , async () => {
const client = makeClient ();
const snapshot : SubagentTaskSnapshot = {
task_id : "background-task" , revision : 1 , label : "Background inspection" , task_description : "Inspect settings" ,
origin_turn_id : "parent-turn" , origin_message_id : null , created_at : 100 , completed_at : null ,
state : "running" , phase : "awaiting_model" , elapsed_seconds : 2 , iteration : 1 , tool_events : [],
usage : null , receipts : {}, result : null , partial : false , stop_reason : null , error : null ,
};
vi . stubGlobal ( "fetch" , vi . fn ( async ( input : RequestInfo | URL ) => {
2026-11-12 21:37:08 +08:00
if ( new URL ( String ( input ), "http://localhost" ). pathname . endsWith ( "/subagents" )) return httpJson ({ tasks : [ snapshot ] });
2026-10-26 13:16:44 +08:00
if ( String ( input ). includes ( "/webui-thread" )) return httpJson ( transcriptFromSimpleMessages ([
{ role : "user" , content : "Delegate inspection" , turnId : "parent-turn" },
]));
return Response . json ({}, { status : 404 });
}));
render ( wrap ( client , < ThreadShell session = { session ( "background-work" )} title = "Background work" onToggleSidebar = {() => {}} />,
null , "tok" , [ "webui.core.v1" , "webui.subagents.v1" , "webui.subagents.events.v1" ]));
const trigger = await screen . findByTestId ( "subagent-task-dock-trigger" );
act (() => client . _emitChat ( "background-work" , { event : "goal_status" , chat_id : "background-work" , turn_id : "parent-turn" , status : "running" , started_at : 100 }));
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeVisible ();
act (() => client . _emitChat ( "background-work" , { event : "turn_end" , chat_id : "background-work" , turn_id : "parent-turn" }));
expect ( screen . queryByRole ( "button" , { name : "Stop response" })). not . toBeInTheDocument ();
expect ( trigger ). toHaveTextContent ( "Running: 1" );
act (() => client . _emitChat ( "background-work" , { event : "user_message" , chat_id : "background-work" , turn_id : "next-turn" , turn_seq : 1 , starts_turn : true , text : "Continue with the next request" }));
expect ( trigger ). toHaveTextContent ( "Running: 1" );
fireEvent . click ( trigger );
const list = screen . getByTestId ( "subagent-task-tree" );
expect ( within ( list ). getByRole ( "button" , { name : /Background inspection Running/ })). toBeVisible ();
act (() => client . _emitChat ( "background-work" , { event : "subagent_task" , chat_id : "background-work" , task : {
... snapshot , revision : 2 , state : "done" , completed_at : 103 , result : "Inspection finished after the parent reply" ,
} }));
expect ( trigger ). toHaveTextContent ( "Completed: 1" );
expect ( await within ( list ). findByText ( "Inspection finished after the parent reply" )). toBeVisible ();
expect ( list ). toBeVisible ();
});
2026-10-05 05:16:33 +08:00
it ( "renders one persisted task entry at the initiating prompt through the full shell" , async () => {
const client = makeClient ();
vi . stubGlobal ( "fetch" , vi . fn ( async ( input : RequestInfo | URL ) => {
2026-11-12 21:37:08 +08:00
if ( new URL ( String ( input ), "http://localhost" ). pathname . endsWith ( "/subagents" )) return httpJson ({ tasks : [{
2026-10-05 05:16:33 +08:00
task_id : "completed-task" , label : "Inspect settings" , task_description : "Inspect settings" ,
origin_turn_id : "delegation-turn" , origin_message_id : null , created_at : 100 , completed_at : 102 ,
state : "done" , phase : "done" , elapsed_seconds : 2 , iteration : 1 , tool_events : [],
usage : null , receipts : {}, result : "Verified" , partial : false , stop_reason : "completed" , error : null ,
}] });
if ( String ( input ). includes ( "/webui-thread" )) return httpJson ( transcriptFromSimpleMessages ([
{ role : "user" , content : "Delegate inspection" , turnId : "delegation-turn" },
{ role : "assistant" , content : "Parent conclusion" , turnId : "delegation-turn" },
]));
return { ok : false , status : 404 , json : async () => ({}) };
}));
const shell = () => wrap ( client , < ThreadShell session = { session ( "persisted-tasks" )} title = "Task history"
onToggleSidebar = {() => {}} />, null , "tok" , [ "webui.core.v1" , "webui.subagents.v1" ]);
const view = render ( shell ());
await screen . findByText ( "Delegate inspection" );
2026-10-26 13:16:44 +08:00
fireEvent . click ( await screen . findByRole ( "button" , { name : /Subtasks Completed: 1/ }));
2026-10-05 05:16:33 +08:00
const task = await screen . findByRole ( "button" , { name : /Inspect settings Completed/ });
2026-10-26 13:16:44 +08:00
expect ( screen . queryByTestId ( "subagent-task-dock" )). not . toBeInTheDocument ();
2026-10-05 05:16:33 +08:00
await screen . findByText ( "Delegate inspection" );
expect ( screen . getAllByRole ( "button" , { name : /Inspect settings/ })). toHaveLength ( 1 );
expect ( screen . getByTestId ( "thread-message-region" )). toContainElement ( task );
expect ( within ( screen . getByTestId ( "thread-composer-motion" )). queryByText ( "Inspect settings" )). not . toBeInTheDocument ();
view . unmount ();
render ( shell ());
await screen . findByText ( "Delegate inspection" );
2026-10-26 13:16:44 +08:00
fireEvent . click ( await screen . findByRole ( "button" , { name : /Subtasks Completed: 1/ }));
2026-10-05 05:16:33 +08:00
await screen . findByRole ( "button" , { name : /Inspect settings Completed/ });
2026-10-26 13:16:44 +08:00
expect ( screen . queryByTestId ( "subagent-task-dock" )). not . toBeInTheDocument ();
2026-10-05 05:16:33 +08:00
expect ( client . sendMessage ). not . toHaveBeenCalled ();
});
2026-10-22 18:32:18 +08:00
it ( "restores the landing attachment draft in its created topic after a gateway rejection" , async () => {
const client = { ... makeClient (), sendAttachments : vi.fn (). mockRejectedValue ( new Error ( "file not found" )) };
const store = new ComposerDraftStore ();
store . set ( "new:chat" , {
text : "keep the first draft" , sessionMentions : [], quotedContext : null ,
attachments : [{ path : "/project/video.mp4" , name : "video.mp4" , size : 8 , mime : "video/mp4" , kind : "video" , url : "" }],
});
const onCreateChat = vi . fn (). mockResolvedValue ( "created" );
const shell = ( id : string | null ) => wrap ( client , < ThreadShell session = { id ? session ( id ) : null }
title = "First attachment" draftStore = { store } onToggleSidebar = {() => {}} onCreateChat = { onCreateChat } />);
const view = render ( shell ( null ));
await screen . findByTestId ( "composer-chip" );
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( onCreateChat ). toHaveBeenCalledTimes ( 1 ));
view . rerender ( shell ( "created" ));
await waitFor (() => expect ( screen . getByRole ( "textbox" )). toHaveValue ( "keep the first draft" ));
2026-10-25 22:39:44 +08:00
expect ( within ( await screen . findByTestId ( "composer-chip" )). getByRole ( "button" , { name : "video.mp4" })). toBeVisible ();
2026-10-22 18:32:18 +08:00
expect ( screen . getByRole ( "alert" )). toHaveTextContent ( "file not found" );
2026-10-25 22:39:44 +08:00
expect ( store . get ( "websocket:created" )). toMatchObject ({
text : "keep the first draft" ,
attachments : [{ path : "/project/video.mp4" , name : "video.mp4" , kind : "video" }],
});
2026-10-22 18:32:18 +08:00
expect ( store . has ( "new:chat" )). toBe ( false );
client . sendAttachments . mockResolvedValue ( undefined );
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( screen . queryByTestId ( "composer-chip" )). not . toBeInTheDocument ());
expect ( screen . getByRole ( "textbox" )). toHaveValue ( "" );
expect ( client . sendAttachments ). toHaveBeenCalledTimes ( 2 );
});
2026-09-25 23:42:01 +08:00
it ( "clears the welcome draft after a delayed new-chat send and an unchanged round-trip" , async () => {
const client = makeClient ();
const store = new ComposerDraftStore ();
let completeCreate !: ( id : string ) => void ;
const onCreateChat = vi . fn (() => new Promise < string >(( resolve ) => { completeCreate = resolve ; }));
const shell = ( id : string | null ) => wrap ( client ,
< ThreadShell session = { id ? session ( id ) : null } title = "Draft race" draftStore = { store }
onToggleSidebar = {() => {}} onCreateChat = { onCreateChat } />);
const view = render ( shell ( null ));
fireEvent . change ( screen . getByRole ( "textbox" ), { target : { value : "original first message" } });
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
expect ( onCreateChat ). toHaveBeenCalledTimes ( 1 );
view . rerender ( shell ( "other" ));
view . rerender ( shell ( null ));
expect ( screen . getByRole ( "textbox" )). toHaveValue ( "original first message" );
await act ( async () => {
view . rerender ( shell ( "created" ));
completeCreate ( "created" );
});
await waitFor (() => expect ( client . sendMessage ). toHaveBeenCalledWith (
"created" , "original first message" , undefined , expect . anything ()));
view . unmount ();
expect ( new ComposerDraftStore (). get ( "new:chat" , true )). toBeUndefined ();
});
it . each ([ false , true ])( "restores regular drafts after reload but excludes temporary chats (temporary=%s)" , async ( temporary ) => {
const client = makeClient ();
let draftStore = new ComposerDraftStore ();
draftStore . set ( "websocket:reload-draft" , {
2026-10-22 18:32:18 +08:00
text : "original" , attachments : [], sessionMentions : [], quotedContext : "quoted answer" ,
2026-09-25 23:42:01 +08:00
});
const shell = () => wrap ( client , (
< ThreadShell session = { session ( "reload-draft" )} title = "Reload test" temporary = { temporary }
draftStore = { draftStore } onToggleSidebar = {() => {}} />
));
const first = render ( shell ());
fireEvent . change ( screen . getByRole ( "textbox" ), { target : { value : " unsent draft\n第二行" } });
first . unmount ();
draftStore = new ComposerDraftStore ();
const reloaded = render ( shell ());
expect ( screen . getByRole ( "textbox" )). toHaveValue ( temporary ? "" : " unsent draft\n第二行" );
if ( temporary ) {
expect ( screen . queryByLabelText ( "Quoted context" )). not . toBeInTheDocument ();
} else {
expect ( screen . getByLabelText ( "Quoted context" )). toHaveTextContent ( "quoted answer" );
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( client . sendMessage ). toHaveBeenCalled ());
reloaded . unmount ();
draftStore = new ComposerDraftStore ();
render ( shell ());
expect ( screen . getByRole ( "textbox" )). toHaveValue ( "" );
expect ( screen . queryByLabelText ( "Quoted context" )). not . toBeInTheDocument ();
}
await act ( async () => {});
clearStoredComposerDrafts ();
});
it . each ([ false , true ])( "persists only ordinary new-topic drafts (temporary=%s)" , async ( temporary ) => {
const client = makeClient ();
const shell = () => wrap ( client , (
< ThreadShell session = { null } title = "New topic" temporaryChatEnabled = { temporary }
draftStore = { new ComposerDraftStore ()} onToggleSidebar = {() => {}} />
));
const first = render ( shell ());
fireEvent . change ( screen . getByRole ( "textbox" ), { target : { value : "new topic draft" } });
first . unmount ();
render ( shell ());
expect ( screen . getByRole ( "textbox" )). toHaveValue ( temporary ? "" : "new topic draft" );
await act ( async () => {});
clearStoredComposerDrafts ();
});
it . each ([ false , true ])( "keeps text and quote drafts scoped to the session (temporary=%s)" , async ( temporary ) => {
const client = makeClient ();
const draftStore : ComposerDraftStore = new Map ([
2026-10-22 18:32:18 +08:00
[ "websocket:draft-a" , { text : "draft A" , attachments : [], sessionMentions : [], quotedContext : "quote A" }],
[ "websocket:draft-b" , { text : "draft B" , attachments : [], sessionMentions : [], quotedContext : "quote B" }],
2026-09-25 23:42:01 +08:00
]);
const shell = ( chatId : string ) => wrap ( client , (
< ThreadShell session = { session ( chatId )} title = "Draft test" temporary = { temporary }
draftStore = { draftStore } onToggleSidebar = {() => {}} />
));
const view = render ( shell ( "draft-a" ));
expect ( screen . getByRole ( "textbox" )). toHaveValue ( "draft A" );
expect ( screen . getByLabelText ( "Quoted context" )). toHaveTextContent ( "quote A" );
2026-10-09 17:47:21 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : "Remove quote" }));
2026-09-25 23:42:01 +08:00
view . rerender ( shell ( "draft-b" ));
expect ( screen . getByRole ( "textbox" )). toHaveValue ( "draft B" );
expect ( screen . getByLabelText ( "Quoted context" )). toHaveTextContent ( "quote B" );
view . rerender ( shell ( "draft-a" ));
expect ( screen . getByRole ( "textbox" )). toHaveValue ( "draft A" );
expect ( screen . queryByLabelText ( "Quoted context" )). not . toBeInTheDocument ();
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( client . sendMessage ). toHaveBeenCalled ());
view . rerender ( shell ( "draft-b" ));
view . rerender ( shell ( "draft-a" ));
expect ( screen . getByRole ( "textbox" )). toHaveValue ( "" );
expect ( draftStore . has ( "websocket:draft-a" )). toBe ( false );
await act ( async () => {});
});
2026-11-13 19:16:03 +08:00
it ( "resolves a session command from loaded history outside the visible window" , async () => {
const client = makeClient ();
const id = "012345abcdef" ;
const command = { cmd : "bun run test --token secret-value" };
const sessionArgs = { session_id : id , until_exit : true };
const events = [
{ event : "message" , chat_id : "command-history" , projection_id : "initial-exec" , kind : "progress" ,
text : `exec( ${ JSON . stringify ( command ) } )` , tool_events : [{ name : "exec" , phase : "end" , call_id : "exec-1" , arguments : command ,
result : `Process running. session_id: ${ id } \ nRuntime remaining: 100.0s \ nElapsed: 1.0s \ nInitial wait ended; session remains active.` }] },
... Array . from ({ length : 150 }, ( _ , index ) => ({ event : "user_message" , chat_id : "command-history" ,
projection_id : `old- ${ index } ` , text : `older question ${ index } ` , starts_turn : true })),
{ event : "message" , chat_id : "command-history" , projection_id : "session-call" , kind : "progress" ,
text : `exec_session( ${ JSON . stringify ( sessionArgs ) } )` , tool_events : [{ name : "exec_session" , phase : "end" ,
call_id : "poll-1" , arguments : sessionArgs , result : "Exit code: 0\nElapsed: 2.0s" }] },
{ event : "message" , chat_id : "command-history" , projection_id : "final-answer" , text : "Command answer" },
];
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => String ( input ). includes ( "/webui-thread" )
? Promise . resolve ( httpJson ({ schemaVersion : 3 , projection : "events" , events }))
: Promise . resolve ({ ok : false , status : 404 , json : async () => ({}) })));
render ( wrap ( client , < ThreadShell session = { session ( "command-history" )} title = "Command history" onToggleSidebar = {() => {}} />));
const menu = await openMessageActions ( "Command answer" );
fireEvent . click ( within ( menu ). getByRole ( "button" , { name : /Worked/ }));
await waitFor (() => expect ( document . body ). toHaveTextContent ( "Command completed bun run test --token ••••" ));
expect ( document . body ). not . toHaveTextContent ( id );
expect ( document . body ). not . toHaveTextContent ( "secret-value" );
expect ( screen . queryByText ( "older question 0" )). not . toBeInTheDocument ();
});
2026-09-12 04:37:37 +08:00
it ( "surfaces and retries a deferred trace-detail request failure" , async () => {
const client = makeClient ();
let detailCalls = 0 ;
const fetchMock = vi . fn (( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "/webui-thread/trace-detail?" )) {
detailCalls += 1 ;
if ( detailCalls === 1 ) {
return Promise . resolve ({ ok : false , status : 500 , json : async () => ({}) });
}
return Promise . resolve ( httpJson ({
2026-09-20 16:48:13 +08:00
message_id : "history-aaaaaaaaaaaaaaaaaaaa" ,
events : [{
event : "message" ,
chat_id : "trace-detail-retry" ,
projection_id : "trace-deferred" ,
kind : "progress" ,
text : 'exec({"command":"echo full"})' ,
}],
2026-09-12 04:37:37 +08:00
}));
}
if ( url . includes ( "websocket%3Atrace-detail-retry/webui-thread" )) {
return Promise . resolve ( httpJson ({
schemaVersion : 3 ,
messages : [
{
id : "trace-deferred" ,
role : "tool" ,
kind : "trace" ,
content : "exec(…)" ,
traces : [ "exec(…)" ],
2026-09-20 16:48:13 +08:00
traceDetail : {
ref : "1.history-aaaaaaaaaaaaaaaaaaaa" ,
bytes : 40_000 ,
traceCount : 1 ,
},
2026-09-12 04:37:37 +08:00
createdAt : 1_000 ,
},
{ id : "answer" , role : "assistant" , content : "done" , createdAt : 2_000 },
],
}));
}
return Promise . resolve ({ ok : false , status : 404 , json : async () => ({}) });
});
vi . stubGlobal ( "fetch" , fetchMock );
render ( wrap (
client ,
< ThreadShell
session = { session ( "trace-detail-retry" )}
title = "Trace detail retry"
onToggleSidebar = {() => {}}
/>,
));
2026-09-22 16:37:35 +08:00
const menu = await openMessageActions ( "done" );
const activity = within ( menu ). getByRole ( "button" , { name : /Worked/ });
2026-09-12 04:37:37 +08:00
fireEvent . click ( activity );
expect ( await screen . findByRole ( "alert" )). toHaveTextContent (
"Full activity details could not be loaded." ,
);
expect ( detailCalls ). toBe ( 1 );
fireEvent . click ( screen . getByRole ( "button" , { name : "Retry" }));
await waitFor (() => expect ( detailCalls ). toBe ( 2 ));
await waitFor (() => expect ( screen . queryByRole ( "alert" )). not . toBeInTheDocument ());
2026-09-20 16:48:13 +08:00
await waitFor (() => expect ( document . body ). toHaveTextContent ( "echo full" ));
2026-09-12 04:37:37 +08:00
2026-09-22 16:37:35 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : /Collapse activity details/ }));
const reopenedMenu = await openMessageActions ( "done" );
fireEvent . click ( within ( reopenedMenu ). getByRole ( "button" , { name : /Worked/ }));
2026-09-12 04:37:37 +08:00
await act ( async () => Promise . resolve ());
expect ( detailCalls ). toBe ( 2 );
});
2026-11-13 19:16:03 +08:00
it . each ([ false , true ])( "hydrates deferred activity in an independently paged navigation window (fragment=%s)" , async ( fragment ) => {
2026-10-18 14:57:23 +08:00
const client = makeClient ();
2026-11-13 19:16:03 +08:00
const id = "012345abcdef" ;
let detailCalls = 0 ;
2026-10-18 14:57:23 +08:00
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "/prompts" )) return Promise . resolve ( httpJson ({ prompts : [{
id : "old-user" , preview : "Old question" , answerPreview : "old answer" , createdAt : 1 ,
cursor : "0" , turnId : "old-turn" ,
}] }));
2026-11-13 19:16:03 +08:00
if ( url . includes ( "/trace-detail?" )) {
detailCalls += 1 ;
return Promise . resolve ( httpJson ({
message_id : "history-aaaaaaaaaaaaaaaaaaaa" , events : [{
event : "message" , chat_id : "trace-navigation" , projection_id : "old-trace" , kind : "progress" ,
text : 'exec({"command":"echo historical"})' ,
tool_events : [{ name : "exec" , phase : "end" , call_id : "navigation-exec" ,
arguments : { command : "echo historical" },
result : `Process running. session_id: ${ id } \ nRuntime remaining: 100.0s \ nElapsed: 1.0s \ nInitial wait ended; session remains active.` }],
}],
}));
}
2026-10-18 14:57:23 +08:00
if ( url . includes ( "after=0" )) return Promise . resolve ( httpJson ({
schemaVersion : 3 , projection : "events" , events : [
{ event : "user_message" , chat_id : "trace-navigation" , projection_id : "old-user" , text : "Old question" , starts_turn : true },
{ event : "message" , chat_id : "trace-navigation" , projection_id : "old-trace" , kind : "progress" , text : "exec(…)" ,
trace_detail : { ref : "1.history-aaaaaaaaaaaaaaaaaaaa" , bytes : 40_000 , traceCount : 1 } },
2026-11-13 19:16:03 +08:00
{ event : "message" , chat_id : "trace-navigation" , projection_id : "old-check" , kind : "progress" ,
text : `exec_session({"session_id":" ${ id } "})` ,
tool_events : [{ name : "exec_session" , phase : "end" , call_id : "navigation-check" ,
arguments : { session_id : id }, result : "Exit code: 0\nElapsed: 2.0s" }] },
2026-10-18 14:57:23 +08:00
{ event : "message" , chat_id : "trace-navigation" , projection_id : "old-answer" , text : "old answer" },
2026-11-13 19:16:03 +08:00
], page : { user_message_offset : 0 , has_more_before : false , has_more_after : true , after_cursor : "1" ,
...( fragment ? { history_generation : "generation-a" , record_range : { turn : 0 , start : 0 , end : 4 } } : {}) },
2026-10-18 14:57:23 +08:00
}));
if ( url . includes ( "/webui-thread" )) return Promise . resolve ( httpJson ({
schemaVersion : 3 , messages : [{ id : "latest-answer" , role : "assistant" , content : "latest answer" , createdAt : 100 }],
}));
return Promise . resolve ({ ok : false , status : 404 , json : async () => ({}) });
}));
render ( wrap ( client , < ThreadShell session = { session ( "trace-navigation" )} title = "Trace navigation" onToggleSidebar = {() => {}} />,
null , "tok" , [ "webui.prompt-navigation.v1" ]));
await screen . findByText ( "latest answer" );
fireEvent . click ( await screen . findByRole ( "button" , { name : "Message navigation" }));
fireEvent . click ( within ( screen . getByRole ( "dialog" )). getByRole ( "button" , { name : "Jump to message: Old question" }));
await screen . findByText ( "old answer" );
const menu = await openMessageActions ( "old answer" );
fireEvent . click ( within ( menu ). getByRole ( "button" , { name : /Worked/ }));
2026-11-13 19:16:03 +08:00
await waitFor (() => expect ( document . body ). toHaveTextContent ( "Command completed echo historical" ));
expect ( detailCalls ). toBe ( 1 );
expect ( document . body ). not . toHaveTextContent ( id );
2026-10-18 14:57:23 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : "Scroll to bottom" }));
await screen . findByText ( "latest answer" );
expect ( screen . queryByText ( "old answer" )). not . toBeInTheDocument ();
});
2026-11-13 19:16:03 +08:00
it ( "starts a fresh trace-detail read after leaving and returning to the same chat" , async () => {
const client = makeClient ();
let resolveOld !: ( response : Response ) => void ;
const oldRequest = new Promise < Response >(( resolve ) => { resolveOld = resolve ; });
let detailCalls = 0 ;
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "/webui-thread/trace-detail?" )) {
detailCalls += 1 ;
if ( detailCalls === 1 ) return oldRequest ;
return Promise . resolve ( httpJson ({ message_id : "history-aaaaaaaaaaaaaaaaaaaa" , events : [{
event : "message" , chat_id : "detail-return-a" , projection_id : "trace-shared" , kind : "progress" ,
text : 'exec({"command":"echo fresh"})' ,
}] }));
}
if ( url . includes ( "websocket%3Adetail-return-a/webui-thread" )) return Promise . resolve ( httpJson ( traceDetailThread ( true , "answer-a" )));
if ( url . includes ( "websocket%3Adetail-return-b/webui-thread" )) return Promise . resolve ( httpJson ( traceDetailThread ( false , "answer-b" )));
return Promise . resolve ({ ok : false , status : 404 , json : async () => ({}) });
}));
const view = ( chatId : string ) => wrap ( client ,
< ThreadShell session = { session ( chatId )} title = "Detail return" onToggleSidebar = {() => {}} />);
const { rerender } = render ( view ( "detail-return-a" ));
fireEvent . click ( within ( await openMessageActions ( "answer-a" )). getByRole ( "button" , { name : /Worked/ }));
await waitFor (() => expect ( detailCalls ). toBe ( 1 ));
rerender ( view ( "detail-return-b" ));
await screen . findByText ( "answer-b" );
rerender ( view ( "detail-return-a" ));
fireEvent . click ( within ( await openMessageActions ( "answer-a" )). getByRole ( "button" , { name : /Worked/ }));
await waitFor (() => expect ( detailCalls ). toBe ( 2 ));
await waitFor (() => expect ( document . body ). toHaveTextContent ( "echo fresh" ));
await act ( async () => resolveOld ( httpJson ({ message_id : "history-aaaaaaaaaaaaaaaaaaaa" , events : [{
event : "message" , chat_id : "detail-return-a" , projection_id : "trace-shared" , kind : "progress" ,
text : 'exec({"command":"echo stale"})' ,
}] })));
expect ( document . body ). not . toHaveTextContent ( "echo stale" );
});
2026-09-12 04:37:37 +08:00
it ( "ignores a deferred trace-detail failure after switching sessions" , async () => {
const client = makeClient ();
const detailUrls : string [] = [];
let rejectDetail !: ( reason : Error ) => void ;
const pendingDetail = new Promise < Response >(( _resolve , reject ) => {
rejectDetail = reject ;
});
const cachedB = traceDetailThread ( false , "done-b" , "rev-b" );
webuiThreadCache . set ( "websocket:trace-failure-b" , cachedB );
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "/webui-thread/trace-detail?" )) {
detailUrls . push ( url );
return pendingDetail ;
}
if ( url . includes ( "websocket%3Atrace-failure-a/webui-thread" )) {
return Promise . resolve ( httpJson ( traceDetailThread ( true , "done-a" )));
}
if ( url . includes ( "websocket%3Atrace-failure-b/webui-thread" )) {
return Promise . resolve ( httpJson ( cachedB ));
}
return Promise . resolve ({ ok : false , status : 404 , json : async () => ({}) });
}));
const view = ( chatId : string ) => wrap (
client ,
< ThreadShell
session = { session ( chatId )}
title = { `Trace ${ chatId } ` }
onToggleSidebar = {() => {}}
/>,
);
const { rerender } = render ( view ( "trace-failure-a" ));
2026-09-22 16:37:35 +08:00
fireEvent . click ( within ( await openMessageActions ( "done-a" )). getByRole ( "button" , { name : /Worked/ }));
2026-09-12 04:37:37 +08:00
rerender ( view ( "trace-failure-b" ));
await screen . findByText ( "done-b" );
await act ( async () => rejectDetail ( new Error ( "late failure" )));
expect ( detailUrls ). toHaveLength ( 1 );
expect ( detailUrls [ 0 ]). toContain ( "websocket%3Atrace-failure-a" );
expect ( screen . queryByRole ( "alert" )). not . toBeInTheDocument ();
});
it ( "does not carry a visible trace-detail failure into a cached session" , async () => {
const client = makeClient ();
const detailUrls : string [] = [];
const cachedB = traceDetailThread ( false , "cached-b" , "rev-visible-b" );
webuiThreadCache . set ( "websocket:visible-failure-b" , cachedB );
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "/webui-thread/trace-detail?" )) {
detailUrls . push ( url );
return Promise . resolve ({ ok : false , status : 500 , json : async () => ({}) });
}
if ( url . includes ( "websocket%3Avisible-failure-a/webui-thread" )) {
return Promise . resolve ( httpJson ( traceDetailThread ( true , "failed-a" )));
}
if ( url . includes ( "websocket%3Avisible-failure-b/webui-thread" )) {
return Promise . resolve ( httpJson ( cachedB ));
}
return Promise . resolve ({ ok : false , status : 404 , json : async () => ({}) });
}));
const view = ( chatId : string ) => wrap (
client ,
< ThreadShell
session = { session ( chatId )}
title = { `Trace ${ chatId } ` }
onToggleSidebar = {() => {}}
/>,
);
const { rerender } = render ( view ( "visible-failure-a" ));
2026-09-22 16:37:35 +08:00
fireEvent . click ( within ( await openMessageActions ( "failed-a" )). getByRole ( "button" , { name : /Worked/ }));
2026-09-12 04:37:37 +08:00
expect ( await screen . findByRole ( "alert" )). toBeInTheDocument ();
rerender ( view ( "visible-failure-b" ));
await screen . findByText ( "cached-b" );
expect ( detailUrls ). toHaveLength ( 1 );
expect ( detailUrls [ 0 ]). toContain ( "websocket%3Avisible-failure-a" );
expect ( screen . queryByRole ( "alert" )). not . toBeInTheDocument ();
});
2026-11-05 17:09:20 +08:00
it ( "shows legacy history usage and clears it after successful compaction" , async () => {
2026-09-04 15:13:17 +08:00
const client = makeClient ();
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => {
if ( String ( input ). includes ( "websocket%3Ausage-chart/webui-thread" )) {
return Promise . resolve ( httpJson ({
schemaVersion : 3 ,
messages : [
{
id : "assistant-1" ,
role : "assistant" ,
content : "First response" ,
turnId : "turn-1" ,
createdAt : 1_000 ,
usage : {
prompt_tokens : 18_000 ,
completion_tokens : 280 ,
cached_tokens : 12_000 ,
request_count : 2 ,
},
roundUsages : [
{ prompt_tokens : 8_000 , completion_tokens : 120 , cached_tokens : 2_000 },
{ prompt_tokens : 10_000 , completion_tokens : 160 , cached_tokens : 10_000 },
],
},
{
id : "assistant-2" ,
role : "assistant" ,
content : "Second response" ,
turnId : "turn-2" ,
createdAt : 2_000 ,
contextWindowTokens : 65_536 ,
usage : {
prompt_tokens : 29_400 ,
completion_tokens : 416 ,
cached_tokens : 26_180 ,
context_tokens : 14_700 ,
request_count : 2 ,
},
roundUsages : [
{ prompt_tokens : 13_000 , completion_tokens : 180 , cached_tokens : 10_000 },
{ prompt_tokens : 16_400 , completion_tokens : 236 , cached_tokens : 16_180 },
],
},
] satisfies UIMessage [],
}));
}
return Promise . resolve ({
ok : false ,
status : 404 ,
json : async () => ({}),
});
}));
render ( wrap (
client ,
< ThreadShell
session = { session ( "usage-chart" )}
title = "Usage chart"
onToggleSidebar = {() => {}}
settingsSnapshot = { modelSettings ( "openai-codex/gpt-5.5" , "openai_codex" )}
/>,
"openai-codex/gpt-5.5" ,
));
const trigger = await screen . findByTestId ( "composer-context-usage" );
fireEvent . click ( trigger );
2026-11-05 17:09:20 +08:00
expect ( screen . getByRole ( "progressbar" , { name : "Context" })). toHaveAttribute ( "aria-valuenow" , "22" );
expect ( screen . getByRole ( "button" , { name : "Play context history" })). toBeDisabled ();
2026-09-08 13:16:45 +08:00
expect ( screen . getByTestId ( "composer-context-meter" )). toBeInTheDocument ();
for ( const phase of [ "started" , "failed" ] as const ) {
act (() => client . _emitChat ( "usage-chart" , {
event : "context_compaction" , chat_id : "usage-chart" , compaction_id : "failed" , phase ,
}));
expect ( screen . getByTestId ( "composer-context-meter" )). toBeInTheDocument ();
}
act (() => client . _emitChat ( "usage-chart" , {
event : "context_compaction" , chat_id : "usage-chart" ,
compaction_id : "success" , phase : "succeeded" ,
}));
2026-11-06 11:31:42 +08:00
expect ( screen . getByTestId ( "composer-context-usage" )). toHaveAttribute ( "aria-expanded" , "true" );
expect ( screen . getByRole ( "progressbar" , { name : "Context" })). not . toHaveAttribute ( "aria-valuenow" );
fireEvent . click ( screen . getByTestId ( "composer-context-usage" ));
2026-11-05 17:09:20 +08:00
await waitFor (() => expect ( screen . queryByTestId ( "composer-context-usage" )). not . toBeInTheDocument ());
2026-09-08 13:16:45 +08:00
});
2026-11-06 22:50:07 +08:00
it ( "closes the context sidebar when starting a new conversation" , async () => {
const client = makeClient ();
const envelope = { chat_id : "live-usage" , turn_id : "live-turn" };
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => Promise . resolve (
String ( input ). includes ( "websocket%3Alive-usage/webui-thread" )
? httpJson ({ schemaVersion : 3 , projection : "events" , active_turn_id : "live-turn" , has_pending_tool_calls : true ,
events : [{ ... envelope , event : "user_message" , text : "Waiting for answer" , starts_turn : true , turn_seq : 0 }] })
: { ok : false , status : 404 , json : async () => ({}) },
)));
const footer = document . createElement ( "div" );
document . body . append ( footer );
const view = render ( wrap ( client , < ThreadShell composerPortalTarget = { footer }
session = { session ( "live-usage" )} title = "Live usage" onToggleSidebar = {() => {}}
settingsSnapshot = { modelSettings ( "test-model" , "deepseek" )} />));
await screen . findByText ( "Waiting for answer" );
act (() => client . _emitChat ( "live-usage" , { ... envelope , event : "model_request" , request_id : "first" , run_id : "run" ,
phase : "completed" , sequence : 1 , turn_seq : 1 , context_window_tokens : 1000 ,
usage : { prompt_tokens : 100 , context_tokens : 100 },
context_graph : { nodes : [{ path : "/first.md" , name : "first.md" , state : "loaded" , tokens : 40 }], edges : [] },
}));
const trigger = await screen . findByTestId ( "composer-context-usage" );
const host = document . querySelector ( ".thread-preview-layout" ) ! ;
Object . defineProperty ( host , "clientWidth" , { value : 1000 });
fireEvent ( window , new Event ( "resize" ));
fireEvent . click ( trigger );
expect ( await screen . findByRole ( "button" , { name : "first.md" })). toBeInTheDocument ();
expect ( screen . getByTestId ( "context-sidebar" )). toBeInTheDocument ();
await act ( async () => view . rerender ( wrap ( client , < ThreadShell composerPortalTarget = { footer }
session = { null } title = "New conversation" onToggleSidebar = {() => {}}
settingsSnapshot = { modelSettings ( "test-model" , "deepseek" )} />)));
await waitFor (() => expect ( screen . queryByTestId ( "context-sidebar" )). not . toBeInTheDocument ());
expect ( footer ). toContainElement ( screen . getByRole ( "textbox" ));
footer . remove ();
});
2026-11-06 11:31:42 +08:00
it . each ([ false , true ])( "switches context in the same side slot unless multiple panes are visible (%s)" , async ( multiplePanes ) => {
2026-11-05 17:20:22 +08:00
const geometry = vi . spyOn ( HTMLElement . prototype , "getBoundingClientRect" ). mockImplementation ( function ( this : HTMLElement ) {
const bottom = this . classList . contains ( "thread-preview-layout" ) ? 900
: this.classList.contains ( "thread-composer-surface" ) && this . isConnected ? 880 : 0 ;
return DOMRect . fromRect ({ x : 0 , y : 0 , width : 1000 , height : bottom });
});
const client = makeClient ();
const envelope = { chat_id : "live-usage" , turn_id : "live-turn" };
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => Promise . resolve (
String ( input ). includes ( "websocket%3Alive-usage/webui-thread" )
? httpJson ({ schemaVersion : 3 , projection : "events" , active_turn_id : "live-turn" , has_pending_tool_calls : true ,
events : [{ ... envelope , event : "user_message" , text : "Waiting for answer" , starts_turn : true , turn_seq : 0 }] })
: { ok : false , status : 404 , json : async () => ({}) },
)));
const footer = document . createElement ( "div" );
document . body . append ( footer );
const view = render ( wrap ( client , < ThreadShell
2026-11-06 11:31:42 +08:00
composerPortalTarget = { footer } multiplePanes = { multiplePanes }
2026-11-05 17:20:22 +08:00
session = { session ( "live-usage" )} title = "Live usage" onToggleSidebar = {() => {}}
settingsSnapshot = { modelSettings ( "test-model" , "deepseek" )}
/>));
await screen . findByText ( "Waiting for answer" );
act (() => client . _emitChat ( "live-usage" , { ... envelope , event : "model_request" , request_id : "first" , run_id : "run" ,
phase : "completed" , sequence : 1 , turn_seq : 1 , context_window_tokens : 1000 ,
usage : { prompt_tokens : 100 , completion_tokens : 10 , context_tokens : 100 , request_count : 1 },
round_usages : [{ prompt_tokens : 100 , completion_tokens : 10 }],
context_graph : { nodes : [{ path : "/first.md" , name : "first.md" , state : "loaded" , tokens : 40 }], edges : [] },
}));
const trigger = await screen . findByTestId ( "composer-context-usage" );
const input = screen . getByRole ( "textbox" );
expect ( footer ). toContainElement ( input );
const host = document . querySelector ( ".thread-preview-layout" ) ! ;
Object . defineProperty ( host , "clientWidth" , { value : 1000 });
fireEvent ( window , new Event ( "resize" ));
fireEvent . click ( trigger );
expect ( await screen . findByRole ( "button" , { name : "first.md" })). toBeInTheDocument ();
expect (( host as HTMLElement ). style . getPropertyValue ( "--sidebar-bottom-inset" )). toBe ( "20px" );
2026-11-06 11:31:42 +08:00
const sidebar = screen . getByTestId ( "context-sidebar" );
2026-11-05 17:20:22 +08:00
await act ( async () => view . rerender ( wrap ( client , < ThreadShell
2026-11-06 11:31:42 +08:00
composerPortalTarget = { footer } multiplePanes = { multiplePanes }
2026-11-05 17:20:22 +08:00
session = { session ( "other-usage" )} title = "Other usage" onToggleSidebar = {() => {}}
settingsSnapshot = { modelSettings ( "test-model" , "deepseek" )}
/>)));
2026-11-06 11:31:42 +08:00
expect ( screen . queryByRole ( "button" , { name : "first.md" })). not . toBeInTheDocument ();
if ( ! multiplePanes ) {
expect ( screen . getByTestId ( "context-sidebar" )). toBe ( sidebar );
expect ( screen . getByRole ( "progressbar" , { name : "Context" })). not . toHaveAttribute ( "aria-valuenow" );
expect (( host as HTMLElement ). style . getPropertyValue ( "--sidebar-bottom-inset" )). toBe ( "20px" );
}
2026-11-05 17:20:22 +08:00
act (() => client . _emitChat ( "other-usage" , {
event : "model_request" , chat_id : "other-usage" , turn_id : "other-turn" , request_id : "other" , run_id : "other-run" ,
phase : "completed" , sequence : 1 , turn_seq : 1 , context_window_tokens : 1000 ,
usage : { prompt_tokens : 200 , context_tokens : 200 },
2026-11-06 11:31:42 +08:00
request_usage : { prompt_tokens : 200 , context_tokens : 200 },
2026-11-05 17:20:22 +08:00
context_graph : { nodes : [{ path : "/other.md" , name : "other.md" , state : "loaded" , tokens : 60 }], edges : [] },
}));
const newInput = screen . getByRole ( "textbox" );
expect ( newInput ). not . toBe ( input );
2026-11-06 11:31:42 +08:00
if ( multiplePanes ) {
await waitFor (() => expect ( screen . queryByTestId ( "context-sidebar" )). not . toBeInTheDocument ());
expect ( host ). not . toHaveAttribute ( "data-preview-open" );
expect ( footer ). toContainElement ( newInput );
fireEvent . click ( screen . getByTestId ( "composer-context-usage" ));
} else {
expect ( screen . getByTestId ( "context-sidebar" )). toBe ( sidebar );
}
2026-11-05 17:20:22 +08:00
expect ( await screen . findByRole ( "button" , { name : "other.md" })). toBeInTheDocument ();
expect (( host as HTMLElement ). style . getPropertyValue ( "--sidebar-bottom-inset" )). toBe ( "20px" );
2026-11-06 11:31:42 +08:00
expect ( screen . getByRole ( "progressbar" , { name : "Context" })). toHaveAttribute ( "aria-valuenow" , "20" );
2026-11-05 17:20:22 +08:00
expect ( host . querySelector ( ".thread-conversation" )). toContainElement ( newInput );
2026-11-06 11:31:42 +08:00
fireEvent . click ( screen . getByTestId ( "composer-context-usage" ));
await waitFor (() => expect ( screen . queryByTestId ( "context-sidebar" )). not . toBeInTheDocument ());
await act ( async () => view . rerender ( wrap ( client , < ThreadShell
composerPortalTarget = { footer } multiplePanes = { multiplePanes }
session = { session ( "live-usage" )} title = "Live usage" onToggleSidebar = {() => {}}
settingsSnapshot = { modelSettings ( "test-model" , "deepseek" )}
/>)));
expect ( host ). not . toHaveAttribute ( "data-preview-open" );
expect ( screen . queryByTestId ( "context-sidebar" )). not . toBeInTheDocument ();
2026-11-05 17:20:22 +08:00
view . unmount ();
footer . remove ();
geometry . mockRestore ();
});
2026-11-04 16:27:24 +08:00
it ( "updates composer usage from active model snapshots without changing the body" , async () => {
const client = makeClient ();
const envelope = { chat_id : "live-usage" , turn_id : "live-turn" };
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => Promise . resolve (
String ( input ). includes ( "websocket%3Alive-usage/webui-thread" )
? httpJson ({ schemaVersion : 3 , projection : "events" , active_turn_id : "live-turn" , has_pending_tool_calls : true ,
events : [{ ... envelope , event : "user_message" , text : "Waiting for answer" , starts_turn : true , turn_seq : 0 }] })
: { ok : false , status : 404 , json : async () => ({}) },
)));
2026-11-05 17:09:20 +08:00
const footer = document . createElement ( "div" );
document . body . append ( footer );
const view = render ( wrap ( client , < ThreadShell
composerPortalTarget = { footer }
2026-11-04 16:27:24 +08:00
session = { session ( "live-usage" )} title = "Live usage" onToggleSidebar = {() => {}}
settingsSnapshot = { modelSettings ( "test-model" , "deepseek" )}
/>));
await screen . findByText ( "Waiting for answer" );
act (() => client . _emitChat ( "live-usage" , { ... envelope , event : "model_request" , request_id : "first" , run_id : "run" ,
phase : "completed" , sequence : 1 , turn_seq : 1 , context_window_tokens : 1000 ,
usage : { prompt_tokens : 100 , completion_tokens : 10 , context_tokens : 100 , request_count : 1 },
round_usages : [{ prompt_tokens : 100 , completion_tokens : 10 }],
2026-11-05 17:09:20 +08:00
context_graph : { nodes : [{ path : "/first.md" , name : "first.md" , state : "loaded" , tokens : 40 }], edges : [] },
2026-11-04 16:27:24 +08:00
}));
const trigger = await screen . findByTestId ( "composer-context-usage" );
expect ( trigger ). toHaveAccessibleName ( "Context 10%. Open context usage" );
act (() => client . _emitChat ( "live-usage" , { ... envelope , event : "model_request" , request_id : "second" , run_id : "run" ,
phase : "completed" , sequence : 2 , turn_seq : 2 , context_window_tokens : 1000 ,
usage : { prompt_tokens : 300 , completion_tokens : 20 , context_tokens : 200 , request_count : 2 },
round_usages : [{ prompt_tokens : 100 , completion_tokens : 10 }, { prompt_tokens : 200 , completion_tokens : 10 }],
2026-11-05 17:09:20 +08:00
context_graph : { nodes : [{ path : "/second.md" , name : "second.md" , state : "loaded" , tokens : 60 }], edges : [] },
2026-11-04 16:27:24 +08:00
}));
expect ( trigger ). toHaveAccessibleName ( "Context 20%. Open context usage" );
2026-11-05 17:09:20 +08:00
const input = screen . getByRole ( "textbox" );
expect ( footer ). toContainElement ( input );
fireEvent . change ( input , { target : { value : "Preserve this draft" } });
const host = document . querySelector ( ".thread-preview-layout" ) ! ;
Object . defineProperty ( host , "clientWidth" , { value : 1000 });
fireEvent ( window , new Event ( "resize" ));
act (() => input . focus ());
2026-11-04 16:27:24 +08:00
fireEvent . click ( trigger );
2026-11-05 17:09:20 +08:00
expect ( host . querySelector ( ".thread-conversation" )). toContainElement ( input );
expect ( footer ). not . toContainElement ( input );
expect ( input ). toHaveValue ( "Preserve this draft" );
expect ( input ). toHaveFocus ();
expect ( screen . getByRole ( "progressbar" , { name : "Context" })). toHaveAttribute ( "aria-valuenow" , "20" );
expect ( await screen . findByRole ( "button" , { name : "second.md" })). toBeInTheDocument ();
expect ( screen . getByRole ( "button" , { name : "Play context history" })). toBeEnabled ();
2026-11-04 16:27:24 +08:00
expect ( screen . getByText ( "Waiting for answer" )). toBeInTheDocument ();
2026-11-05 17:09:20 +08:00
const sidebar = screen . getByTestId ( "context-sidebar" );
2026-11-07 18:18:19 +08:00
// HappyDOM has no CSS timeline; retain a real pending exit for the close assertions.
let finishExit !: () => void ;
const finished = new Promise < void >(( resolve ) => { finishExit = resolve ; });
Object . defineProperty ( sidebar , "getAnimations" , { value : () => [{ finished }] });
2026-11-05 17:09:20 +08:00
fireEvent . click ( trigger );
expect ( screen . getByTestId ( "context-sidebar" )). toBe ( sidebar );
expect ( sidebar ). toHaveAttribute ( "data-closing" );
expect ( footer ). toContainElement ( input );
expect ( input ). toHaveValue ( "Preserve this draft" );
2026-11-07 18:18:19 +08:00
await act ( async () => finishExit ());
2026-11-05 17:09:20 +08:00
await waitFor (() => expect ( screen . queryByTestId ( "context-sidebar" )). not . toBeInTheDocument ());
view . unmount ();
footer . remove ();
2026-11-04 16:27:24 +08:00
});
2026-09-08 13:16:45 +08:00
it . each ([ false , true ])( "restores context after compaction only with newer usage (%s)" , async ( newReply ) => {
const client = makeClient ();
const messages : UIMessage [] = [
{
id : "old" , role : "assistant" , content : "Before compact" , createdAt : 1_000 ,
contextWindowTokens : 1_000_000 , usage : { context_tokens : 170_000 },
roundUsages : [{ prompt_tokens : 170_000 }],
},
{
id : "compact" , role : "assistant" , kind : "compaction" , content : "" , createdAt : 2_000 ,
compaction : { id : "compact" , phase : "succeeded" },
},
];
if ( newReply ) messages . push ({
id : "new" , role : "assistant" , content : "After compact" , createdAt : 3_000 ,
contextWindowTokens : 1_000_000 , usage : { context_tokens : 20_700 },
});
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => Promise . resolve (
String ( input ). includes ( "websocket%3Acompact-usage/webui-thread" )
? httpJson ({ schemaVersion : 3 , messages })
: { ok : false , status : 404 , json : async () => ({}) },
)));
render ( wrap ( client , < ThreadShell
session = { session ( "compact-usage" )} title = "Compact usage" onToggleSidebar = {() => {}}
settingsSnapshot = { modelSettings ( "test-model" , "deepseek" )}
/>));
2026-11-05 17:09:20 +08:00
await screen . findByText ( "Before compact" );
2026-09-08 13:16:45 +08:00
if ( newReply ) {
2026-11-05 17:09:20 +08:00
const trigger = await screen . findByTestId ( "composer-context-usage" );
2026-09-08 13:16:45 +08:00
expect ( trigger ). toHaveAccessibleName ( "Context 2%. Open context usage" );
} else {
2026-11-05 17:09:20 +08:00
expect ( screen . queryByTestId ( "composer-context-usage" )). not . toBeInTheDocument ();
2026-09-08 13:16:45 +08:00
}
2026-09-04 15:13:17 +08:00
});
2026-08-25 01:55:58 +08:00
it ( "moves the session handle into the pane only when the workbench is split" , () => {
const client = makeClient ();
const portal = document . createElement ( "div" );
document . body . append ( portal );
const activeSession = {
... session ( "pane-handle" ),
handle : {
id : "handle_11111111111111111111111111111111" ,
name : "soro" ,
},
};
const { unmount } = render ( wrap (
client ,
< ThreadShell
session = { activeSession }
title = "Single pane"
onToggleSidebar = {() => {}}
hideHeaderTitle
headerPortalTarget = { portal }
/>,
));
2026-09-10 13:27:01 +08:00
expect ( within ( portal ). queryByText ( "@soro" )). not . toBeInTheDocument ();
2026-08-25 01:55:58 +08:00
expect ( screen . queryByLabelText ( "Session @soro" )). not . toBeInTheDocument ();
unmount ();
const splitView = render ( wrap (
client ,
< ThreadShell
session = { activeSession }
title = "Split pane"
onToggleSidebar = {() => {}}
hideHeaderTitle
inlineHandle
headerPortalTarget = { portal }
/>,
));
expect ( screen . getByLabelText ( "Session @soro" )). toHaveTextContent ( "@soro" );
expect ( within ( portal ). queryByText ( "@soro" )). not . toBeInTheDocument ();
splitView . unmount ();
portal . remove ();
});
2026-10-27 09:40:44 +08:00
it . each ([
{ kind : "inferred" , content : "Unreadable file: `prompts/dream.md`" , path : "prompts/dream.md" },
{ kind : "explicit" , content : "[Python code](/ home/example/workspace/model_check.py)" , path : "/ home/example/workspace/model_check.py" },
])( "keeps $kind file references non-interactive when the availability probe fails" , async ({ content , path }) => {
2026-07-22 22:35:39 +08:00
await preloadMarkdownText ();
2026-07-15 10:45:40 +08:00
const client = makeClient ();
let resolveProbe !: ( value : Response ) => void ;
const probe = new Promise < Response >(( resolve ) => {
resolveProbe = resolve ;
});
const fetchMock = vi . fn (( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Apreview-error/webui-thread" )) {
return Promise . resolve ( httpJson ( transcriptFromSimpleMessages ([
2026-10-27 09:40:44 +08:00
{ role : "assistant" , content },
2026-07-15 10:45:40 +08:00
])));
}
if ( url . includes ( "websocket%3Apreview-error/file-preview?" )) return probe ;
return Promise . resolve ({
ok : false ,
status : 404 ,
json : async () => ({}),
});
});
vi . stubGlobal ( "fetch" , fetchMock );
render ( wrap (
client ,
< ThreadShell
session = { session ( "preview-error" )}
title = "Preview error"
onToggleSidebar = {() => {}}
/>,
));
const reference = await screen . findByTestId ( "inline-file-path" );
await waitFor (() => expect ( fetchMock ). toHaveBeenCalledWith (
2026-10-27 09:40:44 +08:00
expect . stringContaining ( `file-preview?path= ${ encodeURIComponent ( path ) } &probe=1` ),
2026-07-15 10:45:40 +08:00
expect . anything (),
));
await act ( async () => {
resolveProbe ({
ok : false ,
status : 500 ,
text : async () => "failed to read file" ,
json : async () => ({}),
} as Response );
await probe ;
await Promise . resolve ();
});
expect ( reference ). not . toHaveAttribute ( "role" );
expect ( reference ). not . toHaveAttribute ( "tabindex" );
fireEvent . click ( reference );
expect ( screen . queryByText ( "failed to read file" )). not . toBeInTheDocument ();
});
2026-08-13 16:25:37 +08:00
it ( "hides actions for a complete assistant-only message until turn_end" , async () => {
const client = makeClient ();
vi . mocked ( fetch ). mockImplementation ( async ( input ) => (
String ( input ). includes ( "websocket%3Aassistant-only-actions/webui-thread" )
? httpJson ( transcriptFromSimpleMessages ([
{ role : "assistant" , content : "old automation" , turnId : "turn-old" },
]))
: { ok : false , status : 404 , json : async () => ({}) }
) as Response );
render ( wrap (
client ,
< ThreadShell
session = { session ( "assistant-only-actions" )}
title = "Assistant-only actions"
onToggleSidebar = {() => {}}
/>,
));
2026-09-22 16:37:35 +08:00
const oldMenu = await openMessageActions ( "old automation" );
expect ( within ( oldMenu ). getByRole ( "button" , { name : "Copy" })). toBeInTheDocument ();
2026-08-13 16:25:37 +08:00
const turnId = "turn-automation" ;
const startedAt = Date . now () / 1000 ;
act (() => client . _emitChat ( "assistant-only-actions" , {
event : "goal_status" ,
chat_id : "assistant-only-actions" ,
status : "running" ,
started_at : startedAt ,
turn_id : turnId ,
}));
2026-09-22 16:37:35 +08:00
expect ( screen . getAllByRole ( "button" , { name : "Message actions" })). toHaveLength ( 1 );
2026-08-13 16:25:37 +08:00
act (() => client . _emitChat ( "assistant-only-actions" , {
event : "message" ,
chat_id : "assistant-only-actions" ,
text : "new automation" ,
turn_id : turnId ,
}));
await waitFor (() => expect ( screen . getByText ( "new automation" )). toBeInTheDocument ());
2026-09-22 16:37:35 +08:00
expect ( screen . getAllByRole ( "button" , { name : "Message actions" })). toHaveLength ( 1 );
expect ( screen . getByText ( "new automation" ). closest ( "[data-thread-display-unit]" ))
. not . toHaveAttribute ( "data-message-context-block" );
2026-08-13 16:25:37 +08:00
act (() => client . _emitChat ( "assistant-only-actions" , {
event : "turn_end" ,
chat_id : "assistant-only-actions" ,
turn_id : turnId ,
}));
2026-09-22 16:37:35 +08:00
await waitFor (() => expect ( screen . getAllByRole ( "button" , { name : "Message actions" })). toHaveLength ( 2 ));
const newMenu = await openMessageActions ( "new automation" );
expect ( within ( newMenu ). getByRole ( "button" , { name : "Copy" })). toBeInTheDocument ();
2026-08-13 16:25:37 +08:00
});
2026-05-06 14:15:36 +00:00
it ( "does not navigate away when clicking the chat title" , async () => {
const client = makeClient ();
render ( wrap (
client ,
< ThreadShell
session = { session ( "chat-title" )}
title = "Important conversation"
onToggleSidebar = {() => {}}
/>,
));
2026-11-13 17:12:18 +08:00
const header = within ( screen . getByTestId ( "thread-header" ));
await waitFor (() => expect ( header . getByText ( "Important conversation" )). toBeInTheDocument ());
fireEvent . click ( header . getByText ( "Important conversation" ));
2026-05-06 14:15:36 +00:00
2026-11-13 17:12:18 +08:00
expect ( header . getByText ( "Important conversation" )). toBeVisible ();
2026-05-06 14:15:36 +00:00
});
2026-09-24 22:05:31 +08:00
it . each ([ true , false ])( "waits for parent settings and retries only on failure (success: %s)" , async ( success ) => {
const client = makeClient ();
const settings = modelSettings ( "deepseek-v4-pro" , "deepseek" );
const settingsRequest = vi . fn (() => Promise . resolve ( httpJson ( settings )));
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => (
String ( input ). endsWith ( "/api/settings" )
? settingsRequest ()
: Promise . resolve ( httpJson ({}))
)));
const view = ( loading : boolean , snapshot : SettingsPayload | null ) => wrap (
client ,
< ThreadShell session = { null } title = "New topic" onToggleSidebar = {() => {}}
settingsLoading = { loading } settingsSnapshot = { snapshot } />,
);
const { rerender } = render ( view ( true , null ));
await act ( async () => {});
expect ( settingsRequest ). not . toHaveBeenCalled ();
rerender ( view ( false , success ? settings : null ));
expect ( await screen . findByTestId ( "composer-model-logo-deepseek" )). toBeInTheDocument ();
expect ( settingsRequest ). toHaveBeenCalledTimes ( success ? 0 : 1 );
});
2026-05-29 03:42:53 +08:00
it ( "updates the composer model logo when settings snapshot changes" , async () => {
const client = makeClient ();
const { rerender } = render (
wrap (
client ,
< ThreadShell
session = { session ( "model-logo" )}
title = "Model logo"
onToggleSidebar = {() => {}}
settingsSnapshot = { modelSettings ( "deepseek-v4-pro" , "deepseek" )}
/>,
"deepseek-v4-pro" ,
),
);
expect ( await screen . findByTestId ( "composer-model-logo-deepseek" )). toBeInTheDocument ();
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "model-logo" )}
title = "Model logo"
onToggleSidebar = {() => {}}
settingsSnapshot = { modelSettings ( "openai-codex/gpt-5.5" , "openai_codex" )}
/>,
"openai-codex/gpt-5.5" ,
),
);
});
expect ( await screen . findByTestId ( "composer-model-logo-openai_codex" )). toBeInTheDocument ();
});
2026-07-23 22:50:54 +08:00
it ( "keeps the composer model name and provider on the same settings snapshot" , async () => {
const client = makeClient ();
render (
wrap (
client ,
< ThreadShell
session = { session ( "model-settings-sync" )}
title = "Model settings sync"
onToggleSidebar = {() => {}}
settingsSnapshot = { modelSettings ( "openai-codex/gpt-5.5" , "openai_codex" )}
/>,
"ling/ling-3.0-flash" ,
),
);
expect ( await screen . findByTestId ( "composer-model-logo-openai_codex" )). toBeInTheDocument ();
2026-07-24 17:34:26 +08:00
expect ( screen . getByText ( "Default" )). toBeInTheDocument ();
2026-07-23 22:50:54 +08:00
expect ( screen . queryByText ( "ling-3.0-flash" )). not . toBeInTheDocument ();
});
2026-07-23 00:38:49 +08:00
it ( "resolves the composer model from the active session preset" , async () => {
const client = makeClient ();
render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-fast" , "fast" )}
title = "Fast session"
onToggleSidebar = {() => {}}
settingsSnapshot = { settingsWithFastPreset ()}
/>,
"deepseek-v4-pro" ,
),
);
2026-09-08 16:00:54 +08:00
fireEvent . focus ( await screen . findByLabelText ( "fast" ));
2026-10-07 15:19:55 +08:00
expect ( await screen . findByRole ( "tooltip" )). toHaveTextContent ( "fast gpt-5.5 OpenAI Codex" );
2026-09-08 16:00:54 +08:00
fireEvent . blur ( screen . getByLabelText ( "fast" ));
expect ( screen . queryByLabelText ( "Default" )). not . toBeInTheDocument ();
2026-08-22 19:41:37 +08:00
});
it ( "falls back to the current preset while a renamed session reference is stale" , async () => {
const client = makeClient ();
const settings = settingsWithFastPreset ();
settings . agent . model_preset = "fast" ;
settings . model_presets = settings . model_presets . map (( preset ) => ({
... preset ,
active : preset.name === "fast" ,
}));
render (
wrap (
client ,
< ThreadShell
session = { session ( "renamed-preset" , "old-fast" )}
title = "Renamed preset"
onToggleSidebar = {() => {}}
settingsSnapshot = { settings }
/>,
"openai-codex/gpt-5.5" ,
),
2026-08-21 16:34:35 +08:00
);
2026-08-22 19:41:37 +08:00
2026-09-08 16:00:54 +08:00
fireEvent . focus ( await screen . findByLabelText ( "fast" ));
2026-10-07 15:19:55 +08:00
expect ( await screen . findByRole ( "tooltip" )). toHaveTextContent ( "fast gpt-5.5 OpenAI Codex" );
2026-09-08 16:00:54 +08:00
fireEvent . blur ( screen . getByLabelText ( "fast" ));
2026-10-09 17:47:21 +08:00
expect ( screen . queryByRole ( "button" , { name : "Choose model" })). not . toBeInTheDocument ();
2026-07-24 17:34:26 +08:00
});
it ( "switches through every named preset while preserving call-order priority" , async () => {
const client = makeClient ();
const settings = settingsWithFastPreset ();
settings . model_presets . push ({
... settings . model_presets . at ( - 1 ) ! ,
name : "extra" ,
label : "Extra" ,
model : "deepseek/extra" ,
provider : "deepseek" ,
active : false ,
is_default : false ,
});
settings . model_call_order = [ "fast" ];
const view = ( preset : string ) => wrap ( client , (
< ThreadShell
session = { session ( "preset-order" , preset )}
title = "Preset order"
onToggleSidebar = {() => {}}
settingsSnapshot = { settings }
/>
));
const { rerender } = render ( view ( "default" ));
2026-08-22 19:41:37 +08:00
const badge = await screen . findByRole ( "button" , { name : "Default" });
2026-07-24 17:34:26 +08:00
expect ( badge ). toHaveTextContent ( "Default" );
2026-08-22 19:41:37 +08:00
fireEvent . click ( badge );
fireEvent . click ( await screen . findByRole ( "option" , { name : /^fast\b/i }));
2026-07-24 17:34:26 +08:00
expect ( client . sendSystemCommand ). toHaveBeenCalledWith (
"preset-order" ,
"/model fast" ,
);
2026-10-07 15:19:55 +08:00
expect ( await screen . findByLabelText ( "fast" , { selector : "button" })). toBeInTheDocument ();
2026-08-22 19:41:37 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : "fast" }));
fireEvent . click ( await screen . findByRole ( "option" , { name : /^extra\b/i }));
2026-07-24 17:34:26 +08:00
expect ( client . sendSystemCommand ). toHaveBeenLastCalledWith (
"preset-order" ,
"/model extra" ,
);
2026-08-16 00:20:39 +08:00
expect ( await screen . findByText ( "extra" )). toBeInTheDocument ();
2026-07-24 17:34:26 +08:00
rerender ( view ( "fast" ));
2026-10-07 15:19:55 +08:00
expect ( await screen . findByLabelText ( "fast" , { selector : "button" })). toBeInTheDocument ();
2026-07-23 00:38:49 +08:00
});
it ( "uses the backend-resolved provider for an auto session preset" , async () => {
const client = makeClient ();
const settings = modelSettings ( "deepseek-v4-pro" , "deepseek" );
settings . providers . push ({
name : "companyproxy" ,
label : "Company Proxy" ,
configured : true ,
});
settings . model_presets . push ({
... settings . model_presets [ 0 ] ! ,
name : "fast" ,
label : "Fast" ,
active : false ,
is_default : false ,
model : "companyproxy/gpt-4" ,
provider : "auto" ,
resolved_provider : "companyproxy" ,
});
render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-auto" , "fast" )}
title = "Auto provider session"
onToggleSidebar = {() => {}}
settingsSnapshot = { settings }
/>,
"deepseek-v4-pro" ,
),
);
2026-09-08 16:00:54 +08:00
fireEvent . focus ( await screen . findByLabelText ( "fast" ));
2026-10-07 15:19:55 +08:00
expect ( await screen . findByRole ( "tooltip" )). toHaveTextContent ( "fast gpt-4 Company Proxy" );
2026-09-08 16:00:54 +08:00
fireEvent . blur ( screen . getByLabelText ( "fast" ));
2026-10-09 17:47:21 +08:00
expect ( screen . queryByRole ( "button" , { name : "Choose model" })). not . toBeInTheDocument ();
2026-07-23 00:38:49 +08:00
});
2026-09-20 15:07:19 +08:00
it ( "keeps the selected composer preset and attributes only the reply to its actual source" , async () => {
2026-07-23 15:57:13 +08:00
const client = makeClient ();
render ( wrap (
client ,
< ThreadShell
session = { session ( "fallback-model" )}
title = "Fallback model"
onToggleSidebar = {() => {}}
settingsSnapshot = { modelSettings ( "openai-codex/gpt-5.5" , "openai_codex" )}
/>,
"openai-codex/gpt-5.5" ,
));
2026-07-24 17:34:26 +08:00
expect ( await screen . findByText ( "Default" )). toBeInTheDocument ();
2026-08-22 19:41:37 +08:00
const configuredLogo = await screen . findByTestId ( "composer-model-logo-openai_codex" );
const configuredBadge = configuredLogo . parentElement ;
2026-07-23 15:57:13 +08:00
expect ( configuredBadge ). not . toBeNull ();
expect ( configuredBadge ). toHaveClass ( "composer-model-badge" );
expect ( configuredBadge ). not . toHaveAttribute ( "data-fallback" );
2026-08-21 15:12:40 +08:00
act (() => {
client . _emitChat ( "fallback-model" , {
event : "turn_model_updated" ,
chat_id : "fallback-model" ,
model_name : "openai-codex/gpt-5.5" ,
2026-08-22 19:41:37 +08:00
model_preset : "Default" ,
2026-08-21 15:12:40 +08:00
});
});
expect ( configuredBadge ). not . toHaveAttribute ( "data-fallback" );
2026-08-22 19:41:37 +08:00
expect ( screen . getByText ( "Default" )). toBeInTheDocument ();
2026-08-21 15:12:40 +08:00
2026-07-23 15:57:13 +08:00
act (() => {
client . _emitChat ( "fallback-model" , {
event : "turn_model_updated" ,
chat_id : "fallback-model" ,
model_name : "deepseek/deepseek-chat" ,
2026-08-22 19:41:37 +08:00
fallback : true ,
2026-07-23 15:57:13 +08:00
});
});
2026-09-20 15:07:19 +08:00
expect ( screen . getByTestId ( "composer-model-logo-openai_codex" ). parentElement ). toBe ( configuredBadge );
expect ( screen . getByText ( "Default" )). toBeInTheDocument ();
expect ( screen . queryByTestId ( "composer-model-logo-deepseek" )). not . toBeInTheDocument ();
expect ( configuredBadge ). not . toHaveAttribute ( "data-fallback" );
fireEvent . focus ( screen . getByLabelText ( "Default" ));
2026-09-08 16:00:54 +08:00
expect ( await screen . findByRole ( "tooltip" )). toHaveTextContent (
2026-10-07 15:19:55 +08:00
"Default gpt-5.5 OpenAI Codex" ,
2026-08-22 19:41:37 +08:00
);
2026-09-20 15:07:19 +08:00
fireEvent . blur ( screen . getByLabelText ( "Default" ));
2026-07-23 15:57:13 +08:00
act (() => {
2026-09-20 15:07:19 +08:00
client . _emitChat ( "fallback-model" , {
event : "message" , chat_id : "fallback-model" , text : "Reply from the actual provider" ,
response_sources : [{ provider : "deepseek" , model : "deepseek-chat" , preset : "backup" , fallback : true }],
});
2026-07-23 15:57:13 +08:00
client . _emitChat ( "fallback-model" , {
event : "turn_end" ,
chat_id : "fallback-model" ,
});
});
await waitFor (() => {
expect (
screen . getByTestId ( "composer-model-logo-openai_codex" ). parentElement ,
). not . toHaveAttribute ( "data-fallback" );
});
2026-08-22 19:41:37 +08:00
expect ( screen . getByText ( "Default" )). toBeInTheDocument ();
2026-09-22 16:37:35 +08:00
await openMessageActions ( "Reply from the actual provider" );
2026-09-20 15:07:19 +08:00
expect ( await screen . findByText ( "backup" )). toBeInTheDocument ();
2026-07-23 15:57:13 +08:00
});
2026-11-08 13:14:52 +08:00
it . each ([
[ "bwrap" , "MacIntel" , "Bubblewrap (bwrap)" , "Configure bwrap path" ],
[ "seatbelt" , "Linux x86_64" , "macOS Seatbelt (sandbox-exec)" , "Configure sandbox-exec path" ],
] as const )( "uses the gateway's %s launcher and links to its path editor" , async ( backend , browserPlatform , launcher , action ) => {
const platform = vi . spyOn ( navigator , "platform" , "get" ). mockReturnValue ( browserPlatform );
try {
const client = makeClient ();
const openSettings = vi . fn ();
const settings = modelSettings ( "test-model" , "deepseek" );
settings . advanced . exec_sandbox_status = {
state : "unavailable" , reason : "launcher_missing" , launcher : null ,
revision : "gateway-launcher" , supported_backend : backend ,
};
render ( wrap ( client , < ThreadShell session = { session ( "sandbox-notice" )} title = "Sandbox notice"
onToggleSidebar = {() => {}} settingsSnapshot = { settings } onOpenSandboxSettings = { openSettings }
/>, undefined , "tok" , [ "webui.sandbox-settings.v1" ]));
const input = await screen . findByRole ( "textbox" );
fireEvent . change ( input , { target : { value : "Keep my draft" } });
input . focus ();
act (() => {
client . _emitChat ( "sandbox-notice" , { event : "user_message" , chat_id : "sandbox-notice" ,
turn_id : "sandbox-turn" , starts_turn : true , text : "Run a command" });
client . _emitChat ( "sandbox-notice" , { event : "message" , chat_id : "sandbox-notice" , text : "" ,
turn_id : "sandbox-turn" , kind : "progress" , tool_events : [{
name : "exec" , phase : "error" , error_code : "sandbox_launcher_missing" , call_id : "sandbox-command" ,
}] });
});
const banner = ( await screen . findByRole ( "button" , { name : action })). closest < HTMLElement >( '[role="status"]' ) ! ;
expect ( banner ). toHaveTextContent ( launcher );
expect ( input ). toHaveFocus ();
fireEvent . click ( within ( banner ). getByRole ( "button" , { name : action }));
expect ( openSettings ). toHaveBeenCalledWith ( "sandbox-launcher" );
expect ( input ). toHaveValue ( "Keep my draft" );
} finally {
platform . mockRestore ();
}
});
2026-09-20 15:51:08 +08:00
it ( "shows a dismissible, session-scoped fallback notice without changing the composer preset" , async () => {
const client = makeClient ();
const openSettings = vi . fn ();
const settings = modelSettings ( "openai-codex/gpt-5.5" , "openai_codex" );
const tree = ( chatId : string ) => wrap ( client , < ThreadShell
session = { session ( chatId )} title = "Fallback notice" onToggleSidebar = {() => {}}
settingsSnapshot = { settings } onOpenModelSettings = { openSettings }
/>);
const view = render ( tree ( "notice-a" ));
await screen . findByTestId ( "composer-model-logo-openai_codex" );
const emit = ( chatId : string , fallback : boolean ) => act (() => client . _emitChat ( chatId , {
event : "turn_model_updated" , chat_id : chatId ,
model_name : fallback ? "xai-grok/grok-4.5" : "openai-codex/gpt-5.5" ,
fallback ,
}));
const notice = () => screen . queryByText ( "This response used a fallback model: xai-grok/grok-4.5." );
emit ( "notice-b" , true );
emit ( "notice-a" , false );
expect ( notice ()). not . toBeInTheDocument ();
emit ( "notice-a" , true );
const banner = notice () ! . closest ( '[role="status"]' ) as HTMLElement ;
expect ( banner ). toBeVisible ();
expect ( screen . getByTestId ( "composer-model-logo-openai_codex" )). toBeInTheDocument ();
expect ( banner . textContent ). not . toMatch ( /expired|sign in/i );
const input = screen . getByRole ( "textbox" );
fireEvent . change ( input , { target : { value : "Keep my draft" } });
fireEvent . click ( within ( banner ). getByRole ( "button" , { name : "Check model settings" }));
expect ( openSettings ). toHaveBeenCalledTimes ( 1 );
fireEvent . click ( within ( banner ). getByRole ( "button" , { name : "Dismiss" }));
expect ( notice ()). not . toBeInTheDocument ();
expect ( input ). toHaveValue ( "Keep my draft" );
expect ( client . sendSystemCommand ). not . toHaveBeenCalled ();
emit ( "notice-a" , true );
expect ( notice ()). not . toBeInTheDocument ();
emit ( "notice-a" , false );
emit ( "notice-a" , true );
expect ( notice ()). toBeVisible ();
view . rerender ( tree ( "notice-b" ));
expect ( notice ()). not . toBeInTheDocument ();
emit ( "notice-a" , true );
expect ( notice ()). not . toBeInTheDocument ();
view . rerender ( tree ( "notice-a" ));
await act ( async () => {});
expect ( notice ()). not . toBeInTheDocument ();
});
2026-09-20 16:02:09 +08:00
it ( "prioritizes the rejected provider's login over fallback details" , async () => {
const client = makeClient ();
const openSettings = vi . fn ();
render ( wrap ( client , < ThreadShell session = { session ( "reauth" )}
title = "Auth notice" onToggleSidebar = {() => {}} onOpenModelSettings = { openSettings }
settingsSnapshot = { modelSettings ( "openai-codex/gpt-5.5" , "openai_codex" )} />));
await screen . findByTestId ( "composer-model-logo-openai_codex" );
const emit = ( reauth_provider? : string ) => act (() => client . _emitChat ( "reauth" , {
event : "turn_model_updated" , chat_id : "reauth" , model_name : "xai-grok/grok-4.5" ,
fallback : true , reauth_provider ,
}));
emit ();
const generic = screen . getByText ( /This response used a fallback model/ ). closest ( '[role="status"]' ) ! ;
fireEvent . click ( within ( generic as HTMLElement ). getByRole ( "button" , { name : "Dismiss" }));
emit ( "openai_codex" );
const title = screen . getByText ( "OpenAI Codex authorization expired. Please sign in again." );
expect ( title ). toBeVisible ();
expect ( screen . getByText ( "A fallback model handled this response." )). toBeVisible ();
expect ( screen . queryByText ( /This response used a fallback model/ )). not . toBeInTheDocument ();
2026-09-20 16:48:15 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : "Open model settings" }));
2026-09-20 16:02:09 +08:00
expect ( openSettings ). toHaveBeenCalledOnce ();
fireEvent . click ( within ( title . closest ( '[role="status"]' ) as HTMLElement ). getByRole ( "button" , { name : "Dismiss" }));
emit ( "openai_codex" );
emit ();
expect ( screen . queryByText ( /authorization expired/ )). not . toBeInTheDocument ();
expect ( screen . getByTestId ( "composer-model-logo-openai_codex" )). toBeInTheDocument ();
expect ( client . sendSystemCommand ). not . toHaveBeenCalled ();
});
2026-09-20 15:51:08 +08:00
it ( "does not show a live fallback notice just from replayed response attribution" , async () => {
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => Promise . resolve (
String ( input ). includes ( "/webui-thread" ) ? httpJson ({
schemaVersion : 3 ,
messages : [{ id : "old-reply" , role : "assistant" , content : "Previous reply" , createdAt : 1_000 ,
responseSources : [{ provider : "xai" , model : "grok-4.5" , preset : "backup" , fallback : true }] }],
}) : { ok : false , status : 404 , json : async () => ({}) },
)));
render ( wrap ( makeClient (), < ThreadShell session = { session ( "old-fallback" )} title = "History"
onToggleSidebar = {() => {}} settingsSnapshot = { modelSettings ( "gpt-5.5" , "openai_codex" )} />));
expect ( await screen . findByText ( "Previous reply" )). toBeInTheDocument ();
expect ( screen . queryByText ( /This response used a fallback model/ )). not . toBeInTheDocument ();
});
2026-10-06 00:46:38 +08:00
it . each ([ false , true ])( "keeps model setup actionable without a repeated tooltip (existing history: %s)" , async ( hasHistory ) => {
2026-09-18 00:25:48 +08:00
const client = makeClient ();
const settings = modelSettings ( "anthropic/claude-opus-4-5" , "anthropic" );
settings . agent . has_api_key = false ;
settings . providers = [{ name : "anthropic" , label : "Anthropic" , configured : false }];
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => {
if ( String ( input ). includes ( "websocket%3Asetup-tooltip/webui-thread" )) {
return Promise . resolve ( httpJson ( transcriptFromSimpleMessages (
hasHistory ? [{ role : "user" , content : "Previous message" }] : [],
)));
}
return Promise . resolve ({ ok : false , status : 404 , json : async () => ({}) });
}));
const onOpenModelSettings = vi . fn ();
render ( wrap (
client ,
< ThreadShell
session = { session ( "setup-tooltip" )}
title = "Setup tooltip"
onToggleSidebar = {() => {}}
settingsSnapshot = { settings }
onOpenModelSettings = { onOpenModelSettings }
/>,
"anthropic/claude-opus-4-5" ,
));
2026-11-13 17:12:18 +08:00
if ( hasHistory ) {
await screen . findByText ( "Previous message" );
} else {
await waitFor (() => expect ( screen . getByTestId ( "thread-welcome-layout" )). toHaveAttribute ( "data-layout" , "hero" ));
}
2026-10-09 17:47:21 +08:00
const badge = screen . getByRole ( "button" , { name : "Choose model" });
2026-09-18 00:25:48 +08:00
fireEvent . focus ( badge );
2026-10-06 00:46:38 +08:00
expect ( screen . queryByRole ( "tooltip" )). not . toBeInTheDocument ();
2026-09-18 00:25:48 +08:00
fireEvent . click ( badge );
expect ( onOpenModelSettings ). toHaveBeenCalledTimes ( 1 );
expect ( client . sendMessage ). not . toHaveBeenCalled ();
});
2026-09-02 04:19:12 +08:00
it ( "opens model settings directly without clearing the draft" , async () => {
2026-06-06 19:49:33 +08:00
const client = makeClient ();
const settings = modelSettings ( "openai-codex/gpt-5.1-codex" , "openai_codex" );
settings . agent . has_api_key = false ;
settings . providers = settings . providers . map (( provider ) =>
provider . name === "openai_codex"
? { ... provider , auth_type : "oauth" , configured : false }
: provider ,
);
2026-09-01 20:18:58 +08:00
settings . providers . push (
{
name : "xai_grok" ,
label : "xAI Grok" ,
auth_type : "oauth" ,
configured : true ,
},
{
name : "ollama" ,
label : "Ollama" ,
configured : true ,
api_base : "http://127.0.0.1:11434" ,
},
);
2026-06-06 19:49:33 +08:00
const onOpenModelSettings = vi . fn ();
render (
wrap (
client ,
< ThreadShell
session = { session ( "unconfigured-model" )}
title = "Unconfigured model"
onToggleSidebar = {() => {}}
settingsSnapshot = { settings }
onOpenModelSettings = { onOpenModelSettings }
/>,
"openai-codex/gpt-5.1-codex" ,
),
);
2026-10-09 17:47:21 +08:00
const badge = await screen . findByRole ( "button" , { name : "Choose model" });
2026-09-02 03:48:10 +08:00
expect ( badge . querySelector ( '[data-needs-setup="true"]' )). toHaveClass (
"composer-model-pill-setup" ,
);
2026-10-09 17:47:21 +08:00
expect ( screen . getByTestId ( "composer-model-setup-label" )). toHaveTextContent ( "Choose model" );
2026-09-02 02:02:30 +08:00
expect ( badge ). not . toHaveClass ( "border-amber-500/35" );
2026-06-06 19:49:33 +08:00
expect ( screen . queryByTestId ( "composer-model-logo-openai_codex" )). not . toBeInTheDocument ();
2026-09-01 20:18:58 +08:00
const input = screen . getByRole ( "textbox" , { name : "Message input" });
fireEvent . change ( input , {
2026-06-06 19:49:33 +08:00
target : { value : "hello" },
});
2026-09-02 04:19:12 +08:00
fireEvent . click ( badge );
2026-10-09 17:47:21 +08:00
expect ( screen . queryByRole ( "dialog" , { name : "Choose model" })). not . toBeInTheDocument ();
2026-09-02 04:19:12 +08:00
expect ( onOpenModelSettings ). toHaveBeenCalledTimes ( 1 );
expect ( input ). toHaveValue ( "hello" );
expect ( client . sendMessage ). not . toHaveBeenCalled ();
onOpenModelSettings . mockClear ();
2026-09-02 12:21:53 +08:00
const firstSetupPill = badge . querySelector ( '[data-needs-setup="true"]' );
2026-09-01 20:18:58 +08:00
fireEvent . keyDown ( input , { key : "Enter" , code : "Enter" });
2026-09-02 12:21:53 +08:00
const secondSetupPill = badge . querySelector ( '[data-needs-setup="true"]' );
expect ( onOpenModelSettings ). not . toHaveBeenCalled ();
expect ( secondSetupPill ). not . toBe ( firstSetupPill );
expect ( secondSetupPill ). toHaveClass ( "composer-model-pill-setup-attention" );
2026-09-01 20:18:58 +08:00
expect ( input ). toHaveValue ( "hello" );
2026-06-06 19:49:33 +08:00
expect ( client . sendMessage ). not . toHaveBeenCalled ();
2026-09-02 12:21:53 +08:00
fireEvent . keyDown ( input , { key : "Enter" , code : "Enter" });
expect ( badge . querySelector ( '[data-needs-setup="true"]' )). not . toBe ( secondSetupPill );
2026-06-06 19:49:33 +08:00
});
2026-05-30 23:45:26 +08:00
it ( "keeps image generation controls out of the composer" , async () => {
2026-05-29 03:42:53 +08:00
const client = makeClient ();
const disabledSettings = modelSettings ( "deepseek-v4-pro" , "deepseek" );
const enabledSettings : SettingsPayload = {
... disabledSettings ,
image_generation : {
... disabledSettings . image_generation ,
enabled : true ,
provider_configured : true ,
},
};
const { rerender } = render (
wrap (
client ,
< ThreadShell
session = { session ( "image-generation-disabled" )}
title = "Image generation disabled"
onToggleSidebar = {() => {}}
settingsSnapshot = { disabledSettings }
/>,
"deepseek-v4-pro" ,
),
);
await screen . findByLabelText ( "Message input" );
2026-10-09 17:47:21 +08:00
expect ( screen . queryByRole ( "button" , { name : "Image mode" })). not . toBeInTheDocument ();
2026-05-29 03:42:53 +08:00
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "image-generation-disabled" )}
title = "Image generation disabled"
onToggleSidebar = {() => {}}
settingsSnapshot = { enabledSettings }
/>,
"deepseek-v4-pro" ,
),
);
});
2026-10-09 17:47:21 +08:00
expect ( screen . queryByRole ( "button" , { name : "Image mode" })). not . toBeInTheDocument ();
2026-05-29 03:42:53 +08:00
});
2026-04-18 18:51:53 +00:00
it ( "restores in-memory messages when switching away and back to a session" , async () => {
const client = makeClient ();
const { rerender } = render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-a" )}
title = "Chat chat-a"
onToggleSidebar = {() => {}}
/>,
),
);
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "persist me across tabs" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() =>
2026-06-06 19:49:33 +08:00
expectSendMessageWithTurn ( client , "chat-a" , "persist me across tabs" ),
2026-04-18 18:51:53 +00:00
);
expect ( screen . getByText ( "persist me across tabs" )). toBeInTheDocument ();
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "chat-b" )}
title = "Chat chat-b"
onToggleSidebar = {() => {}}
/>,
),
);
});
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "chat-a" )}
title = "Chat chat-a"
onToggleSidebar = {() => {}}
/>,
),
);
});
expect ( screen . getByText ( "persist me across tabs" )). toBeInTheDocument ();
});
2026-10-19 21:06:46 +08:00
it . each ([ false , true ])( "sends the merged pending message before history refresh resolves (pending tools=%s)" , async ( pendingTools ) => {
2026-10-16 13:33:41 +08:00
const client = makeClient ();
const chatId = "queued-live-completion" ;
const owner = "queued-owner" ;
const initialHistory = httpJson ({
... transcriptFromSimpleMessages ([{ role : "user" , content : "Initial question" , turnId : owner }]),
has_pending_tool_calls : pendingTools ,
active_turn_id : owner ,
completed_turn_ids : [],
});
vi . mocked ( fetch ). mockImplementation ( async ( input ) => (
2026-10-20 14:26:54 +08:00
String ( input ). includes ( "/webui-thread" ) ? initialHistory . clone ()
2026-10-16 13:33:41 +08:00
: { ok : false , status : 404 , json : async () => ({}) }
) as Response );
render ( wrap ( client , < ThreadShell session = { session ( chatId )} title = "Queued chat" onToggleSidebar = {() => {}} />));
await screen . findByText ( "Initial question" );
act (() => client . _emitChat ( chatId , {
event : "goal_status" , chat_id : chatId , turn_id : owner ,
status : "running" , started_at : 1_000 ,
}));
const input = screen . getByLabelText ( "Message input" );
for ( const text of [ "first persisted follow-up" , "second persisted follow-up" ]) {
fireEvent . change ( input , { target : { value : text } });
fireEvent . keyDown ( input , { key : "Enter" });
}
let finishRefresh !: ( response : Response ) => void ;
const refresh = new Promise < Response >(( resolve ) => { finishRefresh = resolve ; });
let refreshStarted = false ;
vi . mocked ( fetch ). mockImplementation ( async ( input ) => {
if ( String ( input ). includes ( "/webui-thread" )) {
refreshStarted = true ;
return refresh ;
}
return { ok : false , status : 404 , json : async () => ({}) } as Response ;
});
act (() => client . _emitSessionUpdate ( chatId , "thread" ));
await waitFor (() => expect ( refreshStarted ). toBe ( true ));
try {
act (() => client . _emitChat ( chatId , { event : "turn_end" , chat_id : chatId , turn_id : owner }));
2026-10-19 21:06:46 +08:00
await waitFor (() => expectSendMessageWithTurn ( client , chatId , "first persisted follow-up\nsecond persisted follow-up" ));
expect ( screen . queryByRole ( "group" , { name : "Waiting to send" })). not . toBeInTheDocument ();
2026-10-16 13:33:41 +08:00
expect ( client . sendMessage ). toHaveBeenCalledTimes ( 1 );
const nextTurnId = client . sendMessage . mock . calls [ 0 ][ 3 ] ! . turnId ! ;
act (() => client . _emitChat ( chatId , {
event : "goal_status" , chat_id : chatId , turn_id : nextTurnId ,
status : "running" , started_at : 2_000 ,
}));
expect ( client . sendMessage ). toHaveBeenCalledTimes ( 1 );
act (() => client . _emitChat ( chatId , { event : "turn_end" , chat_id : chatId , turn_id : nextTurnId }));
2026-10-19 21:06:46 +08:00
expect ( client . sendMessage ). toHaveBeenCalledTimes ( 1 );
2026-10-16 13:33:41 +08:00
} finally {
2026-10-20 14:26:54 +08:00
await act ( async () => { finishRefresh ( initialHistory . clone ()); });
2026-10-16 13:33:41 +08:00
}
});
2026-10-19 21:06:46 +08:00
it ( "sends the complete temporary pending message once without persisted history" , async () => {
2026-10-16 13:33:41 +08:00
const client = makeClient ();
const chatId = "temporary-queued-follow-ups" ;
render ( wrap ( client , < ThreadShell
session = { session ( chatId )} title = "Temporary chat" temporary
temporaryChatIds = {[ chatId ]} onToggleSidebar = {() => {}}
/>));
act (() => client . _emitChat ( chatId , {
event : "goal_status" , chat_id : chatId , turn_id : "temporary-owner" ,
status : "running" , started_at : 1_000 ,
}));
const input = screen . getByLabelText ( "Message input" );
for ( const text of [ "first temporary follow-up" , "second temporary follow-up" ]) {
fireEvent . change ( input , { target : { value : text } });
fireEvent . keyDown ( input , { key : "Enter" });
}
expect ( client . sendMessage ). not . toHaveBeenCalled ();
act (() => client . _emitChat ( chatId , {
event : "turn_end" , chat_id : chatId , turn_id : "temporary-owner" ,
}));
2026-10-19 21:06:46 +08:00
await waitFor (() => expectSendMessageWithTurn ( client , chatId , "first temporary follow-up\nsecond temporary follow-up" ));
2026-10-16 13:33:41 +08:00
expect ( client . sendMessage ). toHaveBeenCalledTimes ( 1 );
2026-10-19 21:06:46 +08:00
expect ( screen . queryByRole ( "group" , { name : "Waiting to send" })). not . toBeInTheDocument ();
2026-10-16 13:33:41 +08:00
const nextTurnId = client . sendMessage . mock . calls [ 0 ][ 3 ] ! . turnId ! ;
act (() => client . _emitChat ( chatId , {
event : "goal_status" , chat_id : chatId , turn_id : nextTurnId ,
status : "running" , started_at : 2_000 ,
}));
expect ( client . sendMessage ). toHaveBeenCalledTimes ( 1 );
act (() => client . _emitChat ( chatId , {
event : "turn_end" , chat_id : chatId , turn_id : nextTurnId ,
}));
2026-10-19 21:06:46 +08:00
expect ( client . sendMessage ). toHaveBeenCalledTimes ( 1 );
2026-10-16 13:33:41 +08:00
expect ( screen . queryByRole ( "group" , { name : "Waiting to send" })). not . toBeInTheDocument ();
expect ( vi . mocked ( fetch ). mock . calls . some (([ url ]) => String ( url ). includes ( "/webui-thread" ))). toBe ( false );
expect ( window . localStorage . getItem ( `nanobot.webui.composerQueuedGuidance.v1: ${ chatId } ` )). toBeNull ();
});
2026-08-05 19:24:41 +08:00
it ( "keeps temporary messages across navigation and drops them after clear" , async () => {
const client = makeClient ();
2026-08-06 18:29:04 +08:00
const view = (
chatId : string ,
temporary : boolean ,
temporaryChatIds : readonly string [],
) => wrap (
2026-08-05 19:24:41 +08:00
client ,
< ThreadShell
session = { session ( chatId )}
title = { temporary ? "Temporary chat" : "Regular chat" }
temporary = { temporary }
2026-08-06 18:29:04 +08:00
temporaryChatIds = { temporaryChatIds }
2026-08-05 19:24:41 +08:00
onToggleSidebar = {() => {}}
/>,
);
2026-08-06 18:29:04 +08:00
const retainedTemporaryChats = [ "temporary-live" ];
const { rerender } = render ( view ( "temporary-live" , true , retainedTemporaryChats ));
2026-08-05 19:24:41 +08:00
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "keep this only in memory" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expectSendMessageWithTurn (
client ,
"temporary-live" ,
"keep this only in memory" ,
));
2026-08-06 18:29:04 +08:00
rerender ( view ( "regular" , false , retainedTemporaryChats ));
2026-08-05 19:24:41 +08:00
await waitFor (() => {
expect ( screen . queryByText ( "keep this only in memory" )). not . toBeInTheDocument ();
});
2026-08-06 18:29:04 +08:00
rerender ( view ( "temporary-live" , true , retainedTemporaryChats ));
2026-08-05 19:24:41 +08:00
expect ( screen . getByText ( "keep this only in memory" )). toBeInTheDocument ();
2026-08-06 18:29:04 +08:00
rerender ( view ( "temporary-cleared" , true , [ "temporary-cleared" ]));
2026-08-05 19:24:41 +08:00
await waitFor (() => {
expect ( screen . queryByText ( "keep this only in memory" )). not . toBeInTheDocument ();
});
});
2026-07-21 18:42:25 +08:00
it ( "highlights sent skill references without skill metadata" , async () => {
2026-07-21 18:29:57 +08:00
const client = makeClient ();
render ( wrap (
client ,
< ThreadShell
session = { session ( "skill-reference" )}
title = "Skill reference"
onToggleSidebar = {() => {}}
/>,
));
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "Use $github for this" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() =>
expectSendMessageWithTurn ( client , "skill-reference" , "Use $github for this" ),
);
expect ( screen . getByTestId ( "message-skill-reference-github" ))
2026-10-22 21:32:31 +08:00
. toHaveTextContent ( /^\$github$/ );
2026-07-21 18:29:57 +08:00
});
2026-04-18 18:51:53 +00:00
it ( "clears the old thread when the active session is removed" , async () => {
const client = makeClient ();
const { rerender } = render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-a" )}
title = "Chat chat-a"
onToggleSidebar = {() => {}}
/>,
),
);
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "delete me cleanly" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() =>
2026-06-06 19:49:33 +08:00
expectSendMessageWithTurn ( client , "chat-a" , "delete me cleanly" ),
2026-04-18 18:51:53 +00:00
);
expect ( screen . getByText ( "delete me cleanly" )). toBeInTheDocument ();
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { null }
title = "nanobot"
onToggleSidebar = {() => {}}
/>,
),
);
});
await waitFor (() => {
expect ( screen . queryByText ( "delete me cleanly" )). not . toBeInTheDocument ();
});
2026-10-07 13:53:48 +08:00
expect ( screen . getByRole ( "textbox" )). toBeInTheDocument ();
2026-05-06 14:15:36 +00:00
});
it ( "creates a chat only when the blank landing sends a first message" , async () => {
const client = makeClient ();
const onCreateChat = vi . fn (). mockResolvedValue ( "chat-new" );
render (
wrap (
client ,
< ThreadShell
session = { null }
title = "nanobot"
onToggleSidebar = {() => {}}
onCreateChat = { onCreateChat }
/>,
),
);
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "start for real" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( onCreateChat ). toHaveBeenCalledTimes ( 1 ));
2026-09-04 10:36:24 +08:00
expect ( onCreateChat ). toHaveBeenCalledWith ( null , "start for real" , null );
2026-05-06 14:15:36 +00:00
});
2026-07-24 17:34:26 +08:00
it ( "applies the selected landing preset before sending the first prompt" , async () => {
const client = makeClient ();
const settings = settingsWithFastPreset ();
settings . model_call_order = [ "fast" ];
let resolveModelCommand !: () => void ;
client . sendSystemCommand . mockImplementation (
() => new Promise < void >(( resolve ) => {
resolveModelCommand = resolve ;
}),
);
const onCreateChat = vi . fn (). mockResolvedValue ( "chat-new" );
const view = ( currentSession : ReturnType < typeof session > | null ) => wrap ( client , (
< ThreadShell
session = { currentSession }
title = { currentSession ? "New chat" : "nanobot" }
onToggleSidebar = {() => {}}
onCreateChat = { onCreateChat }
settingsSnapshot = { settings }
/>
));
const { rerender } = render ( view ( null ));
2026-08-22 19:41:37 +08:00
fireEvent . click ( await screen . findByRole ( "button" , { name : "Default" }));
fireEvent . click ( await screen . findByRole ( "option" , { name : /^fast\b/i }));
2026-10-07 15:19:55 +08:00
expect ( await within ( screen . getByTestId ( "thread-welcome-layout" )). findByText ( "fast" )). toBeInTheDocument ();
2026-07-24 17:34:26 +08:00
expect ( client . sendSystemCommand ). not . toHaveBeenCalled ();
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "use the selected model" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( client . sendSystemCommand ). toHaveBeenCalledWith (
"chat-new" ,
"/model fast" ,
));
2026-09-04 10:36:24 +08:00
expect ( onCreateChat ). toHaveBeenCalledWith ( null , "use the selected model" , "fast" );
2026-07-24 17:34:26 +08:00
2026-09-04 10:36:24 +08:00
await act ( async () => {
rerender ( view ( session ( "chat-new" , "fast" )));
});
2026-09-08 16:00:54 +08:00
fireEvent . focus ( await screen . findByLabelText ( "fast" ));
2026-10-07 15:19:55 +08:00
expect ( await screen . findByRole ( "tooltip" )). toHaveTextContent ( "fast gpt-5.5 OpenAI Codex" );
2026-09-08 16:00:54 +08:00
fireEvent . blur ( screen . getByLabelText ( "fast" ));
2026-09-04 10:36:24 +08:00
expect ( screen . queryByText ( "Default" )). not . toBeInTheDocument ();
2026-07-24 17:34:26 +08:00
expect ( client . sendMessage ). not . toHaveBeenCalled ();
await act ( async () => {
resolveModelCommand ();
});
await waitFor (() => {
expectSendMessageWithTurn ( client , "chat-new" , "use the selected model" );
});
});
2026-07-07 18:20:42 +08:00
it ( "binds a pending landing message to the chat created for it" , async () => {
const client = makeClient ();
let resolveCreate : (( chatId : string ) => void ) | null = null ;
const onCreateChat = vi . fn (() => new Promise < string >(( resolve ) => {
resolveCreate = resolve ;
}));
const { rerender } = render (
wrap (
client ,
< ThreadShell
session = { null }
title = "nanobot"
onToggleSidebar = {() => {}}
onCreateChat = { onCreateChat }
/>,
),
);
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "must not leak" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( onCreateChat ). toHaveBeenCalledTimes ( 1 ));
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "existing-chat" )}
title = "Existing chat"
onToggleSidebar = {() => {}}
onCreateChat = { onCreateChat }
/>,
),
);
});
await act ( async () => {
resolveCreate ? .( "chat-new" );
});
expect ( client . sendMessage ). not . toHaveBeenCalled ();
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "chat-new" )}
title = "New chat"
onToggleSidebar = {() => {}}
onCreateChat = { onCreateChat }
/>,
),
);
});
await waitFor (() =>
expectSendMessageWithTurn ( client , "chat-new" , "must not leak" ),
);
});
2026-09-12 16:32:46 +08:00
it ( "consumes an automation-page first message through the normal thread stream" , async () => {
const client = makeClient ();
const consumed = vi . fn ();
const pendingFirstMessage = {
id : "automation-first-message" ,
chatId : "chat-new" ,
content : "Every weekday at 9, summarize open pull requests" ,
2026-09-13 05:20:26 +08:00
options : { intent : "create_automation" as const },
2026-09-12 16:32:46 +08:00
};
render (
wrap (
client ,
< StrictMode >
< ThreadShell
session = { session ( "chat-new" )}
title = "New automation chat"
onToggleSidebar = {() => {}}
pendingFirstMessage = { pendingFirstMessage }
onPendingFirstMessageConsumed = { consumed }
/>
</ StrictMode >,
),
);
await waitFor (() => expectSendMessageWithTurn (
client ,
"chat-new" ,
pendingFirstMessage . content ,
));
expect ( client . sendMessage ). toHaveBeenCalledTimes ( 1 );
expect ( consumed ). toHaveBeenCalledOnce ();
expect ( consumed ). toHaveBeenCalledWith ( pendingFirstMessage . id );
2026-09-13 05:20:26 +08:00
expect ( client . sendMessage ). toHaveBeenCalledWith (
"chat-new" ,
pendingFirstMessage . content ,
undefined ,
expect . objectContaining ({ intent : "create_automation" }),
);
2026-09-12 16:32:46 +08:00
});
2026-05-08 09:40:15 +00:00
it ( "keeps the first landing message when new chat history is still empty" , async () => {
const client = makeClient ();
const onCreateChat = vi . fn (). mockResolvedValue ( "chat-new" );
vi . stubGlobal (
"fetch" ,
vi . fn ( async () => ({
ok : false ,
status : 404 ,
json : async () => ({}),
})),
);
const { rerender } = render (
wrap (
client ,
< ThreadShell
session = { null }
title = "nanobot"
onToggleSidebar = {() => {}}
onCreateChat = { onCreateChat }
/>,
),
);
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "first message should stay" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( onCreateChat ). toHaveBeenCalledTimes ( 1 ));
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "chat-new" )}
title = "Chat chat-new"
onToggleSidebar = {() => {}}
onCreateChat = { onCreateChat }
/>,
),
);
});
await waitFor (() =>
2026-06-06 19:49:33 +08:00
expectSendMessageWithTurn ( client , "chat-new" , "first message should stay" ),
2026-05-08 09:40:15 +00:00
);
await waitFor (() =>
expect ( screen . getByText ( "first message should stay" )). toBeInTheDocument (),
);
2026-11-13 17:12:18 +08:00
expect ( screen . getByTestId ( "thread-composer-motion" ). closest ( "[data-layout]" )). toHaveAttribute ( "data-layout" , "thread" );
2026-05-08 09:40:15 +00:00
});
2026-07-24 17:34:26 +08:00
it ( "hides a live first /model turn when the initial history snapshot is stale" , async () => {
2026-05-24 20:56:07 +08:00
const client = makeClient ();
const onCreateChat = vi . fn (). mockResolvedValue ( "chat-new" );
let resolveThread :
| (( value : { ok : boolean ; status : number ; json : () => Promise < unknown > }) => void )
| null = null ;
vi . stubGlobal (
"fetch" ,
vi . fn (( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Achat-new/webui-thread" )) {
return new Promise (( resolve ) => {
resolveThread = resolve ;
});
}
return Promise . resolve ({
ok : false ,
status : 404 ,
json : async () => ({}),
});
}),
);
const { rerender } = render (
wrap (
client ,
< ThreadShell
session = { null }
title = "nanobot"
onToggleSidebar = {() => {}}
onCreateChat = { onCreateChat }
/>,
),
);
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "/model" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( onCreateChat ). toHaveBeenCalledTimes ( 1 ));
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "chat-new" )}
title = "Chat chat-new"
onToggleSidebar = {() => {}}
onCreateChat = { onCreateChat }
/>,
),
);
});
await waitFor (() =>
2026-06-06 19:49:33 +08:00
expectSendMessageWithTurn ( client , "chat-new" , "/model" ),
2026-05-24 20:56:07 +08:00
);
await act ( async () => {
client . _emitChat ( "chat-new" , {
event : "message" ,
chat_id : "chat-new" ,
text : "## Model\n- Current model: `Ring-2.6-1T`" ,
});
2026-07-24 17:34:26 +08:00
client . _emitChat ( "chat-new" , {
event : "message" ,
chat_id : "chat-new" ,
text : "This unrelated reply stays visible." ,
});
2026-05-24 20:56:07 +08:00
});
2026-07-24 17:34:26 +08:00
expect ( screen . queryByText ( "/model" )). not . toBeInTheDocument ();
expect ( screen . queryByText ( /Current model/ )). not . toBeInTheDocument ();
expect ( screen . getByText ( "This unrelated reply stays visible." )). toBeInTheDocument ();
2026-05-24 20:56:07 +08:00
await act ( async () => {
resolveThread ? .(
httpJson ( transcriptFromSimpleMessages ([{ role : "user" , content : "/model" }])),
);
});
2026-07-24 17:34:26 +08:00
await waitFor (() => {
expect ( screen . queryByText ( "/model" )). not . toBeInTheDocument ();
expect ( screen . queryByText ( /Current model/ )). not . toBeInTheDocument ();
expect ( screen . getByText ( "This unrelated reply stays visible." )). toBeInTheDocument ();
});
2026-05-24 20:56:07 +08:00
});
2026-11-13 17:12:18 +08:00
it . each ([ false , true ])( "keeps the empty thread landing focused on the composer (temporary=%s)" , async ( temporary ) => {
2026-05-06 14:15:36 +00:00
const client = makeClient ();
render (
wrap (
client ,
< ThreadShell
2026-05-29 03:42:53 +08:00
session = { null }
title = "nanobot"
2026-11-13 17:12:18 +08:00
temporaryChatEnabled = { temporary }
2026-05-06 14:15:36 +00:00
onToggleSidebar = {() => {}}
/>,
),
);
2026-05-29 03:42:53 +08:00
await act ( async () => {});
2026-05-06 14:15:36 +00:00
2026-11-13 17:12:18 +08:00
expect ( within ( screen . getByTestId ( "thread-empty-region" )). getByRole ( "heading" , {
level : 1 , name : temporary ? "Temporary chat" : "New topic" ,
})). toHaveClass ( "sr-only" );
expect ( screen . getByTestId ( "thread-welcome-mark" )). toHaveAttribute ( "aria-hidden" , "true" );
2026-10-07 13:53:48 +08:00
expect ( screen . getByRole ( "textbox" )). toBeInTheDocument ();
2026-05-29 03:42:53 +08:00
expect ( screen . queryByRole ( "button" , { name : "Write code" })). not . toBeInTheDocument ();
2026-10-09 17:47:21 +08:00
expect ( screen . queryByRole ( "button" , { name : "Make a plan" })). not . toBeInTheDocument ();
2026-04-18 18:51:53 +00:00
});
it ( "does not leak the previous thread when opening a brand-new chat" , async () => {
const client = makeClient ();
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
2026-05-16 01:14:11 +08:00
if ( url . includes ( "websocket%3Achat-a/webui-thread" )) {
return httpJson (
transcriptFromSimpleMessages ([
2026-04-18 18:51:53 +00:00
{ role : "user" , content : "old question" },
{ role : "assistant" , content : "old answer" },
2026-05-16 01:14:11 +08:00
]),
);
2026-04-18 18:51:53 +00:00
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
const { rerender } = render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-a" )}
title = "Chat chat-a"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "old answer" )). toBeInTheDocument ());
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "chat-new" )}
title = "Chat chat-new"
onToggleSidebar = {() => {}}
/>,
),
);
});
expect ( screen . queryByText ( "old answer" )). not . toBeInTheDocument ();
await waitFor (() =>
2026-10-07 13:53:48 +08:00
expect ( screen . getByRole ( "textbox" )). toBeInTheDocument (),
2026-04-18 18:51:53 +00:00
);
2026-10-07 13:53:48 +08:00
const input = screen . getByRole ( "textbox" );
2026-11-05 13:32:55 +08:00
expect ( input ). toHaveAttribute ( "placeholder" , "Type / for commands, @ for chats or apps, $ for skills" );
2026-05-06 14:15:36 +00:00
expect ( input . className ). toContain ( "min-h-[78px]" );
2026-04-18 18:51:53 +00:00
expect ( screen . queryByText ( "old answer" )). not . toBeInTheDocument ();
});
2026-06-05 19:49:34 +08:00
it ( "forks assistant replies using the global user message index rather than the visible window index" , async () => {
const client = makeClient ();
const onForkChat = vi . fn (). mockResolvedValue ( "chat-fork" );
2026-06-10 18:02:27 +08:00
const rows = [
{ role : "user" as const , content : "question 100" },
{ role : "assistant" as const , content : "answer 100" },
];
2026-06-05 19:49:34 +08:00
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Along-chat/webui-thread" )) {
2026-06-10 18:02:27 +08:00
return httpJson ({
... transcriptFromSimpleMessages ( rows ),
page : {
before_cursor : "before-question-100" ,
has_more_before : true ,
loaded_message_count : 2 ,
user_message_offset : 100 ,
},
});
2026-06-05 19:49:34 +08:00
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "long-chat" )}
title = "Long chat"
onToggleSidebar = {() => {}}
onForkChat = { onForkChat }
/>,
),
);
2026-09-22 16:37:35 +08:00
const menu = await openMessageActions ( "answer 100" );
2026-10-09 17:47:21 +08:00
fireEvent . click ( within ( menu ). getByRole ( "button" , { name : "New chat from here" }));
2026-06-05 19:49:34 +08:00
await waitFor (() =>
expect ( onForkChat ). toHaveBeenCalledWith ( "long-chat" , 101 ),
);
});
2026-05-01 13:16:33 -03:00
it ( "does not cache optimistic messages under the next chat during a session switch" , async () => {
const client = makeClient ();
const { rerender } = render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-a" )}
title = "Chat chat-a"
onToggleSidebar = {() => {}}
/>,
),
);
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "only in chat a" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() =>
2026-06-06 19:49:33 +08:00
expectSendMessageWithTurn ( client , "chat-a" , "only in chat a" ),
2026-05-01 13:16:33 -03:00
);
expect ( screen . getByText ( "only in chat a" )). toBeInTheDocument ();
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "chat-b" )}
title = "Chat chat-b"
onToggleSidebar = {() => {}}
/>,
),
);
});
await waitFor (() => {
expect ( screen . queryByText ( "only in chat a" )). not . toBeInTheDocument ();
});
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "chat-a" )}
title = "Chat chat-a"
onToggleSidebar = {() => {}}
/>,
),
);
});
expect ( screen . getByText ( "only in chat a" )). toBeInTheDocument ();
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "chat-b" )}
title = "Chat chat-b"
onToggleSidebar = {() => {}}
/>,
),
);
});
await waitFor (() => {
expect ( screen . queryByText ( "only in chat a" )). not . toBeInTheDocument ();
});
});
2026-05-06 15:54:15 +00:00
it ( "keeps live assistant replies after visiting the blank new-chat page" , async () => {
const client = makeClient ();
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
2026-05-16 01:14:11 +08:00
if ( url . includes ( "websocket%3Achat-a/webui-thread" )) {
return httpJson ( transcriptFromSimpleMessages ([{ role : "user" , content : "hello" }]));
2026-05-06 15:54:15 +00:00
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
const { rerender } = render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-a" )}
title = "Chat chat-a"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "hello" )). toBeInTheDocument ());
await act ( async () => {
client . _emitChat ( "chat-a" , {
event : "message" ,
chat_id : "chat-a" ,
text : "live assistant reply" ,
});
});
expect ( screen . getByText ( "live assistant reply" )). toBeInTheDocument ();
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { null }
title = "nanobot"
onToggleSidebar = {() => {}}
/>,
),
);
});
expect ( screen . queryByText ( "live assistant reply" )). not . toBeInTheDocument ();
2026-11-13 17:12:18 +08:00
expect ( screen . getByTestId ( "thread-welcome-layout" )). toHaveAttribute ( "data-layout" , "hero" );
2026-05-06 15:54:15 +00:00
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "chat-a" )}
title = "Chat chat-a"
onToggleSidebar = {() => {}}
/>,
),
);
});
await waitFor (() => expect ( screen . getByText ( "live assistant reply" )). toBeInTheDocument ());
});
2026-07-26 00:18:24 +08:00
it ( "restores the stop control when returning to a running chat" , async () => {
const client = makeClient ();
const view = ( chatId : string ) => wrap (
client ,
< ThreadShell
session = { session ( chatId )}
title = { `Chat ${ chatId } ` }
onToggleSidebar = {() => {}}
/>,
);
const { rerender } = render ( view ( "chat-a" ));
await act ( async () => {
client . _emitChat ( "chat-a" , {
event : "goal_status" ,
2026-10-21 18:33:53 +08:00
chat_id : "chat-a" , turn_id : "running-chat-a-turn" ,
2026-07-26 00:18:24 +08:00
status : "running" ,
started_at : Date.now () / 1000 ,
});
});
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
await act ( async () => {
rerender ( view ( "chat-b" ));
});
expect ( screen . queryByRole ( "button" , { name : "Stop response" })). not . toBeInTheDocument ();
await act ( async () => {
rerender ( view ( "chat-a" ));
});
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
});
2026-06-22 21:39:42 +08:00
it ( "keeps live fork replies when a canonical refresh is missing an earlier assistant answer" , async () => {
const client = makeClient ();
let historyCalls = 0 ;
2026-10-21 18:33:53 +08:00
let secondTurnId = "" ;
2026-06-22 21:39:42 +08:00
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Achat-fork/webui-thread" )) {
historyCalls += 1 ;
return httpJson (
2026-10-21 18:33:53 +08:00
streamedThreadPayload ( "chat-fork" ,
2026-06-22 21:39:42 +08:00
historyCalls === 1
2026-10-21 18:33:53 +08:00
? [{ role : "user" , content : "first fork question" , turnId : "first-fork-turn" }]
2026-06-22 21:39:42 +08:00
: [
2026-10-21 18:33:53 +08:00
{ role : "user" , content : "first fork question" , turnId : "first-fork-turn" },
{ role : "user" , content : "second fork question" , turnId : secondTurnId },
2026-06-22 21:39:42 +08:00
],
),
);
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-fork" )}
title = "Chat chat-fork"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "first fork question" )). toBeInTheDocument ());
await act ( async () => {
client . _emitChat ( "chat-fork" , {
event : "message" ,
chat_id : "chat-fork" ,
2026-10-21 18:33:53 +08:00
text : "first fork answer" , turn_id : "first-fork-turn" , turn_seq : 2 ,
2026-06-22 21:39:42 +08:00
});
});
expect ( screen . getByText ( "first fork answer" )). toBeInTheDocument ();
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "second fork question" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() =>
expectSendMessageWithTurn ( client , "chat-fork" , "second fork question" ),
);
2026-10-21 18:33:53 +08:00
secondTurnId = client . sendMessage . mock . calls [ 0 ] ? .[ 3 ] ? . turnId ?? "" ;
expect ( secondTurnId ). not . toBe ( "" );
2026-06-22 21:39:42 +08:00
expect ( screen . getByText ( "second fork question" )). toBeInTheDocument ();
await act ( async () => {
client . _emitSessionUpdate ( "chat-fork" );
});
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
2026-10-21 18:33:53 +08:00
const firstQuestion = screen . getByText ( "first fork question" );
const firstAnswer = screen . getByText ( "first fork answer" );
const secondQuestion = screen . getByText ( "second fork question" );
expect ( firstQuestion . compareDocumentPosition ( firstAnswer ) & Node . DOCUMENT_POSITION_FOLLOWING ). toBeTruthy ();
expect ( firstAnswer . compareDocumentPosition ( secondQuestion ) & Node . DOCUMENT_POSITION_FOLLOWING ). toBeTruthy ();
2026-06-22 21:39:42 +08:00
});
2026-07-28 11:40:01 +08:00
it ( "recovers a truncated streamed answer after reconnecting" , async () => {
const client = makeClient ();
2026-10-21 18:33:53 +08:00
const turnId = "resume-turn" ;
const streamId = "resume-answer" ;
2026-07-28 11:40:01 +08:00
let historyCalls = 0 ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Aresume-chat/webui-thread" )) {
historyCalls += 1 ;
2026-10-21 18:33:53 +08:00
return httpJson ({
... streamedThreadPayload ( "resume-chat" ,
2026-07-28 11:40:01 +08:00
historyCalls === 1
2026-10-21 18:33:53 +08:00
? [{ role : "user" , content : "question" , turnId }]
2026-07-28 11:40:01 +08:00
: [
2026-10-21 18:33:53 +08:00
{ role : "user" , content : "question" , turnId },
{ role : "assistant" , content : "partial answer completed while away" , turnId , streamId },
2026-07-28 11:40:01 +08:00
],
2026-10-21 18:33:53 +08:00
historyCalls === 1 ? [] : [ turnId ],
2026-07-28 11:40:01 +08:00
),
2026-10-21 18:33:53 +08:00
has_pending_tool_calls : historyCalls === 1 ,
});
2026-07-28 11:40:01 +08:00
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "resume-chat" )}
title = "Resume chat"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "question" )). toBeInTheDocument ());
act (() => {
client . _emitChat ( "resume-chat" , {
event : "goal_status" ,
2026-10-21 18:33:53 +08:00
chat_id : "resume-chat" , turn_id : turnId ,
2026-07-28 11:40:01 +08:00
status : "running" ,
started_at : 1_700 ,
});
client . _emitChat ( "resume-chat" , {
event : "delta" ,
2026-10-21 18:33:53 +08:00
chat_id : "resume-chat" , turn_id : turnId , turn_seq : 2 , stream_id : streamId ,
2026-07-28 11:40:01 +08:00
text : "partial answer" ,
});
});
await waitFor (() => expect ( screen . getByText ( "partial answer" )). toBeInTheDocument ());
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
expect ( historyCalls ). toBe ( 1 );
act (() => client . _emitStatus ( "reconnecting" ));
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
act (() => client . _emitStatus ( "open" ));
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
await waitFor (() =>
expect ( screen . getByText ( "partial answer completed while away" )). toBeInTheDocument (),
);
expect ( screen . queryByText ( "partial answer" )). not . toBeInTheDocument ();
expect ( screen . queryByRole ( "button" , { name : "Stop response" })). not . toBeInTheDocument ();
});
2026-10-16 11:38:05 +08:00
it ( "adopts a completed canonical cache when reconnect revalidation returns 304" , async () => {
const client = makeClient ();
const chatId = "reconnect-not-modified" ;
const turnId = "turn-cached-completion" ;
let historyCalls = 0 ;
vi . stubGlobal ( "fetch" , vi . fn ( async ( input : RequestInfo | URL ) => {
if ( ! String ( input ). includes ( `websocket%3A ${ chatId } /webui-thread` )) {
return { ok : false , status : 404 , json : async () => ({}) };
}
historyCalls += 1 ;
if ( historyCalls > 1 ) return { ok : false , status : 304 };
return httpJson ({
2026-10-21 18:33:53 +08:00
... streamedThreadPayload ( chatId , [{ role : "user" , content : "question" , turnId }]),
2026-10-16 11:38:05 +08:00
has_pending_tool_calls : true ,
});
}));
render ( wrap ( client , < ThreadShell
session = { session ( chatId )} title = "Cached completion"
2026-10-26 21:45:36 +08:00
onToggleSidebar = {() => {}}
2026-10-16 11:38:05 +08:00
/>));
await screen . findByText ( "question" );
act (() => {
client . _emitChat ( chatId , {
event : "goal_status" , chat_id : chatId , turn_id : turnId ,
status : "running" , started_at : 1_700 ,
});
client . _emitChat ( chatId , {
2026-10-21 18:33:53 +08:00
event : "delta" , chat_id : chatId , turn_id : turnId , turn_seq : 2 ,
stream_id : "cached-answer" , text : "cached prefix" ,
2026-10-16 11:38:05 +08:00
});
});
await screen . findByText ( "cached prefix" );
act (() => client . _emitStatus ( "reconnecting" ));
// The reconnect coordinator can cache this response before the mounted
// thread's conditional request returns the same body through HTTP 304.
2026-10-21 18:33:53 +08:00
act (() => publishReconnectCompletion ( client , chatId , {
... streamedThreadPayload ( chatId , [
{ role : "user" , content : "question" , turnId },
{ role : "assistant" , content : "full cached answer" , turnId , streamId : "cached-answer" },
], [ turnId ]),
2026-10-16 11:38:05 +08:00
revision : "completed-revision" ,
has_pending_tool_calls : false ,
2026-10-21 18:33:53 +08:00
}));
expect ( client . reconcileCanonicalCompletion ). toHaveBeenCalledTimes ( 1 );
2026-10-16 11:38:05 +08:00
act (() => client . _emitStatus ( "open" ));
await screen . findByText ( "full cached answer" );
expect ( historyCalls ). toBe ( 2 );
expect ( screen . queryByText ( "cached prefix" )). not . toBeInTheDocument ();
expect ( screen . queryByRole ( "button" , { name : "Stop response" })). not . toBeInTheDocument ();
});
it ( "shows externally published completion before an older mounted reconnect read returns" , async () => {
const client = makeClient ();
const chatId = "published-completion-race" ;
const turnId = "published-completed-turn" ;
let historyCalls = 0 ;
let finishOlderRead !: ( response : ReturnType < typeof httpJson >) => void ;
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => {
if ( ! String ( input ). includes ( `websocket%3A ${ chatId } /webui-thread` )) {
return Promise . resolve ({ ok : false , status : 404 , json : async () => ({}) });
}
historyCalls += 1 ;
if ( historyCalls === 1 ) return Promise . resolve ( httpJson ({
2026-10-21 18:33:53 +08:00
... streamedThreadPayload ( chatId , [{ role : "user" , content : "question" , turnId }]),
2026-10-16 11:38:05 +08:00
has_pending_tool_calls : true ,
}));
return new Promise < ReturnType < typeof httpJson >>(( resolve ) => { finishOlderRead = resolve ; });
}));
render ( wrap ( client , < ThreadShell
session = { session ( chatId )} title = "Published completion"
2026-10-26 21:45:36 +08:00
onToggleSidebar = {() => {}}
2026-10-16 11:38:05 +08:00
/>));
await screen . findByText ( "question" );
act (() => {
client . _emitChat ( chatId , {
event : "goal_status" , chat_id : chatId , turn_id : turnId ,
status : "running" , started_at : 1_700 ,
});
client . _emitChat ( chatId , {
2026-10-21 18:33:53 +08:00
event : "delta" , chat_id : chatId , turn_id : turnId , turn_seq : 2 ,
stream_id : "published-answer" , text : "old active prefix" ,
2026-10-16 11:38:05 +08:00
});
});
await screen . findByText ( "old active prefix" );
act (() => client . _emitStatus ( "reconnecting" ));
act (() => client . _emitStatus ( "open" ));
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
2026-10-21 18:33:53 +08:00
const completed = {
... streamedThreadPayload ( chatId , [
2026-10-16 11:38:05 +08:00
{ role : "user" , content : "question" , turnId },
2026-10-21 18:33:53 +08:00
{ role : "assistant" , content : "externally published final answer" , turnId , streamId : "published-answer" },
], [ turnId ]),
2026-10-16 11:38:05 +08:00
revision : "completed-revision" ,
has_pending_tool_calls : false ,
2026-10-21 18:33:53 +08:00
};
act (() => publishReconnectCompletion ( client , chatId , completed ));
expect ( client . reconcileCanonicalCompletion ). toHaveBeenCalledTimes ( 1 );
2026-10-16 11:38:05 +08:00
await screen . findByText ( "externally published final answer" );
expect ( screen . queryByRole ( "button" , { name : "Stop response" })). not . toBeInTheDocument ();
await act ( async () => finishOlderRead ( httpJson ({
2026-10-21 18:33:53 +08:00
... streamedThreadPayload ( chatId , [{ role : "user" , content : "question" , turnId }]),
2026-10-16 11:38:05 +08:00
revision : "older-active-revision" ,
has_pending_tool_calls : true ,
active_turn_id : turnId ,
completed_turn_ids : [],
})));
expect ( screen . getByText ( "externally published final answer" )). toBeInTheDocument ();
expect ( screen . queryByText ( "old active prefix" )). not . toBeInTheDocument ();
expect ( screen . queryByRole ( "button" , { name : "Stop response" })). not . toBeInTheDocument ();
expect ( webuiThreadCache . get ( `websocket: ${ chatId } ` )). toBe ( completed );
2026-10-21 18:33:53 +08:00
expect ( client . reconcileCanonicalCompletion ). toHaveBeenCalledTimes ( 1 );
2026-10-16 11:38:05 +08:00
});
2026-07-28 11:40:01 +08:00
it ( "refreshes after opening when mounted while the socket is reconnecting" , async () => {
const client = makeClient ();
client . _emitStatus ( "reconnecting" );
let historyCalls = 0 ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
if ( String ( input ). includes ( "websocket%3Amount-during-reconnect/webui-thread" )) {
historyCalls += 1 ;
return httpJson ( transcriptFromSimpleMessages (
historyCalls === 1
? [{ role : "user" , content : "question before reconnect" }]
: [
{ role : "user" , content : "question before reconnect" },
{ role : "assistant" , content : "answer completed before open" },
],
));
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "mount-during-reconnect" )}
title = "Mount during reconnect"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "question before reconnect" )). toBeInTheDocument ());
expect ( historyCalls ). toBe ( 1 );
act (() => client . _emitStatus ( "open" ));
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
await waitFor (() =>
expect ( screen . getByText ( "answer completed before open" )). toBeInTheDocument (),
);
});
it ( "adopts a disjoint authoritative latest-window reset after overlap falls out" , async () => {
const client = makeClient ();
let historyCalls = 0 ;
const canonicalTurnId = "turn-new-window" ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
if ( String ( input ). includes ( "websocket%3Awindow-reset-chat/webui-thread" )) {
historyCalls += 1 ;
return httpJson ({
... transcriptFromSimpleMessages (
historyCalls === 1
? [
{
2026-10-21 18:33:53 +08:00
id : "expired-window-replay" , role : "assistant" ,
2026-07-28 11:40:01 +08:00
content : "row from the expired latest window" ,
turnId : "turn-old-window" ,
},
]
: [
{
role : "user" ,
content : "question in the new latest window" ,
turnId : canonicalTurnId ,
},
{
2026-10-21 18:33:53 +08:00
id : "new-window-replay" , role : "assistant" ,
2026-07-28 11:40:01 +08:00
content : "answer in the new latest window" ,
turnId : canonicalTurnId ,
},
],
),
has_pending_tool_calls : false ,
});
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "window-reset-chat" )}
title = "Window reset"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() =>
expect ( screen . getByText ( "row from the expired latest window" )). toBeInTheDocument (),
);
2026-07-30 10:25:22 +08:00
act (() => client . _emitSessionUpdate ( "window-reset-chat" , "thread" ));
2026-07-28 11:40:01 +08:00
await waitFor (() =>
expect ( screen . getByText ( "answer in the new latest window" )). toBeInTheDocument (),
);
expect ( screen . queryByText ( "row from the expired latest window" )). not . toBeInTheDocument ();
expect ( client . reconcileCanonicalCompletion ). toHaveBeenCalledWith (
"window-reset-chat" ,
expect . any ( Number ),
expect . arrayContaining ([ canonicalTurnId ]),
{
observedTurnIds : [ canonicalTurnId ],
hasPendingToolCalls : false ,
activeTurnId : null ,
2026-10-16 11:38:05 +08:00
completionIdsProvided : false ,
2026-07-28 11:40:01 +08:00
},
);
});
2026-11-12 16:08:48 +08:00
it ( "adopts a disjoint latest window immediately when returning to a cached session" , async () => {
2026-07-28 11:40:01 +08:00
const client = makeClient ();
let chatACalls = 0 ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Alineage-chat-a/webui-thread" )) {
chatACalls += 1 ;
return httpJson ({
... transcriptFromSimpleMessages (
chatACalls === 1
2026-10-21 18:33:53 +08:00
? [{ id : "old-lineage-replay" , role : "assistant" , content : "committed old lineage" }]
: [{ id : "new-lineage-replay" , role : "assistant" , content : "disjoint new lineage" }],
2026-07-28 11:40:01 +08:00
),
has_pending_tool_calls : false ,
});
}
if ( url . includes ( "websocket%3Alineage-chat-b/webui-thread" )) {
return httpJson ( transcriptFromSimpleMessages ([
{ role : "assistant" , content : "other lineage chat" },
]));
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
const view = ( chatId : string ) => wrap (
client ,
< ThreadShell
session = { session ( chatId )}
title = { `Chat ${ chatId } ` }
onToggleSidebar = {() => {}}
/>,
);
const { rerender } = render ( view ( "lineage-chat-a" ));
await waitFor (() => expect ( screen . getByText ( "committed old lineage" )). toBeInTheDocument ());
rerender ( view ( "lineage-chat-b" ));
await waitFor (() => expect ( screen . getByText ( "other lineage chat" )). toBeInTheDocument ());
rerender ( view ( "lineage-chat-a" ));
await waitFor (() => expect ( chatACalls ). toBe ( 2 ));
2026-11-12 16:08:48 +08:00
expect ( await screen . findByText ( "disjoint new lineage" )). toBeInTheDocument ();
expect ( screen . queryByText ( "committed old lineage" )). not . toBeInTheDocument ();
2026-07-28 11:40:01 +08:00
2026-07-30 10:25:22 +08:00
act (() => client . _emitSessionUpdate ( "lineage-chat-a" , "thread" ));
2026-07-28 11:40:01 +08:00
await waitFor (() => expect ( chatACalls ). toBe ( 3 ));
await waitFor (() => expect ( screen . getByText ( "disjoint new lineage" )). toBeInTheDocument ());
expect ( screen . queryByText ( "committed old lineage" )). not . toBeInTheDocument ();
});
it ( "does not reset away a durable UI tail that arrives after the request" , async () => {
const client = makeClient ();
let historyCalls = 0 ;
let resolveRefresh :
| (( value : ReturnType < typeof httpJson >) => void )
| null = null ;
vi . stubGlobal (
"fetch" ,
vi . fn (( input : RequestInfo | URL ) => {
if ( ! String ( input ). includes ( "websocket%3Areset-tail-race/webui-thread" )) {
return Promise . resolve ({
ok : false ,
status : 404 ,
json : async () => ({}),
});
}
historyCalls += 1 ;
if ( historyCalls === 1 ) {
return Promise . resolve ( httpJson ( transcriptFromSimpleMessages ([
2026-10-21 18:33:53 +08:00
{ id : "old-canonical-replay" , role : "assistant" , content : "old canonical row" },
2026-07-28 11:40:01 +08:00
])));
}
return new Promise (( resolve ) => {
resolveRefresh = resolve ;
});
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "reset-tail-race" )}
title = "Reset tail race"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "old canonical row" )). toBeInTheDocument ());
2026-07-30 10:25:22 +08:00
act (() => client . _emitSessionUpdate ( "reset-tail-race" , "thread" ));
2026-07-28 11:40:01 +08:00
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
act (() => {
client . _emitChat ( "reset-tail-race" , {
event : "message" ,
chat_id : "reset-tail-race" ,
2026-10-21 18:33:53 +08:00
text : "local durable row after request" , turn_id : "durable-post-request-turn" , turn_seq : 2 ,
2026-07-28 11:40:01 +08:00
});
});
await waitFor (() =>
expect ( screen . getByText ( "local durable row after request" )). toBeInTheDocument (),
);
await act ( async () => {
resolveRefresh ? .( httpJson ({
... transcriptFromSimpleMessages ([
2026-10-21 18:33:53 +08:00
{ id : "disjoint-canonical-replay" , role : "assistant" , content : "disjoint canonical reset row" },
2026-07-28 11:40:01 +08:00
]),
has_pending_tool_calls : false ,
}));
await Promise . resolve ();
});
expect ( screen . getByText ( "old canonical row" )). toBeInTheDocument ();
expect ( screen . getByText ( "local durable row after request" )). toBeInTheDocument ();
expect ( screen . queryByText ( "disjoint canonical reset row" )). not . toBeInTheDocument ();
});
it ( "safely commits an empty canonical reset for a rejected local turn" , async () => {
const client = makeClient ();
let historyCalls = 0 ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
if ( String ( input ). includes ( "websocket%3Aempty-reset-chat/webui-thread" )) {
historyCalls += 1 ;
2026-10-21 18:33:53 +08:00
if ( historyCalls > 1 ) return httpJson ({
schemaVersion : 3 , projection : "events" , events : [], has_pending_tool_calls : false ,
});
2026-07-28 11:40:01 +08:00
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "empty-reset-chat" )}
title = "Empty reset"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( historyCalls ). toBe ( 1 ));
2026-08-18 18:28:19 +08:00
const input = screen . getByRole ( "textbox" , { name : "Message input" });
2026-07-28 11:40:01 +08:00
fireEvent . change ( input , { target : { value : "rejected local turn" } });
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( screen . getByText ( "rejected local turn" )). toBeInTheDocument ());
2026-10-21 18:33:53 +08:00
const rejectedTurnId = client . sendMessage . mock . calls [ 0 ] ? .[ 3 ] ? . turnId ;
expect ( rejectedTurnId ). toBeTruthy ();
act (() => client . _emitError ({
kind : "turn_rejected" , chatId : "empty-reset-chat" , turnId : rejectedTurnId ! ,
detail : "message_rejected" ,
}));
2026-07-28 11:40:01 +08:00
2026-10-24 00:43:34 +08:00
act (() => {
client . _emitError ({
kind : "turn_rejected" , chatId : "empty-reset-chat" ,
turnId : client.sendMessage.mock.calls [ 0 ][ 3 ] ! . turnId ! ,
});
client . _emitSessionUpdate ( "empty-reset-chat" , "thread" );
});
2026-07-28 11:40:01 +08:00
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
await waitFor (() =>
expect ( screen . queryByText ( "rejected local turn" )). not . toBeInTheDocument (),
);
expect ( client . reconcileCanonicalCompletion ). toHaveBeenCalledWith (
"empty-reset-chat" ,
expect . any ( Number ),
[],
{
observedTurnIds : [],
hasPendingToolCalls : false ,
activeTurnId : null ,
2026-10-16 11:38:05 +08:00
completionIdsProvided : false ,
2026-07-28 11:40:01 +08:00
},
);
});
it ( "runs canonical reconciliation once when React replays state calculations" , async () => {
const client = makeClient ();
const turnId = "turn-strict-canonical" ;
let canonicalComplete = false ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
if ( String ( input ). includes ( "websocket%3Astrict-canonical/webui-thread" )) {
return httpJson ({
2026-10-21 18:33:53 +08:00
... streamedThreadPayload ( "strict-canonical" ,
2026-07-28 11:40:01 +08:00
canonicalComplete
? [
{ role : "user" , content : "strict question" , turnId },
2026-10-21 18:33:53 +08:00
{ role : "assistant" , content : "strict canonical answer" , turnId , streamId : "strict-answer" },
2026-07-28 11:40:01 +08:00
]
: [{ role : "user" , content : "strict question" , turnId }],
2026-10-21 18:33:53 +08:00
canonicalComplete ? [ turnId ] : [],
2026-07-28 11:40:01 +08:00
),
has_pending_tool_calls : ! canonicalComplete ,
});
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
render (
wrap (
client ,
< StrictMode >
< ThreadShell
session = { session ( "strict-canonical" )}
title = "Strict canonical"
onToggleSidebar = {() => {}}
/>
</ StrictMode >,
),
);
await waitFor (() => expect ( screen . getByText ( "strict question" )). toBeInTheDocument ());
act (() => {
client . _emitChat ( "strict-canonical" , {
event : "goal_status" ,
chat_id : "strict-canonical" ,
status : "running" ,
started_at : 2_100 ,
turn_id : turnId ,
});
client . _emitChat ( "strict-canonical" , {
event : "delta" ,
chat_id : "strict-canonical" ,
text : "strict partial" ,
2026-10-21 18:33:53 +08:00
turn_id : turnId , turn_seq : 2 , stream_id : "strict-answer" ,
2026-07-28 11:40:01 +08:00
});
});
await waitFor (() => expect ( screen . getByText ( "strict partial" )). toBeInTheDocument ());
client . reconcileCanonicalCompletion . mockClear ();
canonicalComplete = true ;
2026-07-30 10:25:22 +08:00
act (() => client . _emitSessionUpdate ( "strict-canonical" , "thread" ));
2026-07-28 11:40:01 +08:00
await waitFor (() => expect ( screen . getByText ( "strict canonical answer" )). toBeInTheDocument ());
expect ( client . reconcileCanonicalCompletion ). toHaveBeenCalledTimes ( 1 );
expect ( client . canReconcileCanonicalCompletion ). toHaveBeenCalled ();
});
2026-10-21 18:33:53 +08:00
it ( "keeps completed content while a newer run blocks lifecycle reconciliation" , async () => {
2026-07-28 11:40:01 +08:00
const client = makeClient ();
2026-10-21 18:33:53 +08:00
const chatId = "layout-recheck" ;
2026-07-28 11:40:01 +08:00
const turnId = "turn-layout-recheck" ;
2026-10-21 18:33:53 +08:00
const newerTurnId = "newer-layout-turn" ;
2026-07-28 11:40:01 +08:00
let historyCalls = 0 ;
2026-10-21 18:33:53 +08:00
let finishRefresh !: ( response : Response ) => void ;
const completedBody = ( includeNewer : boolean ) => {
const rows : StreamedFixtureRow [] = [
{ role : "user" , content : "layout question" , turnId },
{ role : "assistant" , content : "layout canonical answer" , turnId , streamId : "layout-answer" },
];
if ( includeNewer ) rows . push (
{ role : "user" , content : "newer layout question" , turnId : newerTurnId },
{ role : "assistant" , content : "newer layout complete" , turnId : newerTurnId , streamId : "newer-layout-answer" },
);
return {
... streamedThreadPayload ( chatId , rows , includeNewer ? [ turnId , newerTurnId ] : [ turnId ]),
has_pending_tool_calls : false ,
};
};
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => {
if ( ! String ( input ). includes ( `websocket%3A ${ chatId } /webui-thread` )) {
return Promise . resolve ({ ok : false , status : 404 , json : async () => ({}) });
}
historyCalls += 1 ;
if ( historyCalls === 1 ) return Promise . resolve ( httpJson ({
... streamedThreadPayload ( chatId , [{ role : "user" , content : "layout question" , turnId }]),
has_pending_tool_calls : true ,
}));
if ( historyCalls === 2 ) return new Promise < Response >(( resolve ) => { finishRefresh = resolve ; });
return Promise . resolve ( httpJson ( completedBody ( true )));
}));
render ( wrap ( client , < ThreadShell session = { session ( chatId )} title = "Layout recheck"
2026-10-26 21:45:36 +08:00
onToggleSidebar = {() => {}} />));
2026-10-21 18:33:53 +08:00
await screen . findByText ( "layout question" );
2026-07-28 11:40:01 +08:00
act (() => {
2026-10-21 18:33:53 +08:00
client . _emitChat ( chatId , {
event : "goal_status" , chat_id : chatId , status : "running" , started_at : 2_200 , turn_id : turnId ,
2026-07-28 11:40:01 +08:00
});
2026-10-21 18:33:53 +08:00
client . _emitChat ( chatId , {
event : "delta" , chat_id : chatId , text : "layout partial" , turn_id : turnId ,
turn_seq : 2 , stream_id : "layout-answer" ,
2026-07-28 11:40:01 +08:00
});
});
2026-10-21 18:33:53 +08:00
await screen . findByText ( "layout partial" );
act (() => client . _emitSessionUpdate ( chatId , "thread" ));
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
2026-07-28 11:40:01 +08:00
2026-10-21 18:33:53 +08:00
// Another tab starts a newer turn while this read is pending. Its running
// status invalidates settlement before the pure preflight runs.
act (() => {
for ( const event of streamedThreadPayload ( chatId , [
{ role : "user" , content : "newer layout question" , turnId : newerTurnId },
]). events ) client . _emitChat ( chatId , event );
client . _emitChat ( chatId , {
event : "goal_status" , chat_id : chatId , status : "running" , started_at : 2_300 , turn_id : newerTurnId ,
});
client . _emitChat ( chatId , {
event : "delta" , chat_id : chatId , text : "newer layout partial" , turn_id : newerTurnId ,
turn_seq : 2 , stream_id : "newer-layout-answer" ,
});
2026-10-19 17:31:52 +08:00
});
2026-10-21 18:33:53 +08:00
await screen . findByText ( "newer layout partial" );
await act ( async () => finishRefresh ( httpJson ( completedBody ( false ))));
await screen . findByText ( "layout canonical answer" );
expect ( screen . queryByText ( "layout partial" )). not . toBeInTheDocument ();
expect ( screen . getByText ( "newer layout partial" )). toBeInTheDocument ();
expect ( client . reconcileCanonicalCompletion ). not . toHaveBeenCalled ();
expect ( client . isRunCompleted ( chatId , turnId )). toBe ( true );
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
2026-07-28 11:40:01 +08:00
2026-10-21 18:33:53 +08:00
act (() => client . _emitSessionUpdate ( chatId , "thread" ));
await screen . findByText ( "newer layout complete" );
expect ( historyCalls ). toBe ( 3 );
expect ( screen . getByText ( "layout canonical answer" )). toBeInTheDocument ();
expect ( screen . queryByText ( "layout partial" )). not . toBeInTheDocument ();
expect ( screen . queryByText ( "newer layout partial" )). not . toBeInTheDocument ();
expect ( screen . queryByRole ( "button" , { name : "Stop response" })). not . toBeInTheDocument ();
expect ( client . reconcileCanonicalCompletion ). toHaveBeenCalledTimes ( 1 );
2026-07-28 11:40:01 +08:00
});
2026-10-16 11:38:05 +08:00
it ( "adopts a completed equal-length history when returning after an inactive outage" , async () => {
2026-07-28 11:40:01 +08:00
const client = makeClient ();
const oldTurnId = "turn-old" ;
let newTurnId = "" ;
let chatACalls = 0 ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Achat-version-a/webui-thread" )) {
chatACalls += 1 ;
2026-10-21 18:33:53 +08:00
const rows : StreamedFixtureRow [] = [
{ role : "user" , content : "old question" , turnId : oldTurnId },
{ role : "assistant" , content : "old answer" , turnId : oldTurnId , streamId : "old-answer" },
];
if ( chatACalls > 2 ) rows . push (
{ role : "user" , content : "new question" , turnId : newTurnId },
{ role : "assistant" , content : "partial answer completed" , turnId : newTurnId , streamId : "new-answer" },
);
2026-07-28 11:40:01 +08:00
return httpJson ({
2026-10-21 18:33:53 +08:00
... streamedThreadPayload ( "chat-version-a" , rows , chatACalls <= 2 ? [ oldTurnId ] : [ oldTurnId , newTurnId ]),
2026-07-28 11:40:01 +08:00
has_pending_tool_calls : false ,
});
}
if ( url . includes ( "websocket%3Achat-version-b/webui-thread" )) {
return httpJson ( transcriptFromSimpleMessages ([
{ role : "user" , content : "other chat" },
]));
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
const view = ( chatId : string ) => wrap (
client ,
< ThreadShell
session = { session ( chatId )}
title = { `Chat ${ chatId } ` }
onToggleSidebar = {() => {}}
/>,
);
const { rerender } = render ( view ( "chat-version-a" ));
await waitFor (() => expect ( screen . getByText ( "old answer" )). toBeInTheDocument ());
act (() => client . _emitSessionUpdate ( "chat-version-a" ));
await waitFor (() => expect ( chatACalls ). toBe ( 2 ));
2026-08-18 18:28:19 +08:00
fireEvent . change ( screen . getByRole ( "textbox" , { name : "Message input" }), {
2026-07-28 11:40:01 +08:00
target : { value : "new question" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( client . sendMessage ). toHaveBeenCalledTimes ( 1 ));
newTurnId = (
client . sendMessage . mock . calls [ 0 ] ? .[ 3 ] as { turnId? : string } | undefined
) ? . turnId ?? "" ;
expect ( newTurnId ). not . toBe ( "" );
act (() => {
client . _emitChat ( "chat-version-a" , {
event : "goal_status" ,
chat_id : "chat-version-a" ,
status : "running" ,
started_at : 2_000 ,
turn_id : newTurnId ,
});
client . _emitChat ( "chat-version-a" , {
event : "delta" ,
chat_id : "chat-version-a" ,
text : "partial answer" ,
2026-10-21 18:33:53 +08:00
turn_id : newTurnId , turn_seq : 2 , stream_id : "new-answer" ,
2026-07-28 11:40:01 +08:00
});
});
await waitFor (() => expect ( screen . getByText ( "partial answer" )). toBeInTheDocument ());
rerender ( view ( "chat-version-b" ));
await waitFor (() => expect ( screen . getByText ( "other chat" )). toBeInTheDocument ());
act (() => client . _emitStatus ( "reconnecting" ));
act (() => client . _emitStatus ( "open" ));
2026-10-16 11:38:05 +08:00
rerender ( view ( "chat-version-a" ));
await waitFor (() => expect ( chatACalls ). toBe ( 3 ));
2026-07-28 11:40:01 +08:00
await waitFor (() =>
expect ( screen . getByText ( "partial answer completed" )). toBeInTheDocument (),
);
expect ( screen . queryByText ( "partial answer" )). not . toBeInTheDocument ();
expect ( screen . queryByRole ( "button" , { name : "Stop response" })). not . toBeInTheDocument ();
});
it ( "does not let an older completed snapshot clear a run that starts in flight" , async () => {
const client = makeClient ();
const oldTurnId = "turn-before-refresh" ;
let historyCalls = 0 ;
let resolveRefresh :
| (( value : { ok : boolean ; status : number ; json : () => Promise < unknown > }) => void )
| null = null ;
vi . stubGlobal (
"fetch" ,
vi . fn (( input : RequestInfo | URL ) => {
const url = String ( input );
if ( ! url . includes ( "websocket%3Arun-generation-chat/webui-thread" )) {
return Promise . resolve ({
ok : false ,
status : 404 ,
json : async () => ({}),
});
}
historyCalls += 1 ;
if ( historyCalls === 1 ) {
return Promise . resolve ( httpJson ( transcriptFromSimpleMessages ([
{ role : "user" , content : "old question" , turnId : oldTurnId },
{ role : "assistant" , content : "old answer" , turnId : oldTurnId },
])));
}
return new Promise (( resolve ) => {
resolveRefresh = resolve ;
});
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "run-generation-chat" )}
title = "Run generation chat"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "old answer" )). toBeInTheDocument ());
2026-07-30 10:25:22 +08:00
act (() => client . _emitSessionUpdate ( "run-generation-chat" , "thread" ));
2026-07-28 11:40:01 +08:00
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
const newTurnId = "turn-started-during-refresh" ;
act (() => {
client . _emitChat ( "run-generation-chat" , {
event : "goal_status" ,
chat_id : "run-generation-chat" ,
status : "running" ,
started_at : 3_000 ,
turn_id : newTurnId ,
});
});
2026-08-18 18:28:19 +08:00
const input = screen . getByRole ( "textbox" , { name : "Message input" });
2026-07-28 11:40:01 +08:00
fireEvent . change ( input , { target : { value : "queued for the new run" } });
fireEvent . keyDown ( input , { key : "Enter" });
expect ( client . sendMessage ). not . toHaveBeenCalled ();
await act ( async () => {
resolveRefresh ? .( httpJson ({
... transcriptFromSimpleMessages ([
{ role : "user" , content : "old question" , turnId : oldTurnId },
{ role : "assistant" , content : "old answer" , turnId : oldTurnId },
]),
has_pending_tool_calls : false ,
}));
await Promise . resolve ();
});
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
expect ( client . sendMessage ). not . toHaveBeenCalled ();
});
2026-10-21 18:33:53 +08:00
it . each ([ "raw-turn" , "session-message" ] as const )( "keeps repeated guidance order and newer live output with stable %s sources" , async ( guidanceIdentity ) => {
2026-10-16 11:38:05 +08:00
const client = makeClient ();
const chatId = "completed-guidance-new-tail" ;
const turnId = "completed-guided-turn" ;
2026-10-21 18:33:53 +08:00
const guidanceRows = [ "guidance-input" , "repeated-guidance-input" ]. map (( id ) : StreamedFixtureRow => ({
role : "user" , content : "supplemental guidance" , startsTurn : false , activeTurnId : turnId ,
...( guidanceIdentity === "raw-turn"
? { turnId : id }
: { sessionMessage : { message_id : id , session : { id : "guidance-session" , name : "Guidance" } } }),
}));
2026-10-16 11:38:05 +08:00
let historyCalls = 0 ;
let resolveRefresh !: ( response : ReturnType < typeof httpJson >) => void ;
vi . stubGlobal ( "fetch" , vi . fn (( input : RequestInfo | URL ) => {
if ( ! String ( input ). includes ( `websocket%3A ${ chatId } /webui-thread` )) {
return Promise . resolve ({ ok : false , status : 404 , json : async () => ({}) });
}
historyCalls += 1 ;
if ( historyCalls === 1 ) return Promise . resolve ( httpJson ({
2026-10-21 18:33:53 +08:00
... streamedThreadPayload ( chatId , [{ role : "user" , content : "guided question" , turnId }]),
2026-10-16 11:38:05 +08:00
has_pending_tool_calls : true ,
}));
return new Promise < ReturnType < typeof httpJson >>(( resolve ) => { resolveRefresh = resolve ; });
}));
render ( wrap ( client , < ThreadShell
session = { session ( chatId )} title = "Guided turn"
2026-10-26 21:45:36 +08:00
onToggleSidebar = {() => {}}
2026-10-16 11:38:05 +08:00
/>));
await screen . findByText ( "guided question" );
act (() => {
client . _emitChat ( chatId , {
event : "goal_status" , chat_id : chatId , status : "running" ,
started_at : 1_700 , turn_id : turnId ,
});
client . _emitChat ( chatId , {
event : "delta" , chat_id : chatId , text : "first partial segment" , turn_id : turnId ,
2026-10-21 18:33:53 +08:00
turn_seq : 2 , stream_id : "guided-first-answer" ,
2026-10-16 11:38:05 +08:00
});
});
await screen . findByText ( "first partial segment" );
act (() => {
client . _emitChat ( chatId , {
event : "stream_end" , chat_id : chatId , turn_id : turnId , resuming : true ,
2026-10-21 18:33:53 +08:00
turn_seq : 3 , stream_id : "guided-first-answer" , text : "first partial segment" ,
2026-10-16 11:38:05 +08:00
});
2026-10-21 18:33:53 +08:00
for ( const event of streamedThreadPayload ( chatId , guidanceRows ). events ) client . _emitChat ( chatId , event );
2026-10-16 11:38:05 +08:00
client . _emitChat ( chatId , {
event : "delta" , chat_id : chatId , turn_id : turnId , text : "last partial segment" ,
2026-10-21 18:33:53 +08:00
turn_seq : 4 , stream_id : "guided-last-answer" ,
2026-10-16 11:38:05 +08:00
});
});
await screen . findByText ( "last partial segment" );
act (() => client . _emitSessionUpdate ( chatId , "thread" ));
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
act (() => client . _emitChat ( chatId , {
2026-10-21 18:33:53 +08:00
event : "turn_end" , chat_id : chatId , turn_id : turnId , turn_seq : 6 ,
2026-10-16 11:38:05 +08:00
}));
fireEvent . change ( screen . getByRole ( "textbox" , { name : "Message input" }), {
target : { value : "new local question" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
const newerTurnId = client . sendMessage . mock . calls [ 0 ] ? .[ 3 ] ? . turnId ;
expect ( newerTurnId ). toBeTruthy ();
act (() => {
client . _emitChat ( chatId , {
event : "goal_status" , chat_id : chatId , status : "running" ,
started_at : 2_000 , turn_id : newerTurnId ,
});
client . _emitChat ( chatId , {
event : "delta" , chat_id : chatId , turn_id : newerTurnId , text : "newer live reply" ,
2026-10-21 18:33:53 +08:00
turn_seq : 2 , stream_id : "newer-guidance-answer" ,
2026-10-16 11:38:05 +08:00
});
});
await screen . findByText ( "newer live reply" );
await act ( async () => resolveRefresh ( httpJson ({
2026-10-21 18:33:53 +08:00
... streamedThreadPayload ( chatId , [
2026-10-16 11:38:05 +08:00
{ role : "user" , content : "guided question" , turnId },
2026-10-21 18:33:53 +08:00
{ role : "assistant" , content : "canonical first segment" , turnId , streamId : "guided-first-answer" },
... guidanceRows ,
{ role : "assistant" , content : "canonical final segment" , turnId , streamId : "guided-last-answer" , textSeq : 4 , endSeq : 5 },
], [ turnId ]),
2026-10-16 11:38:05 +08:00
has_pending_tool_calls : false ,
})));
const first = await screen . findByText ( "canonical first segment" );
const guidance = screen . getAllByText ( "supplemental guidance" );
const final = screen . getByText ( "canonical final segment" );
const newer = screen . getByText ( "newer live reply" );
expect ( guidance ). toHaveLength ( 2 );
expect ( first . compareDocumentPosition ( guidance [ 0 ]) & Node . DOCUMENT_POSITION_FOLLOWING ). toBeTruthy ();
expect ( guidance [ 0 ]. compareDocumentPosition ( guidance [ 1 ]) & Node . DOCUMENT_POSITION_FOLLOWING ). toBeTruthy ();
expect ( guidance [ 1 ]. compareDocumentPosition ( final ) & Node . DOCUMENT_POSITION_FOLLOWING ). toBeTruthy ();
expect ( final . compareDocumentPosition ( newer ) & Node . DOCUMENT_POSITION_FOLLOWING ). toBeTruthy ();
expect ( screen . queryByText ( "first partial segment" )). not . toBeInTheDocument ();
expect ( screen . queryByText ( "last partial segment" )). not . toBeInTheDocument ();
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
act (() => {
client . _emitChat ( chatId , {
event : "delta" , chat_id : chatId , turn_id : turnId , text : "obsolete delayed delta" ,
2026-10-21 18:33:53 +08:00
turn_seq : 7 , stream_id : "guided-last-answer" ,
2026-10-16 11:38:05 +08:00
});
client . _emitChat ( chatId , {
event : "delta" , chat_id : chatId , turn_id : newerTurnId , text : " continued" ,
2026-10-21 18:33:53 +08:00
turn_seq : 3 , stream_id : "newer-guidance-answer" ,
2026-10-16 11:38:05 +08:00
});
});
await screen . findByText ( "newer live reply continued" );
expect ( screen . queryByText ( /obsolete delayed delta/ )). not . toBeInTheDocument ();
expect ( screen . queryByText ( "newer live reply" )). not . toBeInTheDocument ();
});
it ( "keeps canonical completed turns after an older cached pagination prefix" , async () => {
const client = makeClient ();
const chatId = "completed-window-order" ;
const completedTurnId = "completed-cached-turn" ;
const unseenTurnId = "other-tab-completed-turn" ;
const newerTurnId = "new-local-turn" ;
const messageCache = new ThreadMessageCache (() => false );
2026-10-21 18:33:53 +08:00
const owner = new ThreadTranscript ([
2026-10-16 11:38:05 +08:00
{ id : "older-page" , role : "assistant" , content : "older paginated answer" , createdAt : 1 },
2026-10-21 18:33:53 +08:00
]);
const cachedEvents = [
{ event : "user_message" , chat_id : chatId , turn_id : completedTurnId , turn_seq : 1 ,
text : "completed question" , starts_turn : true },
{ event : "delta" , chat_id : chatId , turn_id : completedTurnId , turn_seq : 2 ,
stream_id : "completed-cached-answer" , text : "outdated prefix" },
{ event : "user_message" , chat_id : chatId , turn_id : newerTurnId , turn_seq : 1 ,
text : "new local question" , starts_turn : true },
{ event : "delta" , chat_id : chatId , turn_id : newerTurnId , turn_seq : 2 ,
stream_id : "new-local-answer" , text : "new local stream" },
] satisfies ThreadProjectionEvent [];
cachedEvents . forEach (( event , index ) => owner . project ( event , {
createId : () => `cached- ${ index } ` , now : index + 2 ,
}));
messageCache . set ( chatId , owner . save ());
2026-10-16 11:38:05 +08:00
client . _emitChat ( chatId , {
event : "goal_status" , chat_id : chatId , turn_id : newerTurnId , status : "running" , started_at : 2_000 ,
});
vi . stubGlobal ( "fetch" , vi . fn ( async ( input : RequestInfo | URL ) => {
if ( ! String ( input ). includes ( `websocket%3A ${ chatId } /webui-thread` )) {
return { ok : false , status : 404 , json : async () => ({}) };
}
return httpJson ({
2026-10-21 18:33:53 +08:00
... streamedThreadPayload ( chatId , [
2026-10-16 11:38:05 +08:00
{ role : "user" , content : "completed question" , turnId : completedTurnId },
2026-10-21 18:33:53 +08:00
{ role : "assistant" , content : "completed reply" , turnId : completedTurnId , streamId : "completed-cached-answer" },
2026-10-16 11:38:05 +08:00
{ role : "user" , content : "other tab question" , turnId : unseenTurnId },
2026-10-21 18:33:53 +08:00
{ role : "assistant" , content : "other tab completed reply" , turnId : unseenTurnId , streamId : "other-tab-answer" },
], [ completedTurnId , unseenTurnId ]),
2026-10-16 11:38:05 +08:00
has_pending_tool_calls : false ,
completed_turn_ids : [ completedTurnId , unseenTurnId ],
page : { before_cursor : "older-page" , has_more_before : true , user_message_offset : 25 },
});
}));
render ( wrap ( client , < ThreadShell
session = { session ( chatId )} title = "Completed latest window" messageCache = { messageCache }
2026-10-26 21:45:36 +08:00
onToggleSidebar = {() => {}}
2026-10-16 11:38:05 +08:00
/>));
const completed = await screen . findByText ( "completed reply" );
const older = screen . getByText ( "older paginated answer" );
const other = screen . getByText ( "other tab completed reply" );
const newer = screen . getByText ( "new local stream" );
expect ( older . compareDocumentPosition ( completed ) & Node . DOCUMENT_POSITION_FOLLOWING ). toBeTruthy ();
expect ( completed . compareDocumentPosition ( other ) & Node . DOCUMENT_POSITION_FOLLOWING ). toBeTruthy ();
expect ( other . compareDocumentPosition ( newer ) & Node . DOCUMENT_POSITION_FOLLOWING ). toBeTruthy ();
expect ( screen . queryByText ( "outdated prefix" )). not . toBeInTheDocument ();
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
});
2026-10-21 18:33:53 +08:00
it . each ([ "raw-turn" , "session-message" ] as const )( "keeps completed guidance after a paginated prefix with stable %s sources" , async ( guidanceIdentity ) => {
2026-10-16 11:38:05 +08:00
const client = makeClient ();
const chatId = "completed-guidance-paged-prefix" ;
2026-10-21 18:33:53 +08:00
const guidanceRow : StreamedFixtureRow = {
role : "user" , content : "continue" , startsTurn : false , activeTurnId : "main" ,
...( guidanceIdentity === "raw-turn"
? { turnId : "guidance" }
: { sessionMessage : { message_id : "cached-guidance" , session : { id : "guidance-session" , name : "Guidance" } } }),
};
2026-10-16 11:38:05 +08:00
const messageCache = new ThreadMessageCache (() => false );
2026-10-21 18:33:53 +08:00
const owner = new ThreadTranscript ([
2026-10-16 11:38:05 +08:00
{ id : "old-user" , role : "user" , content : "continue" , createdAt : 1 },
{ id : "old-answer" , role : "assistant" , content : "older answer" , createdAt : 2 },
2026-10-21 18:33:53 +08:00
]);
const cachedEvents = [
{ event : "user_message" , chat_id : chatId , turn_id : "main" , turn_seq : 1 ,
text : "current question" , starts_turn : true },
{ event : "delta" , chat_id : chatId , turn_id : "main" , turn_seq : 2 ,
stream_id : "main-first-answer" , text : "first partial" },
... streamedThreadPayload ( chatId , [ guidanceRow ]). events ,
{ event : "delta" , chat_id : chatId , turn_id : "main" , turn_seq : 4 ,
stream_id : "main-last-answer" , text : "last partial" },
{ event : "user_message" , chat_id : chatId , turn_id : "new" , turn_seq : 1 ,
text : "new question" , starts_turn : true },
{ event : "delta" , chat_id : chatId , turn_id : "new" , turn_seq : 2 ,
stream_id : "new-live-answer" , text : "new live answer" },
] satisfies ThreadProjectionEvent [];
cachedEvents . forEach (( event , index ) => owner . project ( event , {
createId : () => `cached- ${ index } ` , now : index + 3 ,
}));
messageCache . set ( chatId , owner . save ());
2026-10-16 11:38:05 +08:00
client . _emitChat ( chatId , {
event : "goal_status" , chat_id : chatId , turn_id : "new" , status : "running" , started_at : 2_000 ,
});
vi . stubGlobal ( "fetch" , vi . fn ( async ( input : RequestInfo | URL ) => {
if ( ! String ( input ). includes ( `websocket%3A ${ chatId } /webui-thread` )) {
return { ok : false , status : 404 , json : async () => ({}) };
}
return httpJson ({
2026-10-21 18:33:53 +08:00
... streamedThreadPayload ( chatId , [
2026-10-16 11:38:05 +08:00
{ role : "user" , content : "current question" , turnId : "main" },
2026-10-21 18:33:53 +08:00
{ role : "assistant" , content : "completed first" , turnId : "main" , streamId : "main-first-answer" },
guidanceRow ,
{ role : "assistant" , content : "completed last" , turnId : "main" , streamId : "main-last-answer" , textSeq : 4 , endSeq : 5 },
], [ "main" ]),
2026-10-16 11:38:05 +08:00
has_pending_tool_calls : false ,
completed_turn_ids : [ "main" ],
page : { before_cursor : "older-page" , has_more_before : true , user_message_offset : 25 },
});
}));
render ( wrap ( client , < ThreadShell
session = { session ( chatId )} title = "Completed paged guidance" messageCache = { messageCache }
2026-10-26 21:45:36 +08:00
onToggleSidebar = {() => {}}
2026-10-16 11:38:05 +08:00
/>));
await screen . findByText ( "completed last" );
const messages = [
... screen . getAllByText ( "continue" ),
...[ "older answer" , "current question" , "completed first" , "completed last" , "new question" , "new live answer" ]
. map (( text ) => screen . getByText ( text )),
];
messages . sort (( a , b ) => a . compareDocumentPosition ( b ) & Node . DOCUMENT_POSITION_FOLLOWING ? - 1 : 1 );
expect ( messages . map (( message ) => message . textContent )). toEqual ([
"continue" , "older answer" , "current question" , "completed first" ,
"continue" , "completed last" , "new question" , "new live answer" ,
]);
expect ( screen . queryByText ( "first partial" )). not . toBeInTheDocument ();
expect ( screen . queryByText ( "last partial" )). not . toBeInTheDocument ();
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
act (() => client . _emitChat ( chatId , {
event : "delta" , chat_id : chatId , turn_id : "new" , text : " continued" ,
2026-10-21 18:33:53 +08:00
turn_seq : 3 , stream_id : "new-live-answer" ,
2026-10-16 11:38:05 +08:00
}));
await screen . findByText ( "new live answer continued" );
});
2026-09-30 17:40:11 +08:00
it ( "remembers explicit completed turns on initial history load" , async () => {
const client = makeClient ();
const turnId = "turn-completed-before-load" ;
vi . stubGlobal ( "fetch" , vi . fn ( async ( input : RequestInfo | URL ) => {
if ( String ( input ). includes ( "websocket%3Ainitial-completion/webui-thread" )) {
return httpJson ({
... transcriptFromSimpleMessages ([
{ role : "user" , content : "previous question" , turnId },
]),
has_pending_tool_calls : false ,
completed_turn_ids : [ turnId ],
});
}
return { ok : false , status : 404 , json : async () => ({}) };
}));
render ( wrap ( client , < ThreadShell
session = { session ( "initial-completion" )}
title = "Initial completion"
onToggleSidebar = {() => {}}
/>));
await screen . findByText ( "previous question" );
act (() => client . _emitChat ( "initial-completion" , {
event : "goal_status" , chat_id : "initial-completion" , turn_id : turnId ,
status : "running" , started_at : 4_000 ,
}));
expect ( screen . queryByRole ( "button" , { name : "Stop response" })). not . toBeInTheDocument ();
act (() => client . _emitChat ( "initial-completion" , {
event : "goal_status" , chat_id : "initial-completion" , turn_id : "new-turn" ,
status : "running" , started_at : 5_000 ,
}));
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
});
2026-07-28 11:40:01 +08:00
it ( "fences websocket frames that arrive after canonical completion" , async () => {
const client = makeClient ();
const turnId = "turn-http-won" ;
let historyCalls = 0 ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Alate-frame-chat/webui-thread" )) {
historyCalls += 1 ;
return httpJson ({
2026-10-21 18:33:53 +08:00
... streamedThreadPayload ( "late-frame-chat" ,
2026-07-28 11:40:01 +08:00
historyCalls === 1
? [{ role : "user" , content : "question" , turnId }]
: [
{ role : "user" , content : "question" , turnId },
2026-10-21 18:33:53 +08:00
{ role : "assistant" , content : "canonical complete answer" , turnId , streamId : "http-won-answer" },
2026-07-28 11:40:01 +08:00
],
2026-10-21 18:33:53 +08:00
historyCalls === 1 ? [] : [ turnId ],
2026-07-28 11:40:01 +08:00
),
has_pending_tool_calls : false ,
});
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "late-frame-chat" )}
title = "Late frame chat"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "question" )). toBeInTheDocument ());
act (() => {
client . _emitChat ( "late-frame-chat" , {
event : "goal_status" ,
chat_id : "late-frame-chat" ,
status : "running" ,
started_at : 4_000 ,
turn_id : turnId ,
});
client . _emitChat ( "late-frame-chat" , {
event : "delta" ,
chat_id : "late-frame-chat" ,
text : "partial" ,
2026-10-21 18:33:53 +08:00
turn_id : turnId , turn_seq : 2 , stream_id : "http-won-answer" ,
2026-07-28 11:40:01 +08:00
});
});
await waitFor (() => expect ( screen . getByText ( "partial" )). toBeInTheDocument ());
2026-07-30 10:25:22 +08:00
act (() => client . _emitSessionUpdate ( "late-frame-chat" , "thread" ));
2026-07-28 11:40:01 +08:00
await waitFor (() =>
expect ( screen . getByText ( "canonical complete answer" )). toBeInTheDocument (),
);
act (() => {
client . _emitChat ( "late-frame-chat" , {
event : "delta" ,
chat_id : "late-frame-chat" ,
text : " delayed duplicate" ,
2026-10-21 18:33:53 +08:00
turn_id : turnId , turn_seq : 2 , stream_id : "http-won-answer" ,
2026-07-28 11:40:01 +08:00
});
client . _emitChat ( "late-frame-chat" , {
event : "turn_end" ,
chat_id : "late-frame-chat" ,
2026-10-21 18:33:53 +08:00
turn_id : turnId , turn_seq : 4 ,
2026-07-28 11:40:01 +08:00
});
client . _emitSessionUpdate ( "late-frame-chat" );
});
await waitFor (() => expect ( historyCalls ). toBe ( 3 ));
expect ( screen . getAllByText ( "canonical complete answer" )). toHaveLength ( 1 );
2026-10-21 18:33:53 +08:00
expect ( screen . queryByText ( "partial" )). not . toBeInTheDocument ();
2026-07-28 11:40:01 +08:00
expect ( screen . queryByText ( " delayed duplicate" )). not . toBeInTheDocument ();
expect ( screen . queryByText ( "canonical complete answer delayed duplicate" )). not . toBeInTheDocument ();
expect ( screen . queryByRole ( "button" , { name : "Stop response" })). not . toBeInTheDocument ();
});
it ( "does not revive a canonically completed run after switching chats" , async () => {
const client = makeClient ();
const turnId = "turn-visibility-complete" ;
let chatACalls = 0 ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Avisibility-complete-a/webui-thread" )) {
chatACalls += 1 ;
return httpJson ({
... transcriptFromSimpleMessages (
chatACalls === 1
? [{ role : "user" , content : "question" , turnId }]
: [
{ role : "user" , content : "question" , turnId },
{ role : "assistant" , content : "completed while hidden" , turnId },
],
),
has_pending_tool_calls : false ,
});
}
if ( url . includes ( "websocket%3Avisibility-complete-b/webui-thread" )) {
return httpJson ( transcriptFromSimpleMessages ([
{ role : "user" , content : "other thread" },
]));
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
const view = ( chatId : string ) => wrap (
client ,
< ThreadShell
session = { session ( chatId )}
title = { `Chat ${ chatId } ` }
onToggleSidebar = {() => {}}
/>,
);
const { rerender } = render ( view ( "visibility-complete-a" ));
await waitFor (() => expect ( screen . getByText ( "question" )). toBeInTheDocument ());
act (() => {
client . _emitChat ( "visibility-complete-a" , {
event : "goal_status" ,
chat_id : "visibility-complete-a" ,
status : "running" ,
started_at : 5_000 ,
turn_id : turnId ,
});
});
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
2026-07-30 10:25:22 +08:00
act (() => client . _emitSessionUpdate ( "visibility-complete-a" , "thread" ));
2026-07-28 11:40:01 +08:00
await waitFor (() => expect ( screen . getByText ( "completed while hidden" )). toBeInTheDocument ());
expect ( screen . queryByRole ( "button" , { name : "Stop response" })). not . toBeInTheDocument ();
2026-11-09 11:55:22 +08:00
expect ( client . getRunState ( "visibility-complete-a" ). startedAt ). toBeNull ();
2026-07-28 11:40:01 +08:00
rerender ( view ( "visibility-complete-b" ));
await waitFor (() => expect ( screen . getByText ( "other thread" )). toBeInTheDocument ());
rerender ( view ( "visibility-complete-a" ));
await waitFor (() => expect ( screen . getByText ( "completed while hidden" )). toBeInTheDocument ());
expect ( screen . queryByRole ( "button" , { name : "Stop response" })). not . toBeInTheDocument ();
});
it ( "uses explicit completion ids when a completed turn has no assistant row" , async () => {
const client = makeClient ();
const turnId = "turn-empty-answer" ;
let historyCalls = 0 ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
if ( String ( input ). includes ( "websocket%3Aempty-answer/webui-thread" )) {
historyCalls += 1 ;
return httpJson ({
... transcriptFromSimpleMessages ([
{ role : "user" , content : "stop" , turnId },
]),
has_pending_tool_calls : historyCalls === 1 ,
completed_turn_ids : historyCalls === 1 ? [] : [ turnId ],
});
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "empty-answer" )}
title = "Empty answer"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "stop" )). toBeInTheDocument ());
act (() => {
client . _emitChat ( "empty-answer" , {
event : "goal_status" ,
chat_id : "empty-answer" ,
status : "running" ,
started_at : 5_000 ,
turn_id : turnId ,
});
});
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
2026-07-30 10:25:22 +08:00
act (() => client . _emitSessionUpdate ( "empty-answer" , "thread" ));
2026-07-28 11:40:01 +08:00
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
await waitFor (() => expect ( client . reconcileCanonicalCompletion ). toHaveBeenCalledWith (
"empty-answer" ,
expect . any ( Number ),
expect . arrayContaining ([ turnId ]),
expect . objectContaining ({
observedTurnIds : [ turnId ],
hasPendingToolCalls : false ,
}),
));
expect ( screen . queryByRole ( "button" , { name : "Stop response" })). not . toBeInTheDocument ();
});
2026-10-16 14:04:54 +08:00
it . each ([ "persisted-turn" , "recovery:restored-turn" ])(
"loads history when opening a running session without settling %s" ,
async ( turnId ) => {
const client = makeClient ();
const chatId = "running-history" ;
client . _emitChat ( chatId , {
event : "goal_status" , chat_id : chatId , status : "running" ,
started_at : 1_700 , turn_id : turnId ,
});
vi . stubGlobal ( "fetch" , vi . fn ( async ( input : RequestInfo | URL ) => {
if ( String ( input ). includes ( `websocket%3A ${ chatId } /webui-thread` )) {
return httpJson ({
2026-10-21 18:33:53 +08:00
... streamedThreadPayload ( chatId , [
2026-10-16 14:04:54 +08:00
{ role : "user" , content : "previous question" , turnId : "finished-turn" },
2026-10-21 18:33:53 +08:00
{ role : "assistant" , content : "previous answer" , turnId : "finished-turn" , streamId : "finished-answer" },
2026-10-16 14:04:54 +08:00
{ role : "user" , content : "current question" , turnId : "persisted-turn" },
2026-10-21 18:33:53 +08:00
{ role : "assistant" , content : "saved answer prefix" , turnId : "persisted-turn" , streamId : "saved-answer" },
], [ "finished-turn" ]),
2026-10-16 14:04:54 +08:00
completed_turn_ids : [ "finished-turn" ],
has_pending_tool_calls : true ,
active_turn_id : turnId ,
});
}
return { ok : false , status : 404 , json : async () => ({}) };
}));
render ( wrap ( client , < ThreadShell
session = { session ( chatId )} title = "Running history"
2026-10-26 21:45:36 +08:00
onToggleSidebar = {() => {}}
2026-10-16 14:04:54 +08:00
/>));
await screen . findByText ( "previous answer" );
expect ( screen . getByText ( "current question" )). toBeInTheDocument ();
expect ( screen . getByText ( "saved answer prefix" )). toBeInTheDocument ();
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
expect ( client . reconcileCanonicalCompletion ). not . toHaveBeenCalled ();
2026-11-09 11:55:22 +08:00
expect ( client . getRunState ( chatId ). startedAt ). toBe ( 1 _700 );
2026-10-16 14:04:54 +08:00
const input = screen . getByRole ( "textbox" , { name : "Message input" });
fireEvent . change ( input , { target : { value : "queued guidance" } });
fireEvent . keyDown ( input , { key : "Enter" });
expect ( client . sendMessage ). not . toHaveBeenCalled ();
act (() => client . _emitChat ( chatId , {
event : "delta" , chat_id : chatId , turn_id : turnId , text : "continued" ,
2026-10-21 18:33:53 +08:00
turn_seq : 4 , stream_id : "continued-answer" ,
2026-10-16 14:04:54 +08:00
}));
await screen . findByText ( "continued" );
act (() => client . _emitChat ( chatId , {
event : "delta" , chat_id : chatId , turn_id : turnId , text : " answer" ,
2026-10-21 18:33:53 +08:00
turn_seq : 5 , stream_id : "continued-answer" ,
2026-10-16 14:04:54 +08:00
}));
await screen . findByText ( "continued answer" );
expect ( screen . getByText ( "saved answer prefix" )). toBeInTheDocument ();
expect ( client . sendMessage ). not . toHaveBeenCalled ();
},
);
2026-10-21 13:10:05 +08:00
it . each ([
{ name : "visible rows after a hidden command prefix" , rows : [
{ role : "user" as const , content : "/model hidden" , turnId : "webui-system:model" },
{ role : "assistant" as const , content : "hidden model response" , turnId : "webui-system:model" },
{ role : "user" as const , content : "older question" , turnId : "older-turn" },
{ role : "assistant" as const , content : "older answer" , turnId : "older-turn" },
], expectVisible : true },
{ name : "a page containing only hidden command rows" , rows : [
{ role : "user" as const , content : "/model hidden" , turnId : "webui-system:model" },
{ role : "assistant" as const , content : "hidden model response" , turnId : "webui-system:model" },
], expectVisible : false },
{ name : "an empty successful page" , rows : [], expectVisible : false },
{ name : "a failed page" , rows : [], expectVisible : false , error : true },
2026-10-21 18:33:53 +08:00
])( "atomically publishes older-page rows and loading completion for $name" , async ({ rows , expectVisible , error = false }) => {
2026-10-21 13:10:05 +08:00
const client = makeClient ();
const chatId = `older-projection- ${ expectVisible ? "visible" : "hidden" } ` ;
let resolveOlder !: ( response : Response ) => void ;
let olderReturned = false ;
const commits : Array < { loading : boolean ; olderVisible : boolean } > = [];
vi . stubGlobal ( "fetch" , vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( ! url . includes ( `websocket%3A ${ chatId } /webui-thread` )) {
return { ok : false , status : 404 , json : async () => ({}) };
}
if ( url . includes ( "before=" )) {
return new Promise < Response >(( resolve ) => { resolveOlder = resolve ; });
}
return httpJson ({
... transcriptFromSimpleMessages ([
{ role : "user" , content : "current question" , turnId : "current-turn" },
]),
has_pending_tool_calls : expectVisible ,
active_turn_id : expectVisible ? "current-turn" : null ,
completed_turn_ids : [],
page : { before_cursor : "older-page" , has_more_before : true , user_message_offset : 1 },
});
}));
const capture = () => {
if ( ! olderReturned ) return ;
commits . push ({
loading : document.querySelector ( '.thread-history-status[data-state="loading"]' ) !== null ,
olderVisible : document.body.textContent?.includes ( "older answer" ) ?? false ,
});
};
const { container } = render ( wrap ( client , < Profiler id = "older-history" onRender = { capture }>
< ThreadShell session = { session ( chatId )} title = "Older projection" onToggleSidebar = {() => {}} />
</ Profiler >));
await screen . findByText ( "current question" );
const scroller = container . querySelector ( ".thread-message-viewport" ) as HTMLElement ;
Object . defineProperties ( scroller , {
scrollHeight : { configurable : true , value : 2400 },
clientHeight : { configurable : true , value : 600 },
scrollTop : { configurable : true , writable : true , value : 0 },
});
fireEvent . keyDown ( scroller , { key : "Home" });
await waitFor (() => expect ( resolveOlder ). toBeTypeOf ( "function" ));
await screen . findByText ( "Loading earlier messages…" );
if ( expectVisible ) {
act (() => client . _emitChat ( chatId , {
event : "delta" , chat_id : chatId , turn_id : "current-turn" , text : "live during pagination" ,
2026-10-21 18:33:53 +08:00
turn_seq : 2 , stream_id : "pagination-answer" ,
2026-10-21 13:10:05 +08:00
}));
await screen . findByText ( "live during pagination" );
}
const olderPayload = rows . length > 0
? transcriptFromSimpleMessages ( rows )
: { schemaVersion : 3 , projection : "events" , events : [], page : { before_cursor : null , has_more_before : false } };
olderReturned = true ;
await act ( async () => {
resolveOlder ( error
? new Response ( "History unavailable" , { status : 503 })
: httpJson ({ ... olderPayload , page : { before_cursor : null , has_more_before : false } }));
});
if ( expectVisible ) await screen . findByText ( "older answer" );
await waitFor (() => expect ( container . querySelector ( '.thread-history-status[data-state="loading"]' )). toBeNull ());
2026-10-21 18:33:53 +08:00
expect ( commits . length ). toBeGreaterThan ( 0 );
expect ( commits . at ( - 1 ) ? . loading ). toBe ( false );
if ( expectVisible ) {
expect ( commits . some (( commit ) => ! commit . loading && ! commit . olderVisible )). toBe ( false );
expect ( commits . at ( - 1 ) ? . olderVisible ). toBe ( true );
}
2026-10-21 13:10:05 +08:00
if ( error ) {
expect ( container . querySelector ( '.thread-history-status[data-state="error"]' )). toBeInTheDocument ();
expect ( container . querySelector ( ".thread-history-slot" )). toBeInTheDocument ();
} else {
expect ( container . querySelector ( ".thread-history-slot" )). not . toBeInTheDocument ();
}
});
2026-10-16 14:04:54 +08:00
it ( "prepends earlier history while preserving the active answer cursor" , async () => {
const client = makeClient ();
const chatId = "running-paged-history" ;
const turnId = "current-turn" ;
client . _emitChat ( chatId , {
event : "goal_status" , chat_id : chatId , status : "running" ,
started_at : 1_700 , turn_id : turnId ,
});
vi . stubGlobal ( "fetch" , vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( ! url . includes ( `websocket%3A ${ chatId } /webui-thread` )) {
return { ok : false , status : 404 , json : async () => ({}) };
}
if ( url . includes ( "before=" )) {
return httpJson ( canonicalThreadPayload ({
schemaVersion : 3 ,
messages : [
{ id : "older-user" , role : "user" , content : "older question" , turnId : "older-turn" , createdAt : 1 },
{ id : "older-answer" , role : "assistant" , content : "older answer" , turnId : "older-turn" , createdAt : 2 },
],
has_pending_tool_calls : false ,
completed_turn_ids : [ "older-turn" ],
page : { before_cursor : null , has_more_before : false , user_message_offset : 0 },
}));
}
return httpJson ({
... transcriptFromSimpleMessages ([{ role : "user" , content : "current question" , turnId }]),
has_pending_tool_calls : true ,
active_turn_id : turnId ,
completed_turn_ids : [],
page : { before_cursor : "older-page" , has_more_before : true , user_message_offset : 1 },
});
}));
const { container } = render ( wrap ( client , < ThreadShell
session = { session ( chatId )} title = "Running paged history"
2026-10-26 21:45:36 +08:00
onToggleSidebar = {() => {}}
2026-10-16 14:04:54 +08:00
/>));
await screen . findByText ( "current question" );
act (() => client . _emitChat ( chatId , {
event : "delta" , chat_id : chatId , turn_id : turnId , text : "live answer" ,
}));
await screen . findByText ( "live answer" );
fireEvent . wheel ( container . querySelector ( ".thread-message-viewport" ) ! , { deltaY : - 100 });
const older = await screen . findByText ( "older answer" );
const current = screen . getByText ( "current question" );
expect ( older . compareDocumentPosition ( current ) & Node . DOCUMENT_POSITION_FOLLOWING ). toBeTruthy ();
expect ( screen . getByText ( "live answer" )). toBeInTheDocument ();
expect ( client . reconcileCanonicalCompletion ). not . toHaveBeenCalled ();
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
act (() => client . _emitChat ( chatId , {
event : "delta" , chat_id : chatId , turn_id : turnId , text : " continued" ,
}));
await screen . findByText ( "live answer continued" );
expect ( screen . getAllByText ( "older answer" )). toHaveLength ( 1 );
});
2026-07-28 11:40:01 +08:00
it ( "converges after reconnecting before the first assistant delta" , async () => {
const client = makeClient ();
let historyCalls = 0 ;
const turnId = "turn-resume-before-delta" ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Abefore-delta-chat/webui-thread" )) {
historyCalls += 1 ;
2026-10-21 18:33:53 +08:00
const transcript = streamedThreadPayload ( "before-delta-chat" ,
2026-07-28 11:40:01 +08:00
historyCalls === 1
? [{ role : "user" , content : "question" , turnId }]
: [
{ role : "user" , content : "question" , turnId },
{
2026-10-21 18:33:53 +08:00
role : "assistant" , turnId , streamId : "before-delta-answer" ,
content : historyCalls === 2 ? "missed prefix" : "missed prefix resumed suffix" ,
endSeq : historyCalls === 2 ? 3 : 5 ,
mergeNext : historyCalls === 2 ,
2026-07-28 11:40:01 +08:00
},
],
2026-10-21 18:33:53 +08:00
historyCalls < 3 ? [] : [ turnId ],
2026-07-28 11:40:01 +08:00
);
return httpJson ({
... transcript ,
2026-10-21 18:33:53 +08:00
has_pending_tool_calls : historyCalls < 3 ,
active_turn_id : historyCalls < 3 ? turnId : null ,
2026-07-28 11:40:01 +08:00
});
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "before-delta-chat" )}
title = "Before delta chat"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "question" )). toBeInTheDocument ());
act (() => {
client . _emitChat ( "before-delta-chat" , {
event : "goal_status" ,
chat_id : "before-delta-chat" ,
status : "running" ,
started_at : 1_700 ,
turn_id : turnId ,
});
});
2026-08-18 18:28:19 +08:00
const input = screen . getByRole ( "textbox" , { name : "Message input" });
2026-07-28 11:40:01 +08:00
fireEvent . change ( input , { target : { value : "queued guidance" } });
fireEvent . keyDown ( input , { key : "Enter" });
expect ( client . sendMessage ). not . toHaveBeenCalled ();
act (() => client . _emitStatus ( "reconnecting" ));
act (() => client . _emitStatus ( "open" ));
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
2026-10-21 18:33:53 +08:00
await screen . findByText ( "missed prefix" );
2026-07-28 11:40:01 +08:00
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
expect ( client . sendMessage ). not . toHaveBeenCalled ();
act (() => {
client . _emitChat ( "before-delta-chat" , {
event : "delta" ,
chat_id : "before-delta-chat" ,
2026-10-21 18:33:53 +08:00
text : " resumed suffix" ,
turn_id : turnId , turn_seq : 4 , stream_id : "before-delta-answer" ,
2026-07-28 11:40:01 +08:00
});
});
2026-10-21 18:33:53 +08:00
await screen . findByText ( "missed prefix resumed suffix" );
expect ( screen . queryByText ( "missed prefix" )). not . toBeInTheDocument ();
expect ( screen . queryByText ( "resumed suffix" )). not . toBeInTheDocument ();
expect ( client . sendMessage ). not . toHaveBeenCalled ();
2026-07-28 11:40:01 +08:00
act (() => client . _emitStatus ( "reconnecting" ));
act (() => client . _emitStatus ( "open" ));
await waitFor (() => expect ( historyCalls ). toBe ( 3 ));
await waitFor (() =>
expect ( screen . getByText ( "missed prefix resumed suffix" )). toBeInTheDocument (),
);
expect ( screen . queryByText ( "resumed suffix" )). not . toBeInTheDocument ();
await waitFor (() => expectSendMessageWithTurn (
client ,
"before-delta-chat" ,
"queued guidance" ,
));
});
2026-11-11 17:32:47 +08:00
it ( "catches up the active answer and keeps its cursor when a resumed turn is still running" , async () => {
2026-07-28 11:40:01 +08:00
const client = makeClient ();
let historyCalls = 0 ;
const turnId = "turn-active-resume" ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Aactive-resume-chat/webui-thread" )) {
historyCalls += 1 ;
2026-10-21 18:33:53 +08:00
const transcript = streamedThreadPayload ( "active-resume-chat" ,
2026-07-28 11:40:01 +08:00
historyCalls === 1
? [{ role : "user" , content : "question" , turnId }]
: [
{ role : "user" , content : "question" , turnId },
{
2026-10-21 18:33:53 +08:00
role : "assistant" , turnId , streamId : "active-resume-answer" ,
content : historyCalls === 2 ? "partial answer missed" : "partial answer missed resumed" ,
endSeq : historyCalls === 2 ? 4 : 6 ,
mergeNext : historyCalls === 2 ,
2026-07-28 11:40:01 +08:00
},
],
2026-10-21 18:33:53 +08:00
historyCalls < 3 ? [] : [ turnId ],
2026-07-28 11:40:01 +08:00
);
2026-10-21 18:33:53 +08:00
return httpJson ({
... transcript ,
has_pending_tool_calls : historyCalls < 3 ,
active_turn_id : historyCalls < 3 ? turnId : null ,
});
2026-07-28 11:40:01 +08:00
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "active-resume-chat" )}
title = "Active resume chat"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "question" )). toBeInTheDocument ());
act (() => {
client . _emitChat ( "active-resume-chat" , {
event : "goal_status" ,
chat_id : "active-resume-chat" ,
status : "running" ,
started_at : 1_700 ,
turn_id : turnId ,
});
client . _emitChat ( "active-resume-chat" , {
event : "delta" ,
chat_id : "active-resume-chat" ,
text : "partial answer" ,
2026-10-21 18:33:53 +08:00
turn_id : turnId , turn_seq : 2 , stream_id : "active-resume-answer" ,
2026-07-28 11:40:01 +08:00
});
});
await waitFor (() => expect ( screen . getByText ( "partial answer" )). toBeInTheDocument ());
2026-08-18 18:28:19 +08:00
const input = screen . getByRole ( "textbox" , { name : "Message input" });
2026-07-28 11:40:01 +08:00
fireEvent . change ( input , { target : { value : "queued guidance" } });
fireEvent . keyDown ( input , { key : "Enter" });
expect ( screen . getByText ( "queued guidance" )). toBeInTheDocument ();
expect ( client . sendMessage ). not . toHaveBeenCalled ();
act (() => client . _emitStatus ( "reconnecting" ));
expect ( client . sendMessage ). not . toHaveBeenCalled ();
act (() => client . _emitStatus ( "open" ));
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
2026-11-11 17:32:47 +08:00
await screen . findByText ( "partial answer missed" );
2026-07-28 11:40:01 +08:00
expect ( client . sendMessage ). not . toHaveBeenCalled ();
act (() => {
client . _emitChat ( "active-resume-chat" , {
event : "delta" ,
chat_id : "active-resume-chat" ,
text : " resumed" ,
2026-10-21 18:33:53 +08:00
turn_id : turnId , turn_seq : 5 , stream_id : "active-resume-answer" ,
2026-07-28 11:40:01 +08:00
});
});
2026-11-11 17:32:47 +08:00
await waitFor (() => expect ( screen . getByText ( "partial answer missed resumed" )). toBeInTheDocument ());
2026-07-28 11:40:01 +08:00
expect ( screen . queryByText ( " resumed" )). not . toBeInTheDocument ();
expect ( client . sendMessage ). not . toHaveBeenCalled ();
act (() => client . _emitStatus ( "reconnecting" ));
expect ( client . sendMessage ). not . toHaveBeenCalled ();
act (() => client . _emitStatus ( "open" ));
await waitFor (() => expect ( historyCalls ). toBe ( 3 ));
await waitFor (() =>
expect ( screen . getByText ( "partial answer missed resumed" )). toBeInTheDocument (),
);
expect ( screen . queryByText ( "partial answer resumed" )). not . toBeInTheDocument ();
await waitFor (() => expectSendMessageWithTurn (
client ,
"active-resume-chat" ,
"queued guidance" ,
));
});
2026-08-15 14:58:35 +08:00
it ( "keeps active-run timing attached to the original turn after guidance" , async () => {
const client = makeClient ();
const turnId = "turn-active-timing" ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
if ( String ( input ). includes ( "websocket%3Atiming-chat/webui-thread" )) {
return httpJson ( transcriptFromSimpleMessages ([{
role : "user" ,
content : "research this" ,
turnId ,
}]));
}
return { ok : false , status : 404 , json : async () => ({}) };
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "timing-chat" )}
title = "Timing chat"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "research this" )). toBeInTheDocument ());
act (() => {
client . _emitChat ( "timing-chat" , {
event : "goal_status" ,
chat_id : "timing-chat" ,
status : "running" ,
started_at : Date.now () / 1000 - 215 ,
turn_id : turnId ,
});
client . _emitChat ( "timing-chat" , {
event : "message" ,
chat_id : "timing-chat" ,
kind : "progress" ,
text : "web_search()" ,
turn_id : turnId ,
});
client . _emitChat ( "timing-chat" , {
event : "message" ,
chat_id : "timing-chat" ,
text : "Continuing the search." ,
latency_ms : 1_000 ,
turn_id : turnId ,
});
});
await waitFor (() => expect ( screen . getByText ( "Continuing the search." )). toBeInTheDocument ());
2026-08-18 18:28:19 +08:00
const input = screen . getByRole ( "textbox" , { name : "Message input" });
2026-08-15 14:58:35 +08:00
fireEvent . change ( input , { target : { value : "How is it going?" } });
fireEvent . keyDown ( input , { key : "Enter" });
fireEvent . keyDown ( input , { key : "Enter" });
await waitFor (() => expect ( screen . getByText ( "How is it going?" )). toBeInTheDocument ());
expect ( screen . getByRole ( "button" , { name : /^Working for / })). toBeInTheDocument ();
expect ( screen . queryByText ( "Worked for 1s" )). not . toBeInTheDocument ();
expect ( screen . queryByRole ( "status" , { name : /^Thinking for / })). not . toBeInTheDocument ();
});
2026-07-28 11:40:01 +08:00
it ( "refreshes the current thread when the page returns to the foreground" , async () => {
const client = makeClient ();
let historyCalls = 0 ;
2026-07-30 10:25:22 +08:00
const turnId = "turn-visible-chat" ;
2026-07-28 11:40:01 +08:00
const visibilityDescriptor = Object . getOwnPropertyDescriptor ( document , "visibilityState" );
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Avisible-chat/webui-thread" )) {
historyCalls += 1 ;
2026-07-30 10:25:22 +08:00
return httpJson ({
... transcriptFromSimpleMessages (
2026-07-28 11:40:01 +08:00
historyCalls === 1
2026-07-30 10:25:22 +08:00
? [{ role : "user" , content : "question" , turnId }]
2026-07-28 11:40:01 +08:00
: [
2026-07-30 10:25:22 +08:00
{ role : "user" , content : "question" , turnId },
{
role : "assistant" ,
content : "answer completed in background" ,
turnId ,
},
2026-07-28 11:40:01 +08:00
],
),
2026-07-30 10:25:22 +08:00
has_pending_tool_calls : historyCalls === 1 ,
completed_turn_ids : historyCalls === 1 ? [] : [ turnId ],
});
2026-07-28 11:40:01 +08:00
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
try {
render (
wrap (
client ,
< ThreadShell
session = { session ( "visible-chat" )}
title = "Visible chat"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "question" )). toBeInTheDocument ());
expect ( historyCalls ). toBe ( 1 );
2026-07-30 10:25:22 +08:00
act (() => {
client . _emitChat ( "visible-chat" , {
event : "goal_status" ,
chat_id : "visible-chat" ,
status : "running" ,
started_at : 6_000 ,
turn_id : turnId ,
});
});
2026-07-28 11:40:01 +08:00
act (() => {
2026-07-30 10:25:22 +08:00
setDocumentVisibility ( "hidden" );
2026-07-28 11:40:01 +08:00
});
expect ( historyCalls ). toBe ( 1 );
await act ( async () => {
2026-07-30 10:25:22 +08:00
setDocumentVisibility ( "visible" );
2026-07-28 11:40:01 +08:00
await Promise . resolve ();
});
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
await waitFor (() =>
expect ( screen . getByText ( "answer completed in background" )). toBeInTheDocument (),
);
} finally {
2026-07-30 10:25:22 +08:00
restoreDocumentVisibility ( visibilityDescriptor );
}
});
it ( "does not refresh an idle thread for visibility notifications" , async () => {
const client = makeClient ();
let historyCalls = 0 ;
const visibilityDescriptor = Object . getOwnPropertyDescriptor ( document , "visibilityState" );
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
if ( String ( input ). includes ( "websocket%3Aidle-visible-chat/webui-thread" )) {
historyCalls += 1 ;
return httpJson ( transcriptFromSimpleMessages ([
{ role : "assistant" , content : "settled answer" },
]));
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
try {
render (
wrap (
client ,
< ThreadShell
session = { session ( "idle-visible-chat" )}
title = "Idle visible chat"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "settled answer" )). toBeInTheDocument ());
act (() => document . dispatchEvent ( new Event ( "visibilitychange" )));
act (() => {
setDocumentVisibility ( "hidden" );
});
await act ( async () => {
setDocumentVisibility ( "visible" );
await Promise . resolve ();
});
expect ( historyCalls ). toBe ( 1 );
} finally {
restoreDocumentVisibility ( visibilityDescriptor );
}
});
it ( "retries a failed hydration when the page returns to the foreground" , async () => {
const client = makeClient ();
let historyCalls = 0 ;
const visibilityDescriptor = Object . getOwnPropertyDescriptor ( document , "visibilityState" );
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
if ( String ( input ). includes ( "websocket%3Aretry-visible-chat/webui-thread" )) {
historyCalls += 1 ;
if ( historyCalls === 1 ) {
return {
ok : false ,
status : 500 ,
json : async () => ({}),
};
}
return httpJson ( transcriptFromSimpleMessages ([
{ role : "assistant" , content : "recovered answer" },
]));
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
try {
render (
wrap (
client ,
< ThreadShell
session = { session ( "retry-visible-chat" )}
title = "Retry visible chat"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( historyCalls ). toBe ( 1 ));
act (() => {
setDocumentVisibility ( "hidden" );
});
await act ( async () => {
setDocumentVisibility ( "visible" );
await Promise . resolve ();
});
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
expect ( await screen . findByText ( "recovered answer" )). toBeInTheDocument ();
} finally {
restoreDocumentVisibility ( visibilityDescriptor );
2026-07-28 11:40:01 +08:00
}
});
2026-05-16 08:33:15 +00:00
it ( "does not refetch thread history on turn_end" , async () => {
2026-05-13 16:39:07 +00:00
const client = makeClient ();
let historyCalls = 0 ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
2026-05-16 01:14:11 +08:00
if ( url . includes ( "websocket%3Achat-a/webui-thread" )) {
2026-05-13 16:39:07 +00:00
historyCalls += 1 ;
2026-05-16 01:14:11 +08:00
return httpJson (
transcriptFromSimpleMessages (
historyCalls === 1
? [{ role : "user" , content : "question" }]
: [
{ role : "user" , content : "question" },
{ role : "assistant" , content : "canonical markdown answer" },
],
),
);
2026-05-13 16:39:07 +00:00
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-a" )}
title = "Chat chat-a"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "question" )). toBeInTheDocument ());
await act ( async () => {
client . _emitChat ( "chat-a" , {
event : "delta" ,
chat_id : "chat-a" ,
text : "live half-parsed | markdown" ,
});
client . _emitChat ( "chat-a" , {
event : "turn_end" ,
chat_id : "chat-a" ,
});
});
2026-05-16 08:33:15 +00:00
await waitFor (() => expect ( screen . getByText ( "live half-parsed | markdown" )). toBeInTheDocument ());
expect ( screen . queryByText ( "canonical markdown answer" )). not . toBeInTheDocument ();
expect ( historyCalls ). toBe ( 1 );
2026-05-13 16:39:07 +00:00
});
2026-07-30 10:25:22 +08:00
it ( "keeps rendered media mounted for metadata-only session updates" , async () => {
2026-05-17 23:52:50 +08:00
const client = makeClient ();
let historyCalls = 0 ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Achat-a/webui-thread" )) {
historyCalls += 1 ;
2026-07-30 10:25:22 +08:00
const thread = transcriptFromSimpleMessages ([
{ role : "user" , content : "question" },
{ role : "assistant" , content : "answer" },
]);
2026-09-20 16:48:13 +08:00
const answer = thread . events . find (
( event ) => event . event === "message" && event . text === "answer" ,
);
if ( answer ? . event === "message" ) answer . media_urls = [{
2026-07-30 10:25:22 +08:00
url : "/api/media/stable/image" ,
name : "answer.png" ,
}];
return httpJson ( thread );
2026-05-17 23:52:50 +08:00
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-a" )}
title = "Chat chat-a"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "answer" )). toBeInTheDocument ());
2026-07-30 10:25:22 +08:00
const image = screen . getByRole ( "img" , { name : "answer.png" });
2026-05-17 23:52:50 +08:00
expect ( historyCalls ). toBe ( 1 );
await act ( async () => {
client . _emitSessionUpdate ( "chat-a" , "metadata" );
});
expect ( historyCalls ). toBe ( 1 );
2026-07-30 10:25:22 +08:00
expect ( screen . getByRole ( "img" , { name : "answer.png" })). toBe ( image );
});
it ( "keeps rendered media mounted when the auth token rotates" , async () => {
const client = makeClient ();
let historyCalls = 0 ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
if ( String ( input ). includes ( "websocket%3Atoken-media/webui-thread" )) {
historyCalls += 1 ;
const thread = transcriptFromSimpleMessages ([
{ role : "user" , content : "question" },
{ role : "assistant" , content : "answer" },
]);
2026-09-20 16:48:13 +08:00
const answer = thread . events . find (
( event ) => event . event === "message" && event . text === "answer" ,
);
if ( answer ? . event === "message" ) answer . media_urls = [{
2026-07-30 10:25:22 +08:00
url : "/api/media/stable/token-image" ,
name : "token-answer.png" ,
}];
return httpJson ( thread );
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
const view = ( token : string ) => wrap (
client ,
< ThreadShell
session = { session ( "token-media" )}
title = "Token media"
onToggleSidebar = {() => {}}
/>,
null ,
token ,
);
const { rerender } = render ( view ( "tok-old" ));
await waitFor (() => expect ( screen . getByText ( "answer" )). toBeInTheDocument ());
const image = screen . getByRole ( "img" , { name : "token-answer.png" });
rerender ( view ( "tok-new" ));
await act ( async () => Promise . resolve ());
expect ( historyCalls ). toBe ( 1 );
expect ( screen . getByRole ( "img" , { name : "token-answer.png" })). toBe ( image );
2026-05-17 23:52:50 +08:00
});
2026-06-22 19:11:36 +08:00
it ( "does not scroll again when canonical history refreshes after a session update" , async () => {
const client = makeClient ();
2026-07-26 00:18:24 +08:00
const jumpTo = vi . spyOn ( ThreadCameraController . prototype , "jumpTo" );
2026-06-22 19:11:36 +08:00
let historyCalls = 0 ;
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Achat-a/webui-thread" )) {
historyCalls += 1 ;
return httpJson (
transcriptFromSimpleMessages (
historyCalls === 1
? [{ role : "user" , content : "question" }]
: [
{ role : "user" , content : "question" },
{ role : "assistant" , content : "canonical answer" },
],
),
);
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
try {
render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-a" )}
title = "Chat chat-a"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "question" )). toBeInTheDocument ());
2026-07-26 00:18:24 +08:00
await waitFor (() => expect ( jumpTo ). toHaveBeenCalled ());
2026-06-22 19:11:36 +08:00
await act ( async () => {
for ( let i = 0 ; i < 8 ; i += 1 ) {
await new Promise < void >(( resolve ) => window . requestAnimationFrame (() => resolve ()));
}
});
2026-07-26 00:18:24 +08:00
jumpTo . mockClear ();
2026-06-22 19:11:36 +08:00
await act ( async () => {
client . _emitSessionUpdate ( "chat-a" );
});
await waitFor (() => expect ( historyCalls ). toBe ( 2 ));
await waitFor (() => expect ( screen . getByText ( "canonical answer" )). toBeInTheDocument ());
2026-07-26 00:18:24 +08:00
expect ( jumpTo ). not . toHaveBeenCalled ();
2026-06-22 19:11:36 +08:00
} finally {
2026-07-26 00:18:24 +08:00
jumpTo . mockRestore ();
}
});
it ( "keeps an active completion follow alive while canonical history refreshes" , async () => {
const resizeObserver = stubThreadResizeObserver ();
const client = makeClient ();
let historyCalls = 0 ;
const pendingRefresh = new Promise < ReturnType < typeof httpJson >>(() => {});
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . includes ( "websocket%3Achat-follow/webui-thread" )) {
historyCalls += 1 ;
if ( historyCalls > 1 ) return pendingRefresh ;
return httpJson (
transcriptFromSimpleMessages ([
{ role : "user" , content : "old question" },
{ role : "assistant" , content : "old answer" },
]),
);
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
const requestFrame = vi . spyOn ( window , "requestAnimationFrame" );
const cancelFrame = vi . spyOn ( window , "cancelAnimationFrame" );
try {
const { container } = render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-follow" )}
title = "Chat follow"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "old answer" )). toBeInTheDocument ());
const scroller = container . querySelector ( ".thread-viewport-scrollbar" ) as HTMLElement ;
Object . defineProperties ( scroller , {
scrollHeight : { configurable : true , value : 2_000 },
clientHeight : { configurable : true , value : 500 },
scrollTop : { configurable : true , writable : true , value : 1_500 },
scrollTo : {
configurable : true ,
value : ({ top } : ScrollToOptions ) => {
if ( typeof top === "number" ) scroller . scrollTop = top ;
},
},
});
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "new question" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( screen . getByText ( "new question" )). toBeInTheDocument ());
await act ( async () => {
client . _emitChat ( "chat-follow" , {
event : "delta" ,
chat_id : "chat-follow" ,
text : "new answer" ,
});
});
await waitFor (() => expect ( screen . getByText ( "new answer" )). toBeInTheDocument ());
requestFrame . mockImplementation (() => 9 _001 );
cancelFrame . mockImplementation (() => undefined );
cancelFrame . mockClear ();
Object . defineProperty ( scroller , "scrollHeight" , {
configurable : true ,
value : 2_120 ,
});
const messageContent = screen . getByTestId ( "thread-message-region" ). firstElementChild ;
const contentObserver = resizeObserver . observers . find (
( observer ) => observer . elements . includes ( messageContent ! ),
);
expect ( contentObserver ). toBeDefined ();
act (() => {
contentObserver ! . callback ([], contentObserver as unknown as ResizeObserver );
});
expect ( requestFrame ). toHaveBeenCalled ();
cancelFrame . mockClear ();
act (() => {
client . _emitSessionUpdate ( "chat-follow" , "thread" );
});
expect ( cancelFrame ). not . toHaveBeenCalledWith ( 9 _001 );
expect ( historyCalls ). toBe ( 2 );
} finally {
requestFrame . mockRestore ();
cancelFrame . mockRestore ();
resizeObserver . restore ();
2026-06-22 19:11:36 +08:00
}
});
2026-05-13 16:39:07 +00:00
it ( "scrolls to the bottom after loading a session from the blank new-chat page" , async () => {
const client = makeClient ();
2026-06-22 19:11:36 +08:00
const scrollTo = vi . fn ();
2026-05-13 16:39:07 +00:00
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
2026-05-16 01:14:11 +08:00
if ( url . includes ( "websocket%3Achat-a/webui-thread" )) {
return httpJson (
transcriptFromSimpleMessages ([
2026-05-13 16:39:07 +00:00
{ role : "user" , content : "question" },
{ role : "assistant" , content : "loaded answer" },
2026-05-16 01:14:11 +08:00
]),
);
2026-05-13 16:39:07 +00:00
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
2026-06-22 10:57:29 +08:00
const { container , rerender } = render (
wrap (
client ,
< ThreadShell
session = { null }
title = "nanobot"
onToggleSidebar = {() => {}}
/>,
),
);
2026-11-13 17:12:18 +08:00
expect ( screen . getByTestId ( "thread-welcome-layout" )). toHaveAttribute ( "data-layout" , "hero" );
2026-06-22 10:57:29 +08:00
const scroller = container . querySelector ( ".thread-viewport-scrollbar" ) as HTMLElement ;
Object . defineProperties ( scroller , {
scrollHeight : { configurable : true , value : 2400 },
clientHeight : { configurable : true , value : 600 },
scrollTop : { configurable : true , writable : true , value : 0 },
scrollTo : { configurable : true , value : scrollTo },
});
scrollTo . mockClear ();
await act ( async () => {
rerender (
2026-05-13 16:39:07 +00:00
wrap (
client ,
< ThreadShell
2026-06-22 10:57:29 +08:00
session = { session ( "chat-a" )}
title = "Chat chat-a"
2026-05-13 16:39:07 +00:00
onToggleSidebar = {() => {}}
/>,
),
);
2026-06-22 10:57:29 +08:00
});
2026-05-13 16:39:07 +00:00
2026-06-22 10:57:29 +08:00
await waitFor (() => expect ( screen . getByText ( "loaded answer" )). toBeInTheDocument ());
2026-07-26 00:18:24 +08:00
await waitFor (() => expect ( scroller . scrollTop ). toBe ( 1800 ));
2026-05-13 16:39:07 +00:00
});
2026-11-14 23:48:13 +08:00
it . each ([ "active" , "blocked" ] as const )( "cancels the %s goal through a system command and waits for goal_state" , async ( status ) => {
const client = makeClient ();
const chatId = `cancel- ${ status } ` ;
let complete !: () => void ;
client . sendSystemCommand . mockImplementation (() => new Promise < void >(( resolve ) => { complete = resolve ; }));
render ( wrap ( client , < ThreadShell session = { session ( chatId )} title = "Goal" onToggleSidebar = {() => {}} />));
await act ( async () => {});
act (() => {
client . _emitChat ( chatId , { event : "goal_state" , chat_id : chatId , goal_state : { active : status === "active" , status , objective : "Ship the release" } });
client . _emitChat ( chatId , { event : "goal_status" , chat_id : chatId , turn_id : "running-turn" , status : "running" , started_at : 100 });
client . _emitChat ( chatId , { event : "delta" , chat_id : chatId , turn_id : "running-turn" , stream_id : "live" , text : "Still responding" });
});
await screen . findByText ( "Still responding" );
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeVisible ();
const input = screen . getByRole ( "textbox" , { name : "Message input" });
fireEvent . change ( input , { target : { value : "Keep my draft" } });
fireEvent . click ( await screen . findByRole ( "button" , { name : "Show full goal" }));
const button = screen . getByRole ( "button" , { name : "Cancel goal" });
fireEvent . click ( button );
expect ( button ). toBeDisabled ();
fireEvent . click ( button );
expect ( client . sendSystemCommand ). toHaveBeenCalledTimes ( 1 );
expect ( client . sendSystemCommand ). toHaveBeenCalledWith ( chatId , "/cancel_goal" );
expect ( screen . getByRole ( "dialog" , { name : "Goal" })). toBeVisible ();
expect ( input ). toHaveValue ( "Keep my draft" );
expect ( client . sendMessage ). not . toHaveBeenCalled ();
expect ( client . finishRunLocally ). not . toHaveBeenCalled ();
expect ( client . getRunState ( chatId ). active ). toBe ( true );
act (() => {
if ( status === "active" ) client . _emitChat ( chatId , { event : "turn_end" , chat_id : chatId , turn_id : "running-turn" });
client . _emitChat ( chatId , { event : "goal_state" , chat_id : chatId , goal_state : { active : false } });
});
await waitFor (() => expect ( screen . queryByRole ( "button" , { name : "Show full goal" })). not . toBeInTheDocument ());
await act ( async () => complete ());
expect ( input ). toHaveValue ( "Keep my draft" );
expect ( within ( screen . getByTestId ( "thread-message-region" )). queryByText ( "/cancel_goal" )). not . toBeInTheDocument ();
fireEvent . change ( input , { target : { value : "" } });
if ( status === "blocked" ) {
act (() => client . _emitChat ( chatId , { event : "delta" , chat_id : chatId , turn_id : "running-turn" , stream_id : "live" , text : " after goal cancellation" }));
expect ( await screen . findByText ( "Still responding after goal cancellation" )). toBeVisible ();
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeVisible ();
} else {
expect ( screen . queryByRole ( "button" , { name : "Stop response" })). not . toBeInTheDocument ();
}
});
it ( "disables offline goal cancellation and treats an unchanged goal after a control reply as a retryable failure" , async () => {
const client = makeClient ();
const chatId = "cancel-failure" ;
2026-11-18 16:10:02 +08:00
render (< ToastProvider >{ wrap ( client , < ThreadShell session = { session ( chatId )} title = "Goal" onToggleSidebar = {() => {}} />)}</ ToastProvider >);
2026-11-14 23:48:13 +08:00
await act ( async () => {});
act (() => {
client . _emitChat ( chatId , { event : "goal_state" , chat_id : chatId , goal_state : { active : false , status : "blocked" , objective : "Ship the release" } });
client . _emitStatus ( "closed" );
});
fireEvent . click ( await screen . findByRole ( "button" , { name : "Show full goal" }));
const button = screen . getByRole ( "button" , { name : "Cancel goal" });
expect ( button ). toBeDisabled ();
fireEvent . click ( button );
expect ( client . sendSystemCommand ). not . toHaveBeenCalled ();
act (() => client . _emitStatus ( "open" ));
fireEvent . click ( button );
expect ( await screen . findByRole ( "alert" )). toHaveTextContent ( "Could not cancel goal. Try again." );
expect ( button ). toBeEnabled ();
expect ( screen . getByRole ( "dialog" , { name : "Goal" })). toBeVisible ();
client . sendSystemCommand . mockImplementationOnce ( async () => {
client . _emitChat ( chatId , { event : "goal_state" , chat_id : chatId , goal_state : { active : false } });
});
fireEvent . click ( button );
await waitFor (() => expect ( screen . queryByRole ( "button" , { name : "Show full goal" })). not . toBeInTheDocument ());
expect ( client . sendSystemCommand ). toHaveBeenCalledTimes ( 2 );
});
it ( "sends /cancel_goal directly while streaming without a transcript entry, /stop, or offline replay" , async () => {
const client = makeClient ();
const chatId = "cancel-slash" ;
vi . stubGlobal ( "fetch" , vi . fn ( async ( input : RequestInfo | URL ) => String ( input ). endsWith ( "/api/commands" )
? httpJson ({ commands : [{ command : "/cancel_goal" , title : "Cancel goal" , description : "Cancel the goal" , icon : "square" , lifecycle : "side_channel" , accepts_args : false }] })
: new Response ( null , { status : 404 })));
render ( wrap ( client , < ThreadShell session = { session ( chatId )} title = "Goal" onToggleSidebar = {() => {}} />));
await act ( async () => {});
act (() => {
client . _emitChat ( chatId , { event : "goal_state" , chat_id : chatId , goal_state : { active : false , status : "blocked" , objective : "Ship the release" } });
client . _emitChat ( chatId , { event : "goal_status" , chat_id : chatId , turn_id : "unrelated" , status : "running" , started_at : 100 });
client . _emitChat ( chatId , { event : "delta" , chat_id : chatId , turn_id : "unrelated" , stream_id : "live" , text : "Unrelated reply" });
client . _emitStatus ( "closed" );
});
const input = screen . getByRole ( "textbox" , { name : "Message input" });
fireEvent . change ( input , { target : { value : "/cancel_goal" } });
expect ( await screen . findByRole ( "option" , { name : /Cancel goal/ })). toBeVisible ();
fireEvent . keyDown ( input , { key : "Escape" });
fireEvent . keyDown ( input , { key : "Enter" });
expect ( await screen . findByText ( "Reconnect to cancel the goal." )). toBeVisible ();
expect ( client . sendSystemCommand ). not . toHaveBeenCalled ();
expect ( input ). toHaveValue ( "/cancel_goal" );
act (() => client . _emitStatus ( "open" ));
expect ( client . sendSystemCommand ). not . toHaveBeenCalled ();
client . sendSystemCommand . mockImplementationOnce ( async () => {
client . _emitChat ( chatId , { event : "goal_state" , chat_id : chatId , goal_state : { active : false } });
});
fireEvent . keyDown ( input , { key : "Enter" });
await waitFor (() => expect ( input ). toHaveValue ( "" ));
expect ( client . sendSystemCommand ). toHaveBeenCalledTimes ( 1 );
expect ( client . sendSystemCommand ). toHaveBeenCalledWith ( chatId , "/cancel_goal" );
expect ( client . sendMessage ). not . toHaveBeenCalled ();
expect ( client . finishRunLocally ). not . toHaveBeenCalled ();
expect ( within ( screen . getByTestId ( "thread-message-region" )). queryByText ( "/cancel_goal" )). not . toBeInTheDocument ();
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeVisible ();
});
2026-05-13 08:47:34 +00:00
it ( "opens slash commands on the blank welcome page" , async () => {
2026-05-06 15:54:15 +00:00
const client = makeClient ();
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
const url = String ( input );
if ( url . endsWith ( "/api/commands" )) {
return httpJson ({
commands : [
{
2026-11-14 22:07:21 +08:00
command : "/inspect" ,
title : "Inspect session" ,
description : "Inspect a session." ,
2026-05-13 08:47:34 +00:00
icon : "history" ,
arg_hint : "[n]" ,
2026-07-07 14:01:07 +08:00
lifecycle : "side_channel" ,
accepts_args : true ,
2026-05-06 15:54:15 +00:00
},
],
});
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
};
}),
);
render (
wrap (
client ,
< ThreadShell
session = { null }
title = "nanobot"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( fetch ). toHaveBeenCalledWith (
"/api/commands" ,
expect . objectContaining ({
headers : { Authorization : "Bearer tok" },
}),
));
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "/" },
});
2026-05-13 08:47:34 +00:00
expect ( screen . getByRole ( "listbox" , { name : "Slash commands" })). toBeInTheDocument ();
2026-11-14 22:07:21 +08:00
expect ( screen . getByRole ( "option" , { name : /\/inspect/i })). toBeInTheDocument ();
2026-05-06 15:54:15 +00:00
});
2026-07-29 23:15:45 +08:00
it ( "surfaces a dismissible banner for an uncorrelated message_too_big error" , async () => {
2026-04-21 10:29:47 +00:00
const client = makeClient ();
render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-a" )}
title = "Chat chat-a"
onToggleSidebar = {() => {}}
/>,
),
);
expect ( screen . queryByRole ( "alert" )). not . toBeInTheDocument ();
2026-05-06 15:54:15 +00:00
await act ( async () => {});
2026-04-21 10:29:47 +00:00
await act ( async () => {
client . _emitError ({ kind : "message_too_big" });
});
const banner = await screen . findByRole ( "alert" );
expect ( banner ). toHaveTextContent ( "Message too large" );
fireEvent . click ( screen . getByRole ( "button" , { name : "Dismiss" }));
await waitFor (() => {
expect ( screen . queryByRole ( "alert" )). not . toBeInTheDocument ();
});
});
2026-11-19 18:39:00 +08:00
it . each ([
[ "unsupported_image" , "Image input is off for this preset" ],
[ "image_request_rejected" , "The model rejected the image request" ],
])( "shows %s as a preset action toast when there is no work to recover" , async ( errorKind , toastTitle ) => {
const chatId = "chat-image-failure" ;
const client = makeClient ();
const inspectPreset = vi . fn ();
render ( wrap ( client , < ToastProvider >
< ThreadShell
session = {{ ... session ( chatId ), modelPreset : "test-vision" }}
title = "Chat image failure"
onToggleSidebar = {() => {}}
onInspectImagePreset = { inspectPreset }
/>
</ ToastProvider >));
await act ( async () => {});
act (() => client . _emitChat ( chatId , {
event : "turn_end" , chat_id : chatId , turn_id : "image-turn" ,
outcome : "failed" , failure_kind : "model" , failure_error_kind : errorKind ,
}));
expect ( screen . queryByRole ( "alert" )). not . toBeInTheDocument ();
act (() => client . _emitChat ( chatId , {
event : "recovery_state" , chat_id : chatId , recovery_id : "image-attempt" ,
status : "recovered" , reason : "input_rejected" , failure_error_kind : errorKind ,
}));
const toast = await screen . findByRole ( "alert" );
expect ( toast . closest ( '[data-toast-tone="error"]' )). not . toBeNull ();
expect ( toast ). toHaveTextContent ( toastTitle );
expect ( screen . queryByRole ( "button" , { name : "Continue" })). not . toBeInTheDocument ();
fireEvent . click ( screen . getByRole ( "button" , { name : "View preset" }));
expect ( inspectPreset ). toHaveBeenCalledOnce ();
expect ( inspectPreset ). toHaveBeenCalledWith ( "test-vision" );
});
2026-10-20 15:48:32 +08:00
it . each ([ false , true ])( "keeps one terminal model failure visible until the next user action (recovery: %s)" , async ( recoverable ) => {
2026-09-07 15:12:39 +08:00
const client = makeClient ();
await act ( async () => {
await i18n . changeLanguage ( "zh-CN" );
});
render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-model-failure" )}
title = "Chat model failure"
onToggleSidebar = {() => {}}
/>,
),
);
await act ( async () => {});
act (() => {
client . _emitChat ( "chat-model-failure" , {
event : "turn_end" ,
chat_id : "chat-model-failure" ,
turn_id : "turn-model-failure" ,
outcome : "failed" ,
failure_kind : "model" ,
failure_error_kind : "connection" ,
failure_attempts : 4 ,
failure_message : "Unlocalized server failure" ,
});
});
const banner = await screen . findByRole ( "alert" );
2026-10-27 16:22:33 +08:00
expect ( banner ). toHaveTextContent ( "模型连接异常" );
2026-09-07 15:12:39 +08:00
expect ( banner ). toHaveTextContent (
2026-10-20 15:48:32 +08:00
"已尝试 4 次,仍未成功。可稍后继续或切换模型。" ,
2026-09-07 15:12:39 +08:00
);
expect ( banner ). not . toHaveTextContent ( "Unlocalized server failure" );
2026-10-20 15:48:32 +08:00
if ( recoverable ) {
act (() => {
client . _emitChat ( "chat-model-failure" , {
event : "recovery_state" ,
chat_id : "chat-model-failure" ,
recovery_id : "model-recovery" ,
status : "awaiting_user" ,
reason : "model_request_failed" ,
failure_error_kind : "connection" ,
});
});
expect ( screen . getAllByRole ( "alert" )). toHaveLength ( 1 );
2026-10-27 16:22:33 +08:00
expect ( screen . getByRole ( "alert" )). toHaveTextContent ( "模型连接异常" );
2026-10-20 15:48:32 +08:00
expect ( screen . getByRole ( "button" , { name : "继续" })). toBeEnabled ();
}
2026-09-07 15:12:39 +08:00
fireEvent . change ( screen . getByLabelText ( "消息输入框" ), {
target : { value : "try again" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "发送消息" }));
2026-10-20 15:48:32 +08:00
if ( recoverable ) {
act (() => {
client . _emitChat ( "chat-model-failure" , {
event : "recovery_state" ,
chat_id : "chat-model-failure" ,
recovery_id : "model-recovery" ,
status : "recovered" ,
reason : "superseded" ,
});
});
}
2026-09-07 15:12:39 +08:00
await waitFor (() => {
expect ( screen . queryByRole ( "alert" )). not . toBeInTheDocument ();
});
2026-10-24 00:43:34 +08:00
expect ( screen . getByRole ( "button" , { name : "停止响应" })). toBeInTheDocument ();
const nextTurnId = client . getRunTurnId ( "chat-model-failure" ) ! ;
act (() => {
client . _emitChat ( "chat-model-failure" , {
event : "goal_status" , chat_id : "chat-model-failure" , turn_id : nextTurnId ,
status : "running" , started_at : 1_700_000_000 ,
});
client . _emitChat ( "chat-model-failure" , {
event : "delta" , chat_id : "chat-model-failure" , turn_id : nextTurnId ,
text : "New request is running" ,
});
});
expect ( await screen . findByText ( "New request is running" )). toBeVisible ();
expect ( client . getRunState ( "chat-model-failure" )). toMatchObject ({ active : true , startedAt : 1_700_000_000 });
act (() => client . _emitChat ( "chat-model-failure" , {
event : "turn_end" , chat_id : "chat-model-failure" , turn_id : nextTurnId ,
}));
expect ( screen . queryByRole ( "button" , { name : "停止响应" })). not . toBeInTheDocument ();
2026-09-07 15:12:39 +08:00
});
2026-07-29 23:15:45 +08:00
it ( "moves a correlated delivery error from the banner into the failed message tooltip" , async () => {
const client = makeClient ();
render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-inline-error" )}
title = "Chat inline error"
onToggleSidebar = {() => {}}
/>,
),
);
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "oversized payload" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( client . sendMessage ). toHaveBeenCalledTimes ( 1 ));
const turnId = client . sendMessage . mock . calls [ 0 ][ 3 ] ? . turnId ;
expect ( turnId ). toEqual ( expect . any ( String ));
await act ( async () => {
client . _emitError ({
kind : "message_too_big" ,
chatId : "chat-inline-error" ,
turnId ,
});
});
expect ( screen . queryByRole ( "button" , { name : "Dismiss" })). not . toBeInTheDocument ();
const status = screen . getByRole ( "button" , {
name : "Not sent: Message too large" ,
});
expect ( screen . getByRole ( "alert" )). toHaveClass ( "sr-only" );
expect ( screen . queryByRole ( "tooltip" )). not . toBeInTheDocument ();
fireEvent . focus ( status );
expect ( await screen . findByRole ( "tooltip" )). toHaveTextContent (
"The server rejected your last message because it exceeded the size limit." ,
);
});
2026-04-21 10:29:47 +00:00
it ( "clears the stream error banner when the user switches to another chat" , async () => {
const client = makeClient ();
const { rerender } = render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-a" )}
title = "Chat chat-a"
onToggleSidebar = {() => {}}
/>,
),
);
2026-05-06 15:54:15 +00:00
await act ( async () => {});
2026-04-21 10:29:47 +00:00
await act ( async () => {
client . _emitError ({ kind : "message_too_big" });
});
expect ( await screen . findByRole ( "alert" )). toBeInTheDocument ();
// Switch to a different chat. The banner was about the *previous* send
// in chat-a; it must not leak into chat-b's view.
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "chat-b" )}
title = "Chat chat-b"
onToggleSidebar = {() => {}}
/>,
),
);
});
await waitFor (() => {
expect ( screen . queryByRole ( "alert" )). not . toBeInTheDocument ();
});
});
2026-04-18 18:51:53 +00:00
it ( "clears the previous thread immediately while the next session loads" , async () => {
const client = makeClient ();
let resolveChatB :
| (( value : { ok : boolean ; status : number ; json : () => Promise < unknown > }) => void )
| null = null ;
vi . stubGlobal (
"fetch" ,
vi . fn (( input : RequestInfo | URL ) => {
const url = String ( input );
2026-05-16 01:14:11 +08:00
if ( url . includes ( "websocket%3Achat-a/webui-thread" )) {
2026-04-18 18:51:53 +00:00
return Promise . resolve (
2026-05-16 01:14:11 +08:00
httpJson (
transcriptFromSimpleMessages ([{ role : "assistant" , content : "from chat a" }]),
),
2026-04-18 18:51:53 +00:00
);
}
2026-05-16 01:14:11 +08:00
if ( url . includes ( "websocket%3Achat-b/webui-thread" )) {
2026-04-18 18:51:53 +00:00
return new Promise (( resolve ) => {
resolveChatB = resolve ;
});
}
return Promise . resolve ({
ok : false ,
status : 404 ,
json : async () => ({}),
});
}),
);
const { rerender } = render (
wrap (
client ,
< ThreadShell
session = { session ( "chat-a" )}
title = "Chat chat-a"
onToggleSidebar = {() => {}}
/>,
),
);
await waitFor (() => expect ( screen . getByText ( "from chat a" )). toBeInTheDocument ());
await act ( async () => {
rerender (
wrap (
client ,
< ThreadShell
session = { session ( "chat-b" )}
title = "Chat chat-b"
onToggleSidebar = {() => {}}
/>,
),
);
});
expect ( screen . queryByText ( "from chat a" )). not . toBeInTheDocument ();
2026-10-20 21:41:30 +08:00
const loading = screen . getByRole ( "status" , { name : "Loading conversation…" });
expect ( loading ). toHaveAttribute ( "aria-busy" , "true" );
expect ( loading . querySelector ( "[aria-hidden]" )). not . toBeEmptyDOMElement ();
expect ( screen . getByRole ( "textbox" , { name : "Message input" })). toBeEnabled ();
const header = screen . getByTestId ( "thread-header" );
const composer = screen . getByTestId ( "thread-composer-motion" );
expect ( composer . closest ( "[data-layout]" )). toHaveAttribute ( "data-layout" , "thread" );
2026-04-18 18:51:53 +00:00
await act ( async () => {
resolveChatB ? .(
2026-05-16 01:14:11 +08:00
httpJson ( transcriptFromSimpleMessages ([{ role : "assistant" , content : "from chat b" }])),
2026-04-18 18:51:53 +00:00
);
});
await waitFor (() => expect ( screen . getByText ( "from chat b" )). toBeInTheDocument ());
expect ( screen . queryByText ( "from chat a" )). not . toBeInTheDocument ();
2026-10-20 21:41:30 +08:00
expect ( screen . queryByRole ( "status" , { name : "Loading conversation…" })). not . toBeInTheDocument ();
expect ( screen . getByTestId ( "thread-header" )). toBe ( header );
expect ( screen . getByTestId ( "thread-composer-motion" )). toBe ( composer );
});
2026-11-13 17:12:18 +08:00
it . each ([ false , true ])( "replaces the initial history skeleton with the empty composer when no visible history remains (systemOnly=%s)" , async ( systemOnly ) => {
2026-10-20 21:41:30 +08:00
let resolveHistory !: ( response : Response ) => void ;
vi . mocked ( fetch ). mockImplementation (( input ) => String ( input ). includes ( "/webui-thread" )
? new Promise < Response >(( resolve ) => { resolveHistory = resolve ; })
: Promise . resolve ( new Response ( null , { status : 404 })));
render ( wrap ( makeClient (), < ThreadShell session = { session ( "empty-topic" )} title = "Empty topic"
onToggleSidebar = {() => {}} />));
expect ( screen . getByRole ( "status" , { name : "Loading conversation…" })). toHaveAttribute ( "aria-busy" , "true" );
await act ( async () => {
resolveHistory ( httpJson ( transcriptFromSimpleMessages ( systemOnly
? [{ role : "assistant" , content : "Model selected" , turnId : "webui-system:model-preset" }]
: [])));
});
2026-11-13 17:12:18 +08:00
await waitFor (() => expect ( screen . getByTestId ( "thread-welcome-layout" )). toHaveAttribute ( "data-layout" , "hero" ));
2026-10-20 21:41:30 +08:00
expect ( screen . queryByRole ( "status" , { name : "Loading conversation…" })). not . toBeInTheDocument ();
2026-11-13 17:12:18 +08:00
expect ( within ( screen . getByTestId ( "thread-empty-region" )). getByRole ( "heading" , { level : 1 , name : "Empty topic" })). toHaveClass ( "sr-only" );
expect ( screen . getByRole ( "textbox" , { name : "Message input" })). toBeEnabled ();
2026-10-20 21:41:30 +08:00
});
it ( "keeps cached messages visible while the first history revalidation is pending" , async () => {
webuiThreadCache . set ( "websocket:cached-topic" , transcriptFromSimpleMessages ([
{ role : "assistant" , content : "Cached answer" },
]));
vi . mocked ( fetch ). mockImplementation (( input ) => String ( input ). includes ( "/webui-thread" )
? new Promise < Response >(() => {})
: Promise . resolve ( new Response ( null , { status : 404 })));
render ( wrap ( makeClient (), < ThreadShell session = { session ( "cached-topic" )} title = "Cached topic"
onToggleSidebar = {() => {}} />));
expect ( await screen . findByText ( "Cached answer" )). toBeVisible ();
expect ( screen . queryByRole ( "status" , { name : "Loading conversation…" })). not . toBeInTheDocument ();
expect ( screen . getByRole ( "textbox" , { name : "Message input" })). toBeEnabled ();
2026-04-18 18:51:53 +00:00
});
2026-05-23 00:59:54 +08:00
2026-09-24 23:10:57 +08:00
it ( "loads mention catalogs only on demand and ignores window focus" , async () => {
2026-09-24 23:19:06 +08:00
const originalFetch = vi . mocked ( fetch ). getMockImplementation () ! ;
vi . mocked ( fetch ). mockImplementation (( input , init ) => {
if ( String ( input ). includes ( "cli-apps" )) return Promise . resolve ( httpJson ({ apps : [], installed_count : 0 }));
if ( String ( input ). includes ( "mcp-presets" )) return Promise . resolve ( httpJson ({ presets : [], installed_count : 0 }));
return originalFetch ( input , init );
});
2026-09-24 23:10:57 +08:00
render ( wrap ( makeClient (), < ThreadShell
session = { session ( "lazy-mentions" )}
title = "Lazy mentions"
onToggleSidebar = {() => {}}
/>));
const input = await screen . findByLabelText ( "Message input" );
const catalogCalls = () => vi . mocked ( fetch ). mock . calls . filter (([ url ]) =>
/cli-apps|mcp-presets/ . test ( String ( url )));
fireEvent . change ( input , { target : { value : "hello" , selectionStart : 5 } });
fireEvent ( window , new Event ( "focus" ));
expect ( catalogCalls ()). toHaveLength ( 0 );
fireEvent . change ( input , { target : { value : "@" , selectionStart : 1 } });
await waitFor (() => expect ( catalogCalls ()). toHaveLength ( 2 ));
fireEvent ( window , new Event ( "focus" ));
fireEvent . change ( input , { target : { value : "@app" , selectionStart : 4 } });
fireEvent . change ( input , { target : { value : "" , selectionStart : 0 } });
fireEvent . change ( input , { target : { value : "@" , selectionStart : 1 } });
expect ( catalogCalls ()). toHaveLength ( 2 );
});
2026-09-24 23:19:06 +08:00
it ( "retries a failed mention catalog when the user opens mentions again" , async () => {
vi . mocked ( fetch ). mockResolvedValue ({ ok : false , status : 503 , json : async () => ({}) } as Response );
render ( wrap ( makeClient (), < ThreadShell
session = { session ( "retry-mentions" )}
title = "Retry mentions"
onToggleSidebar = {() => {}}
/>));
const input = await screen . findByLabelText ( "Message input" );
const catalogCalls = () => vi . mocked ( fetch ). mock . calls . filter (([ url ]) =>
/cli-apps|mcp-presets/ . test ( String ( url )));
await act ( async () => {
fireEvent . change ( input , { target : { value : "@" , selectionStart : 1 } });
});
expect ( catalogCalls ()). toHaveLength ( 2 );
fireEvent . change ( input , { target : { value : "" , selectionStart : 0 } });
await act ( async () => {
fireEvent . change ( input , { target : { value : "@" , selectionStart : 1 } });
});
expect ( catalogCalls ()). toHaveLength ( 4 );
});
2026-05-23 00:59:54 +08:00
it ( "updates @ CLI app suggestions when settings broadcasts an install" , async () => {
const client = makeClient ();
render ( wrap (
client ,
< ThreadShell
session = { session ( "chat-cli-apps" )}
title = "Chat chat-cli-apps"
onToggleSidebar = {() => {}}
/>,
));
const input = await screen . findByLabelText ( "Message input" );
2026-08-02 22:04:59 +08:00
expect ( screen . queryByRole ( "listbox" , { name : "Mentions" })). not . toBeInTheDocument ();
2026-05-23 00:59:54 +08:00
const payload : CliAppsPayload = {
apps : [{
name : "gimp" ,
display_name : "GIMP" ,
category : "image" ,
description : "Image editing" ,
requires : "" ,
source : "harness" ,
entry_point : "cli-anything-gimp" ,
install_supported : true ,
installed : true ,
available : true ,
status : "installed" ,
logo_url : null ,
brand_color : "#5C5543" ,
skill_installed : true ,
}],
installed_count : 1 ,
catalog_updated_at : "2026-04-18" ,
};
await act ( async () => {
window . dispatchEvent ( new CustomEvent ( CLI_APPS_CHANGED_EVENT , { detail : payload }));
});
fireEvent . change ( input , { target : { value : "@" , selectionStart : 1 } });
2026-08-02 22:04:59 +08:00
expect ( screen . getByRole ( "listbox" , { name : "Mentions" })). toBeInTheDocument ();
2026-05-23 00:59:54 +08:00
expect ( screen . getByRole ( "option" , { name : /@gimp/i })). toBeInTheDocument ();
});
2026-07-15 00:34:22 +08:00
2026-07-30 10:25:22 +08:00
it ( "does not let an older catalog request overwrite a newer install event" , async () => {
const client = makeClient ();
let resolveCatalog !: ( response : Response ) => void ;
const pendingCatalog = new Promise < Response >(( resolve ) => {
resolveCatalog = resolve ;
});
vi . mocked ( fetch ). mockImplementation (( input ) => {
if ( String ( input ). includes ( "/api/settings/cli-apps?installed_only=1" )) {
return pendingCatalog ;
}
return Promise . resolve ({
ok : false ,
status : 404 ,
json : async () => ({}),
} as Response );
});
render ( wrap (
client ,
< ThreadShell
session = { session ( "chat-cli-race" )}
title = "Chat chat-cli-race"
onToggleSidebar = {() => {}}
/>,
));
const input = await screen . findByLabelText ( "Message input" );
2026-09-24 23:10:57 +08:00
fireEvent . change ( input , { target : { value : "@" , selectionStart : 1 } });
2026-07-30 10:25:22 +08:00
await waitFor (() => expect ( fetch ). toHaveBeenCalledWith (
"/api/settings/cli-apps?installed_only=1" ,
expect . anything (),
));
const payload : CliAppsPayload = {
apps : [{
name : "gimp" ,
display_name : "GIMP" ,
category : "image" ,
description : "Image editing" ,
requires : "" ,
source : "harness" ,
entry_point : "cli-anything-gimp" ,
install_supported : true ,
installed : true ,
available : true ,
status : "installed" ,
logo_url : null ,
brand_color : "#5C5543" ,
skill_installed : true ,
}],
installed_count : 1 ,
catalog_updated_at : "2026-07-30" ,
};
await act ( async () => {
window . dispatchEvent ( new CustomEvent ( CLI_APPS_CHANGED_EVENT , { detail : payload }));
resolveCatalog ( httpJson ({ apps : [], installed_count : 0 }));
await pendingCatalog ;
});
fireEvent . change ( input , { target : { value : "@" , selectionStart : 1 } });
expect ( screen . getByRole ( "option" , { name : /@gimp/i })). toBeInTheDocument ();
});
2026-07-15 00:34:22 +08:00
it ( "keeps installed app mentions available during transient catalog refresh failures" , async () => {
const client = makeClient ();
const payload : CliAppsPayload = {
apps : [{
name : "obsidian-agent-cli" ,
display_name : "Obsidian" ,
category : "productivity" ,
description : "Obsidian automation" ,
requires : "" ,
source : "harness" ,
entry_point : "cli-anything-obsidian" ,
install_supported : true ,
installed : true ,
available : true ,
status : "installed" ,
logo_url : null ,
brand_color : "#7C3AED" ,
skill_installed : true ,
}],
installed_count : 1 ,
catalog_updated_at : "2026-07-14" ,
};
vi . mocked ( fetch ). mockImplementation ( async ( input ) => {
if ( String ( input ). includes ( "/api/settings/cli-apps?installed_only=1" )) {
throw new Error ( "temporary catalog failure" );
}
return {
ok : false ,
status : 404 ,
json : async () => ({}),
} as Response ;
});
render ( wrap (
client ,
< ThreadShell
session = { session ( "chat-cli-refresh" )}
title = "Chat chat-cli-refresh"
onToggleSidebar = {() => {}}
/>,
));
const input = await screen . findByLabelText ( "Message input" );
await act ( async () => {
window . dispatchEvent ( new CustomEvent ( CLI_APPS_CHANGED_EVENT , { detail : payload }));
});
const mention = "@obsidian-agent-cli" ;
fireEvent . change ( input , { target : { value : mention , selectionStart : mention.length } });
expect ( screen . getByRole ( "option" , { name : /@obsidian-agent-cli/i })). toBeInTheDocument ();
await act ( async () => {
window . dispatchEvent ( new Event ( "focus" ));
await Promise . resolve ();
});
expect ( screen . getByRole ( "option" , { name : /@obsidian-agent-cli/i })). toBeInTheDocument ();
expect ( screen . getByTestId ( "composer-cli-mention-obsidian-agent-cli" )). toHaveTextContent (
2026-09-13 12:04:33 +08:00
"@Obsidian" ,
2026-07-15 00:34:22 +08:00
);
2026-09-13 12:04:33 +08:00
expect ( input ). toHaveValue ( "@Obsidian" );
2026-07-15 00:34:22 +08:00
});
2026-08-04 00:01:08 +08:00
2026-08-18 18:28:19 +08:00
it ( "offers sessions across projects in restricted mode" , async () => {
const client = makeClient ();
const currentScope = {
project_path : "/projects/current" ,
access_mode : "restricted" as const ,
};
const sameProject = {
... session ( "same-project" ),
title : "Same project" ,
workspaceScope : currentScope ,
handle : {
id : "handle_11111111111111111111111111111111" ,
name : "same-1111111111" ,
},
};
const otherProject = {
... session ( "other-project" ),
title : "Other project" ,
workspaceScope : {
project_path : "/projects/other" ,
access_mode : "restricted" as const ,
},
handle : {
id : "handle_22222222222222222222222222222222" ,
name : "other-2222222222" ,
},
};
2026-08-04 00:01:08 +08:00
2026-08-18 18:28:19 +08:00
render ( wrap (
client ,
< ThreadShell
session = { session ( "current" )}
sessions = {[ sameProject , otherProject ]}
title = "Current"
onToggleSidebar = {() => {}}
workspaceScope = { currentScope }
/>,
));
2026-08-04 00:01:08 +08:00
2026-08-18 18:28:19 +08:00
const input = await screen . findByLabelText ( "Message input" );
fireEvent . change ( input , { target : { value : "@" , selectionStart : 1 } });
expect ( screen . getByRole ( "option" , { name : /Same project/i })). toBeInTheDocument ();
expect ( screen . getByRole ( "option" , { name : /Other project/i })). toBeInTheDocument ();
});
2026-08-04 00:01:08 +08:00
2026-10-28 21:37:23 +08:00
it . each ([ true , undefined ])( "locks saved topics with projectLocked=%s independently of displayed history" , async ( projectLocked ) => {
2026-10-23 21:09:21 +08:00
const client = makeClient ();
const scope = { project_path : "/srv/alpha" , project_name : "alpha" , access_mode : "restricted" as const };
const props = {
title : "Project chat" , onToggleSidebar : () => {}, workspaceScope : scope ,
workspaceDefaultScope : scope , workspaceControls : { can_change_project : true },
onWorkspaceScopeChange : vi.fn (),
};
const { rerender } = render ( wrap ( client , < ThreadShell { ...props } session = {{ ... session ( "project-chat" ), projectLocked : false }} />));
expect ( await screen . findByRole ( "button" , { name : "Switch directory" })). toBeEnabled ();
expect ( screen . getByTestId ( "thread-header" )). not . toHaveTextContent ( "alpha" );
2026-10-28 21:37:23 +08:00
rerender ( wrap ( client , < ThreadShell { ...props } session = {{ ... session ( "project-chat" ), projectLocked }} />));
2026-10-23 21:09:21 +08:00
expect ( screen . queryByRole ( "button" , { name : "Switch directory" })). not . toBeInTheDocument ();
expect ( screen . getByTestId ( "thread-header" )). not . toHaveTextContent ( "alpha" );
expect ( screen . getByRole ( "button" , { name : "Workspace access mode: Default Permission" })). toBeEnabled ();
});
2026-10-16 18:18:29 +08:00
it ( "keeps normal running controls when attaching to a resumed task" , async () => {
const client = makeClient ();
render ( wrap (
client ,
< ThreadShell
session = { session ( "resuming-chat" )}
title = "Resuming chat"
onToggleSidebar = {() => {}}
/>,
));
await screen . findByLabelText ( "Message input" );
act (() => {
client . _emitChat ( "resuming-chat" , {
event : "attached" ,
chat_id : "resuming-chat" ,
recovery_state : { recovery_id : "recovery-1" , status : "resuming" },
});
});
expect ( screen . queryByText ( "Restoring interrupted task…" )). not . toBeInTheDocument ();
fireEvent . click ( screen . getByRole ( "button" , { name : "Stop response" }));
expect ( client . sendMessage ). toHaveBeenCalledWith ( "resuming-chat" , "/stop" );
});
2026-10-24 00:43:34 +08:00
it . each ([ "awaiting_user" , "failed" , "recovered" ] as const )( "allows a new turn after a %s recovery state" , async ( status ) => {
2026-08-22 19:33:22 +08:00
const client = makeClient ();
render ( wrap (
client ,
< ThreadShell
session = { session ( "recovered-chat" )}
title = "Recovered chat"
onToggleSidebar = {() => {}}
/>,
));
const input = await screen . findByLabelText ( "Message input" );
act (() => {
client . _emitChat ( "recovered-chat" , {
event : "recovery_state" ,
chat_id : "recovered-chat" ,
recovery_id : "recovery-1" ,
2026-10-24 00:43:34 +08:00
status ,
2026-08-22 19:33:22 +08:00
});
});
fireEvent . change ( input , { target : { value : "start the next task" } });
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
expect ( client . sendMessage ). toHaveBeenCalledOnce ();
expect ( screen . getByRole ( "button" , { name : "Stop response" })). toBeInTheDocument ();
});
2026-04-18 18:51:53 +00:00
});