2026-08-09 21:37:06 +08:00
import { act , cleanup , fireEvent , render , screen , waitFor , within } from "@testing-library/react" ;
2026-08-04 15:32:29 +08:00
import userEvent from "@testing-library/user-event" ;
2026-05-18 00:53:36 +08:00
import { afterEach , beforeEach , describe , expect , it , vi } from "vitest" ;
2026-09-30 15:09:14 +08:00
import type { Window as HappyWindow } from "happy-dom" ;
2026-04-18 18:51:53 +00:00
2026-06-12 18:13:25 +08:00
import i18n from "@/i18n" ;
2026-08-06 18:29:04 +08:00
import type {
ChatSummary ,
ConnectionStatus ,
SessionAutomationJob ,
2026-08-12 14:45:12 +08:00
SidebarStatePayload ,
2026-08-06 18:29:04 +08:00
WorkspaceScopePayload ,
} from "@/lib/types" ;
2026-04-18 18:51:53 +00:00
2026-09-30 15:09:14 +08:00
( window as unknown as HappyWindow ). happyDOM . settings . disableIframePageLoading = true ;
2026-04-18 18:51:53 +00:00
const connectSpy = vi . fn ();
const refreshSpy = vi . fn ();
const createChatSpy = vi . fn (). mockResolvedValue ( "chat-1" );
const deleteChatSpy = vi . fn ();
2026-06-12 18:13:25 +08:00
const getSessionAutomationsSpy = vi . fn < ( key : string ) => Promise < SessionAutomationJob [] > > ();
2026-05-06 14:15:36 +00:00
const toggleThemeSpy = vi . fn ();
2026-05-18 00:53:36 +08:00
const updateUrlSpy = vi . fn ();
2026-05-19 22:42:38 +08:00
const attachSpy = vi . fn ();
2026-08-06 18:21:16 +08:00
const setSidebarStateSpy = vi . fn ();
2026-08-10 15:43:54 +08:00
const requestMutationSpy = vi . fn ();
2026-08-05 19:24:41 +08:00
const discardTemporaryChatSpy = vi . fn ();
2026-08-07 11:20:08 +08:00
const newTemporaryChatSpy = vi . fn < () => Promise < string > > ();
2026-08-06 18:29:04 +08:00
const sendMessageSpy = vi . fn ();
2026-10-12 11:36:42 +08:00
const sendSystemCommandSpy = vi . fn (). mockResolvedValue ( undefined );
let mockDefaultChatId : string | null = null ;
2026-08-06 18:29:04 +08:00
const statusHandlers = new Set < ( status : ConnectionStatus ) => void > ();
2026-05-19 22:42:38 +08:00
const runStatusHandlers = new Set < ( chatId : string , startedAt : number | null ) => void > ();
2026-08-06 18:29:04 +08:00
const sessionUpdateHandlers = new Set < (
chatId : string ,
scope? : string ,
workspaceScope? : WorkspaceScopePayload ,
) => void > ();
2026-08-12 14:45:12 +08:00
const sidebarStateUpdateHandlers = new Set < ( state : SidebarStatePayload ) => void > ();
2026-04-18 18:51:53 +00:00
let mockSessions : ChatSummary [] = [];
2026-05-29 03:42:53 +08:00
const HERO_GREETING_PATTERN =
/What should we work on\?|Where should we start\?|What are we building today\?|What should we tackle together\?/ ;
2026-04-18 18:51:53 +00:00
2026-06-04 13:54:52 +08:00
function setNavigatorPlatform ( platform : string ) : void {
Object . defineProperty ( window . navigator , "platform" , {
configurable : true ,
value : platform ,
});
}
2026-05-25 20:07:02 +08:00
function jsonResponse ( body : unknown ) : Response {
return {
ok : true ,
status : 200 ,
json : async () => body ,
} as Response ;
}
2026-06-06 19:49:33 +08:00
function mockFetchRoutes ( routes : Record < string , unknown >) : void {
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
2026-10-05 05:16:33 +08:00
const route = routes [ String ( input )]
?? ( /^\/api\/sessions\/[^/]+\/subagents$/ . test ( String ( input )) ? { tasks : [] } : undefined );
2026-07-28 20:32:13 +08:00
const body =
typeof route === "function"
? await ( route as () => unknown | Promise < unknown >)()
: route ;
2026-06-06 19:49:33 +08:00
return body === undefined
? ({ ok : false , status : 404 , json : async () => ({}) } as Response )
: jsonResponse ( body );
}),
);
}
2026-09-12 23:31:35 +08:00
function currentMonthTimestamp ( day : number , hour = 10 , minute = 0 ) : number {
const now = new Date ();
return new Date ( now . getFullYear (), now . getMonth (), day , hour , minute ). getTime ();
}
2026-05-25 20:07:02 +08:00
function baseSettingsPayload() {
return {
agent : {
model : "openai/gpt-4o" ,
provider : "auto" ,
resolved_provider : "openai" ,
has_api_key : true ,
model_preset : "default" ,
max_tokens : 8192 ,
context_window_tokens : 65536 ,
temperature : 0.1 ,
reasoning_effort : null ,
timezone : "UTC" ,
tool_hint_max_length : 40 ,
},
model_presets : [{
name : "default" ,
label : "Default" ,
active : true ,
is_default : true ,
model : "openai/gpt-4o" ,
provider : "auto" ,
max_tokens : 8192 ,
context_window_tokens : 65536 ,
temperature : 0.1 ,
reasoning_effort : null ,
}],
2026-07-24 00:55:06 +08:00
model_call_order : [],
model_call_order_editable : false ,
2026-05-25 20:07:02 +08:00
providers : [],
web_search : {
provider : "duckduckgo" ,
api_key_hint : null ,
base_url : null ,
max_results : 5 ,
timeout : 30 ,
providers : [{ name : "duckduckgo" , label : "DuckDuckGo" , credential : "none" }],
},
web : {
enable : true ,
proxy : null ,
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" ,
},
unified_session : false ,
},
advanced : {
restrict_to_workspace : false ,
2026-05-29 03:42:53 +08:00
webui_allow_local_service_access : true ,
webui_default_access_mode : "default" ,
private_service_protection_enabled : true ,
2026-05-25 20:07:02 +08:00
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-25 20:07:02 +08:00
exec_path_append_set : false ,
},
requires_restart : false ,
};
}
2026-04-18 18:51:53 +00:00
vi . mock ( "@/hooks/useSessions" , async ( importOriginal ) => {
const React = await import ( "react" );
const actual = await importOriginal < typeof import ( "@/hooks/useSessions" ) >();
return {
... actual ,
useSessions : () => {
const [ sessions , setSessions ] = React . useState ( mockSessions );
return {
sessions ,
loading : false ,
error : null ,
refresh : refreshSpy ,
2026-08-12 14:45:12 +08:00
createChat : async ( scope? : WorkspaceScopePayload | null ) => {
const chatId = await createChatSpy ( scope );
const now = new Date (). toISOString ();
setSessions (( prev : ChatSummary []) => [
{
key : `websocket: ${ chatId } ` ,
channel : "websocket" ,
chatId ,
createdAt : now ,
updatedAt : now ,
title : "" ,
preview : "" ,
workspaceScope : scope ?? null ,
},
... prev . filter (( session ) => session . chatId !== chatId ),
]);
return chatId ;
},
2026-06-05 19:49:34 +08:00
forkChat : async () => "fork-chat" ,
2026-06-12 18:13:25 +08:00
getSessionAutomations : getSessionAutomationsSpy ,
2026-06-12 17:02:29 +08:00
deleteChat : async ( key : string , options ?: { deleteAutomations? : boolean }) => {
if ( options === undefined ) await deleteChatSpy ( key );
else await deleteChatSpy ( key , options );
2026-04-18 18:51:53 +00:00
setSessions (( prev : ChatSummary []) => prev . filter (( s ) => s . key !== key ));
2026-06-11 19:11:37 +08:00
return { deleted : true };
2026-04-18 18:51:53 +00:00
},
};
},
};
});
2026-05-17 17:04:57 +08:00
vi . mock ( "@/hooks/useTheme" , async () => {
const React = await import ( "react" );
return {
ThemeProvider : ({ children } : { children : React.ReactNode }) =>
React . createElement ( React . Fragment , null , children ),
useTheme : () => ({
theme : "light" as const ,
toggle : toggleThemeSpy ,
}),
useThemeValue : () => "light" as const ,
};
});
2026-04-18 18:51:53 +00:00
vi . mock ( "@/lib/bootstrap" , () => ({
2026-07-08 15:46:52 +08:00
BootstrapAuthRequiredError : class BootstrapAuthRequiredError extends Error {
constructor ( message = "bootstrap authentication required" ) {
super ( message );
this . name = "BootstrapAuthRequiredError" ;
}
},
2026-04-18 18:51:53 +00:00
fetchBootstrap : vi.fn (). mockResolvedValue ({
token : "tok" ,
2026-07-08 14:27:52 +08:00
api_token : "api-tok" ,
2026-04-18 18:51:53 +00:00
ws_path : "/" ,
expires_in : 300 ,
}),
deriveWsUrl : vi.fn (() => "ws://test" ),
2026-07-08 14:27:52 +08:00
consumeUrlBootstrapSecret : vi.fn (() => "" ),
2026-05-06 23:15:18 +08:00
loadSavedSecret : vi.fn (() => "" ),
saveSecret : vi.fn (),
clearSavedSecret : vi.fn (),
2026-04-18 18:51:53 +00:00
}));
2026-08-06 18:29:04 +08:00
vi . mock ( "@/lib/nanobot-client" , async ( importOriginal ) => {
const actual = await importOriginal < typeof import ( "@/lib/nanobot-client" ) >();
2026-04-18 18:51:53 +00:00
class MockClient {
status = "idle" as const ;
2026-10-12 11:36:42 +08:00
defaultChatId = mockDefaultChatId ;
sendSystemCommand = sendSystemCommandSpy ;
2026-04-18 18:51:53 +00:00
connect = connectSpy ;
2026-08-06 18:29:04 +08:00
onStatus = ( handler : ( status : ConnectionStatus ) => void ) => {
statusHandlers . add ( handler );
return () => statusHandlers . delete ( handler );
};
2026-05-12 09:05:24 +00:00
onRuntimeModelUpdate = () => () => {};
2026-04-21 10:29:47 +00:00
onError = () => () => {};
2026-04-18 18:51:53 +00:00
onChat = () => () => {};
2026-08-06 18:29:04 +08:00
onSessionUpdate = ( handler : (
chatId : string ,
scope? : string ,
workspaceScope? : WorkspaceScopePayload ,
) => void ) => {
2026-06-15 17:30:06 +08:00
sessionUpdateHandlers . add ( handler );
return () => sessionUpdateHandlers . delete ( handler );
};
2026-08-12 14:45:12 +08:00
onSidebarStateUpdate = ( handler : ( state : SidebarStatePayload ) => void ) => {
sidebarStateUpdateHandlers . add ( handler );
return () => sidebarStateUpdateHandlers . delete ( handler );
};
2026-05-19 22:42:38 +08:00
onRunStatus = ( handler : ( chatId : string , startedAt : number | null ) => void ) => {
runStatusHandlers . add ( handler );
return () => runStatusHandlers . delete ( handler );
};
getRunStartedAt = () => null ;
2026-08-15 14:58:35 +08:00
getRunTurnId = () => null ;
2026-09-30 17:40:11 +08:00
fenceCanonicalCompletedTurns = vi . fn ();
2026-05-19 22:42:38 +08:00
getGoalState = () => undefined ;
2026-08-06 18:29:04 +08:00
sendMessage = sendMessageSpy ;
2026-04-18 18:51:53 +00:00
newChat = vi . fn ();
2026-08-07 11:20:08 +08:00
newTemporaryChat = newTemporaryChatSpy ;
2026-05-19 22:42:38 +08:00
attach = attachSpy ;
2026-08-06 18:21:16 +08:00
setSidebarState = setSidebarStateSpy ;
2026-08-10 15:43:54 +08:00
requestMutation = requestMutationSpy ;
2026-08-05 19:24:41 +08:00
discardTemporaryChat = discardTemporaryChatSpy ;
2026-04-18 18:51:53 +00:00
close = vi . fn ();
2026-05-18 00:53:36 +08:00
updateUrl = updateUrlSpy ;
2026-07-28 11:40:01 +08:00
updateMaxFrameBytes = vi . fn ();
2026-04-18 18:51:53 +00:00
}
2026-08-06 18:29:04 +08:00
return { ... actual , NanobotClient : MockClient };
2026-04-18 18:51:53 +00:00
});
2026-07-08 15:46:52 +08:00
import {
BootstrapAuthRequiredError ,
deriveWsUrl ,
fetchBootstrap ,
} from "@/lib/bootstrap" ;
2026-04-18 18:51:53 +00:00
import App from "@/App" ;
2026-09-21 13:44:42 +08:00
import { mockBrowserFocus } from "./browser-focus" ;
2026-04-18 18:51:53 +00:00
describe ( "App layout" , () => {
2026-09-21 13:44:42 +08:00
let restoreBrowserFocus : (() => void ) | undefined ;
2026-06-12 18:13:25 +08:00
beforeEach ( async () => {
await i18n . changeLanguage ( "en" );
2026-04-18 18:51:53 +00:00
mockSessions = [];
connectSpy . mockClear ();
2026-05-18 00:53:36 +08:00
updateUrlSpy . mockClear ();
2026-04-18 18:51:53 +00:00
refreshSpy . mockReset ();
createChatSpy . mockClear ();
deleteChatSpy . mockReset ();
2026-06-12 18:13:25 +08:00
getSessionAutomationsSpy . mockReset (). mockResolvedValue ([]);
2026-05-06 14:15:36 +00:00
toggleThemeSpy . mockReset ();
2026-05-19 22:42:38 +08:00
attachSpy . mockReset ();
2026-08-12 14:45:12 +08:00
setSidebarStateSpy . mockReset (). mockImplementation (
async ( state : SidebarStatePayload ) => state ,
);
2026-08-10 15:43:54 +08:00
requestMutationSpy . mockReset ();
2026-08-05 19:24:41 +08:00
discardTemporaryChatSpy . mockReset ();
2026-08-07 11:20:08 +08:00
let temporaryChatCounter = 0 ;
newTemporaryChatSpy . mockImplementation ( async () => (
`00000000-0000-4000-8000- ${ String ( ++ temporaryChatCounter ). padStart ( 12 , "0" ) } `
));
2026-08-06 18:29:04 +08:00
sendMessageSpy . mockReset ();
2026-10-12 11:36:42 +08:00
sendSystemCommandSpy . mockReset (). mockResolvedValue ( undefined );
mockDefaultChatId = null ;
2026-08-06 18:29:04 +08:00
statusHandlers . clear ();
2026-05-19 22:42:38 +08:00
runStatusHandlers . clear ();
2026-06-15 17:30:06 +08:00
sessionUpdateHandlers . clear ();
2026-08-12 14:45:12 +08:00
sidebarStateUpdateHandlers . clear ();
2026-06-02 11:29:18 +08:00
window . history . replaceState ( null , "" , "/" );
2026-09-30 15:09:14 +08:00
sessionStorage . removeItem ( "nanobot.remote-instance" );
2026-09-03 08:59:49 +08:00
Reflect . deleteProperty ( window , "nanobotHost" );
2026-06-04 13:54:52 +08:00
setNavigatorPlatform ( "Linux x86_64" );
2026-06-06 19:49:33 +08:00
localStorage . removeItem ( "nanobot-webui.sidebar" );
2026-09-10 11:10:51 +08:00
localStorage . removeItem ( "nanobot-webui.sidebar.width" );
2026-05-19 22:42:38 +08:00
localStorage . removeItem ( "nanobot-webui.sidebar.completed-runs.v1" );
2026-06-15 17:30:06 +08:00
localStorage . removeItem ( "nanobot-webui.sidebar.session-updates.v1" );
2026-08-12 14:45:12 +08:00
localStorage . removeItem ( "nanobot-webui.collapsed-pane-groups.v1" );
2026-07-13 13:11:46 +08:00
localStorage . removeItem ( "nanobot-webui.restartStartedAt" );
localStorage . removeItem ( "nanobot-webui.restartRoute" );
2026-05-18 00:53:36 +08:00
vi . mocked ( fetchBootstrap ). mockReset (). mockResolvedValue ({
token : "tok" ,
2026-07-08 14:27:52 +08:00
api_token : "api-tok" ,
2026-05-18 00:53:36 +08:00
ws_path : "/" ,
expires_in : 300 ,
});
vi . mocked ( deriveWsUrl ). mockReset (). mockReturnValue ( "ws://test" );
2026-10-05 05:16:33 +08:00
mockFetchRoutes ({});
2026-04-18 18:51:53 +00:00
});
2026-05-18 00:53:36 +08:00
afterEach (() => {
2026-08-09 21:37:06 +08:00
cleanup ();
2026-09-21 13:44:42 +08:00
restoreBrowserFocus ? .();
restoreBrowserFocus = undefined ;
2026-09-03 08:59:49 +08:00
Reflect . deleteProperty ( window , "nanobotHost" );
2026-05-18 00:53:36 +08:00
vi . useRealTimers ();
2026-08-12 14:45:12 +08:00
vi . unstubAllGlobals ();
2026-05-18 00:53:36 +08:00
});
2026-09-24 23:10:57 +08:00
it ( "shows only layout shadows while bootstrap is pending" , () => {
vi . mocked ( fetchBootstrap ). mockReturnValueOnce ( new Promise (() => {}));
render (< App />);
expect ( screen . getByRole ( "main" )). toHaveAttribute ( "aria-busy" , "true" );
expect ( screen . queryByRole ( "button" )). not . toBeInTheDocument ();
expect ( screen . queryByRole ( "link" )). not . toBeInTheDocument ();
expect ( screen . getByRole ( "status" )). toHaveClass ( "startup-status" );
expect ( screen . queryByText ( "Loading nanobot…" )). not . toBeInTheDocument ();
});
2026-10-05 05:16:33 +08:00
it . each ([ false , true ])( "enables task controls only when bootstrap advertises support: %s" , async ( supported ) => {
mockSessions = [{
key : "websocket:chat-a" , channel : "websocket" , chatId : "chat-a" ,
createdAt : null , updatedAt : null , title : "Inspection" , preview : "Inspect config" ,
}];
window . history . replaceState ( null , "" , "/#/chat/websocket%3Achat-a" );
vi . mocked ( fetchBootstrap ). mockResolvedValue ({
token : "tok" , api_token : "api-tok" , ws_path : "/" , expires_in : 300 ,
terminal : { webui : { capabilities : supported ? [ "webui.core.v1" , "webui.subagents.v1" ] : [ "webui.core.v1" ] } },
});
mockFetchRoutes ({
"/api/sessions/websocket%3Achat-a/subagents" : { tasks : [{
task_id : "task-1" , label : "Config check" , task_description : "Inspect configuration" ,
state : "running" , phase : "awaiting_model" , elapsed_seconds : 2 , iteration : 1 ,
tool_events : [], usage : null , receipts : {}, result : null , partial : false ,
stop_reason : null , error : null , origin_turn_id : null , origin_message_id : null ,
created_at : 100 , completed_at : null ,
}] },
});
render (< App />);
2026-10-08 15:10:20 +08:00
await screen . findByRole ( "textbox" , {}, { timeout : 5_000 });
2026-10-05 05:16:33 +08:00
if ( supported ) await screen . findByRole ( "button" , { name : /Config check Running/ });
else expect ( screen . queryByText ( "Config check" )). not . toBeInTheDocument ();
const reads = vi . mocked ( fetch ). mock . calls . filter (([ url ]) => String ( url ). endsWith ( "/subagents" ));
expect ( reads ). toHaveLength ( supported ? 1 : 0 );
expect ( requestMutationSpy ). not . toHaveBeenCalled ();
});
2026-06-22 10:57:55 +08:00
it ( "shows the auth form without an invalid-password error on first load" , async () => {
vi . mocked ( fetchBootstrap ). mockRejectedValueOnce (
new Error ( "bootstrap failed: HTTP 401" ),
);
render (< App />);
2026-09-13 05:01:13 +08:00
expect ( await screen . findByRole ( "heading" , { level : 1 , name : "Connect to nanobot" }))
2026-08-10 15:22:25 +08:00
. toBeInTheDocument ();
2026-09-13 05:01:13 +08:00
const password = screen . getByLabelText ( "WebUI password" );
2026-09-14 11:13:40 +08:00
expect ( password ). not . toHaveAttribute ( "aria-describedby" );
2026-08-10 15:22:25 +08:00
expect ( password ). toHaveAttribute (
"autocomplete" ,
"current-password" ,
);
expect ( password ). not . toHaveAttribute ( "placeholder" );
2026-09-14 11:13:40 +08:00
expect ( screen . queryByRole ( "alert" )). not . toBeInTheDocument ();
2026-06-22 10:57:55 +08:00
expect ( connectSpy ). not . toHaveBeenCalled ();
});
2026-07-08 15:46:52 +08:00
2026-09-14 11:13:40 +08:00
it ( "switches language before connecting while preserving the password draft" , async () => {
vi . mocked ( fetchBootstrap ). mockRejectedValueOnce (
new Error ( "bootstrap failed: HTTP 401" ),
);
const user = userEvent . setup ();
render (< App />);
await user . type ( await screen . findByLabelText ( "WebUI password" ), "draft-password" );
await user . tab ({ shift : true });
expect ( screen . getByRole ( "combobox" , { name : "Change language" })). toHaveFocus ();
await user . keyboard ( "{Enter}" );
await screen . findByRole ( "listbox" );
await user . keyboard ( "{ArrowDown}{Enter}" );
expect ( await screen . findByRole ( "heading" , { name : "连接到 nanobot" }))
. toBeInTheDocument ();
expect ( screen . getByLabelText ( "WebUI 密码" )). toHaveValue ( "draft-password" );
expect ( screen . getByRole ( "button" , { name : "连接" , exact : true })). toBeEnabled ();
expect ( document . documentElement . lang ). toBe ( "zh-CN" );
expect ( localStorage . getItem ( "nanobot.locale" )). toBe ( "zh-CN" );
expect ( fetchBootstrap ). toHaveBeenCalledTimes ( 1 );
expect ( connectSpy ). not . toHaveBeenCalled ();
});
it ( "reveals password setup help with the keyboard without submitting the form" , async () => {
vi . mocked ( fetchBootstrap ). mockRejectedValueOnce (
new Error ( "bootstrap failed: HTTP 401" ),
);
const user = userEvent . setup ();
render (< App />);
const password = await screen . findByLabelText ( "WebUI password" );
await user . type ( password , "draft-password" );
await user . tab ();
await user . tab ();
await user . tab ();
const help = screen . getByRole ( "button" , { name : "Where can I find the password?" });
expect ( help ). toHaveFocus ();
expect ( help ). toHaveAttribute ( "aria-expanded" , "false" );
const content = document . getElementById ( help . getAttribute ( "aria-controls" ) ! );
expect ( content ). toHaveAttribute ( "aria-hidden" , "true" );
await user . keyboard ( "{Enter}" );
expect ( help ). toHaveAttribute ( "aria-expanded" , "true" );
expect ( content ). not . toHaveAttribute ( "aria-hidden" );
expect ( content ). toHaveTextContent ( "~/.nanobot/config.json" );
expect ( content ). toHaveTextContent ( "channels.websocket.tokenIssueSecret" );
expect ( content ). toHaveTextContent ( "If that value is empty, use channels.websocket.token." );
await user . keyboard ( " " );
expect ( help ). toHaveAttribute ( "aria-expanded" , "false" );
expect ( password ). toHaveValue ( "draft-password" );
expect ( fetchBootstrap ). toHaveBeenCalledTimes ( 1 );
});
2026-08-10 15:22:25 +08:00
it ( "toggles password visibility without changing the password" , async () => {
vi . mocked ( fetchBootstrap ). mockRejectedValueOnce (
new Error ( "bootstrap failed: HTTP 401" ),
);
const user = userEvent . setup ();
render (< App />);
2026-09-13 05:01:13 +08:00
const password = await screen . findByLabelText ( "WebUI password" );
2026-08-10 15:22:25 +08:00
await user . type ( password , "correct horse battery staple" );
expect ( password ). toHaveAttribute ( "type" , "password" );
await user . click ( screen . getByRole ( "button" , { name : "Show password" }));
expect ( password ). toHaveAttribute ( "type" , "text" );
expect ( password ). toHaveValue ( "correct horse battery staple" );
const hidePassword = screen . getByRole ( "button" , { name : "Hide password" });
expect ( hidePassword ). toHaveFocus ();
await user . click ( hidePassword );
expect ( password ). toHaveAttribute ( "type" , "password" );
expect ( password ). toHaveValue ( "correct horse battery staple" );
expect ( screen . getByRole ( "button" , { name : "Show password" })). toHaveFocus ();
});
it ( "explains and focuses an empty auth password" , async () => {
vi . mocked ( fetchBootstrap ). mockRejectedValue (
new Error ( "bootstrap failed: HTTP 401" ),
);
render (< App />);
2026-09-13 05:01:13 +08:00
const password = await screen . findByLabelText ( "WebUI password" );
2026-08-10 15:22:25 +08:00
const connect = screen . getByRole ( "button" , { name : "Connect" });
expect ( connect ). toBeEnabled ();
fireEvent . click ( connect );
expect ( await screen . findByRole ( "alert" )). toHaveTextContent (
2026-09-14 11:13:40 +08:00
"Enter password" ,
2026-08-10 15:22:25 +08:00
);
2026-09-14 11:13:40 +08:00
expect ( password ). toHaveAttribute ( "placeholder" , "Enter password" );
2026-08-10 15:22:25 +08:00
expect ( password ). toHaveAttribute ( "aria-invalid" , "true" );
2026-09-13 05:01:13 +08:00
expect ( password ). toHaveAttribute (
"aria-describedby" ,
2026-09-14 11:13:40 +08:00
"webui-auth-error" ,
2026-09-13 05:01:13 +08:00
);
2026-08-10 15:22:25 +08:00
expect ( password ). toHaveFocus ();
2026-09-14 11:13:40 +08:00
fireEvent . change ( password , { target : { value : " " } });
fireEvent . click ( connect );
expect ( password ). toHaveValue ( "" );
expect ( password ). toHaveAttribute ( "placeholder" , "Enter password" );
2026-08-10 15:22:25 +08:00
expect ( fetchBootstrap ). toHaveBeenCalledTimes ( 1 );
});
2026-07-08 15:46:52 +08:00
it ( "shows the auth form when bootstrap does not issue an API token" , async () => {
vi . mocked ( fetchBootstrap ). mockRejectedValueOnce (
new BootstrapAuthRequiredError (
"bootstrap authentication required: missing api_token" ,
),
);
render (< App />);
2026-09-13 05:01:13 +08:00
expect ( await screen . findByRole ( "heading" , { level : 1 , name : "Connect to nanobot" }))
2026-08-10 15:22:25 +08:00
. toBeInTheDocument ();
2026-09-14 11:13:40 +08:00
expect ( screen . queryByRole ( "alert" )). not . toBeInTheDocument ();
2026-07-08 15:46:52 +08:00
expect ( connectSpy ). not . toHaveBeenCalled ();
});
2026-06-22 10:57:55 +08:00
it ( "shows an invalid-password error after a submitted password is rejected" , async () => {
vi . mocked ( fetchBootstrap ). mockRejectedValue (
new Error ( "bootstrap failed: HTTP 401" ),
);
render (< App />);
2026-09-13 05:01:13 +08:00
const password = await screen . findByLabelText ( "WebUI password" );
2026-06-22 10:57:55 +08:00
fireEvent . change ( password , { target : { value : "wrong-password" } });
fireEvent . click ( screen . getByRole ( "button" , { name : "Connect" }));
2026-09-13 05:01:13 +08:00
const retryPassword = await screen . findByLabelText ( "WebUI password" );
2026-08-10 15:22:25 +08:00
expect ( await screen . findByRole ( "alert" )). toHaveTextContent (
2026-09-14 11:13:40 +08:00
"Incorrect password" ,
2026-08-10 15:22:25 +08:00
);
2026-09-14 11:13:40 +08:00
expect ( retryPassword ). toHaveAttribute ( "placeholder" , "Incorrect password" );
expect ( retryPassword ). toHaveValue ( "" );
2026-08-10 15:22:25 +08:00
expect ( retryPassword ). toHaveAttribute ( "aria-invalid" , "true" );
expect ( retryPassword ). toHaveFocus ();
2026-06-22 10:57:55 +08:00
expect ( fetchBootstrap ). toHaveBeenLastCalledWith ( "" , "wrong-password" );
expect ( connectSpy ). not . toHaveBeenCalled ();
2026-09-14 11:13:40 +08:00
fireEvent . change ( retryPassword , { target : { value : "retry-password" } });
expect ( retryPassword ). not . toHaveAttribute ( "placeholder" );
expect ( retryPassword ). not . toHaveAttribute ( "aria-invalid" );
expect ( screen . queryByRole ( "alert" )). not . toBeInTheDocument ();
});
it ( "clears auth feedback after three seconds without moving focus" , async () => {
vi . mocked ( fetchBootstrap ). mockRejectedValue (
new Error ( "bootstrap failed: HTTP 401" ),
);
render (< App />);
const password = await screen . findByLabelText ( "WebUI password" );
vi . useFakeTimers ();
fireEvent . click ( screen . getByRole ( "button" , { name : "Connect" }));
expect ( password ). toHaveAttribute ( "placeholder" , "Enter password" );
act (() => vi . advanceTimersByTime ( 3 _000 ));
expect ( password ). not . toHaveAttribute ( "placeholder" );
expect ( password ). toHaveFocus ();
await act ( async () => {
fireEvent . change ( password , { target : { value : "wrong-password" } });
fireEvent . click ( screen . getByRole ( "button" , { name : "Connect" }));
});
const retryPassword = screen . getByLabelText ( "WebUI password" );
expect ( retryPassword ). toHaveAttribute ( "placeholder" , "Incorrect password" );
act (() => vi . advanceTimersByTime ( 2 _999 ));
expect ( retryPassword ). toHaveAttribute ( "placeholder" , "Incorrect password" );
act (() => vi . advanceTimersByTime ( 1 ));
expect ( retryPassword ). not . toHaveAttribute ( "placeholder" );
expect ( retryPassword ). not . toHaveAttribute ( "aria-invalid" );
expect ( screen . queryByRole ( "alert" )). not . toBeInTheDocument ();
expect ( retryPassword ). toHaveFocus ();
2026-06-22 10:57:55 +08:00
});
2026-04-18 18:51:53 +00:00
it ( "keeps sidebar layout out of the main thread width contract" , async () => {
const { container } = render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const main = container . querySelector ( "main" );
expect ( main ). toBeInTheDocument ();
expect ( main ). not . toHaveAttribute ( "style" );
2026-09-03 00:01:39 +08:00
expect ( screen . getByTestId ( "sidebar-brand-row" )). toHaveClass ( "pt-3" );
expect ( screen . getByTestId ( "sidebar-brand-mark" )). not . toHaveClass ( "mt-5" );
2026-09-10 11:10:51 +08:00
expect ( screen . getByRole ( "separator" , { name : "Resize sidebar" })). toHaveAttribute ( "aria-valuenow" , "272" );
2026-04-18 18:51:53 +00:00
const asideClassNames = Array . from ( container . querySelectorAll ( "aside" )). map (
( el ) => el . className ,
);
expect ( asideClassNames . some (( cls ) => cls . includes ( "lg:block" ))). toBe ( true );
});
2026-08-10 15:22:25 +08:00
it ( "uses one main landmark and a page heading in desktop settings" , async () => {
mockFetchRoutes ({ "/api/settings" : baseSettingsPayload () });
const { container } = render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Settings" }));
2026-08-11 13:51:15 +08:00
await act ( async () => {
await import ( "@/components/settings/SettingsView" );
});
2026-08-10 15:22:25 +08:00
expect (
2026-08-11 13:51:15 +08:00
screen . getByRole ( "navigation" , { name : "Settings sections" }),
2026-08-10 15:22:25 +08:00
). toBeInTheDocument ();
2026-09-03 10:23:38 +08:00
const backButton = screen . getByRole ( "button" , { name : "Back to chat" });
expect ( backButton . closest ( "aside" )). toHaveClass ( "pt-4" , "lg:pt-4" );
expect ( backButton ). not . toHaveClass ( "-ml-1" );
2026-08-10 15:22:25 +08:00
expect ( container . querySelectorAll ( "main" )). toHaveLength ( 1 );
2026-09-10 11:10:51 +08:00
expect ( screen . getByRole ( "navigation" , { name : "Settings sections" })). toBeInTheDocument ();
2026-08-10 15:22:25 +08:00
});
2026-09-02 04:19:12 +08:00
it ( "opens the full Models settings directly from the first-run prompt" , async () => {
2026-09-02 01:02:26 +08:00
const user = userEvent . setup ();
const base = baseSettingsPayload ();
mockFetchRoutes ({
"/api/settings" : {
... base ,
agent : {
... base . agent ,
model : "" ,
resolved_provider : "" ,
has_api_key : false ,
model_preset : "" ,
},
model_presets : [],
model_call_order : [],
},
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
2026-10-09 17:47:21 +08:00
await user . click ( await screen . findByRole ( "button" , { name : "Choose model" }));
2026-09-02 01:02:26 +08:00
expect (
await screen . findByRole ( "navigation" , { name : "Settings sections" }),
). toBeInTheDocument ();
2026-10-11 04:30:43 +08:00
expect ( screen . getByRole ( "heading" , { name : "Model presets" })). toBeInTheDocument ();
await user . click ( screen . getByRole ( "button" , { name : "Manage providers" }));
expect ( screen . getByRole ( "dialog" , { name : "Manage providers" })). toBeInTheDocument ();
expect ( screen . getByRole ( "button" , { name : "Add provider" })). toBeInTheDocument ();
2026-10-09 17:47:21 +08:00
expect ( screen . queryByRole ( "dialog" , { name : "Choose model" })). not . toBeInTheDocument ();
2026-09-02 01:02:26 +08:00
});
2026-06-15 18:12:54 +08:00
it ( "places Automations after Skills in the main sidebar" , async () => {
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
const appsButton = within ( sidebar ). getByRole ( "button" , { name : "Apps" });
const skillsButton = within ( sidebar ). getByRole ( "button" , { name : "Skills" });
const automationsButton = within ( sidebar ). getByRole ( "button" , { name : "Automations" });
expect ( appsButton . compareDocumentPosition ( skillsButton ) & Node . DOCUMENT_POSITION_FOLLOWING )
. toBeTruthy ();
expect (
skillsButton . compareDocumentPosition ( automationsButton ) &
Node . DOCUMENT_POSITION_FOLLOWING ,
). toBeTruthy ();
});
2026-09-10 11:10:51 +08:00
it ( "opens Channels below Automations and supports its keyboard shortcut" , async () => {
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/settings/nanobot-features" : { features : [], enabled_count : 0 },
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
const channels = within ( sidebar ). getByRole ( "button" , { name : "Channels" });
expect ( within ( sidebar ). getByRole ( "button" , { name : "Automations" })
. compareDocumentPosition ( channels ) & Node . DOCUMENT_POSITION_FOLLOWING ). toBeTruthy ();
fireEvent . click ( channels );
expect ( await screen . findByRole ( "heading" , { name : "Channels" })). toBeVisible ();
expect ( window . location . hash ). toBe ( "#/channels" );
expect ( channels ). toHaveAttribute ( "aria-current" , "page" );
2026-10-07 15:19:55 +08:00
expect ( document . title ). toBe ( "Channels" );
2026-09-10 11:10:51 +08:00
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "New topic" }));
await waitFor (() => expect ( window . location . hash ). toBe ( "#/new" ));
fireEvent . keyDown ( window , { key : "$" , code : "Digit4" , ctrlKey : true , shiftKey : true });
expect ( await screen . findByRole ( "heading" , { name : "Channels" })). toBeVisible ();
expect ( window . location . hash ). toBe ( "#/channels" );
});
2026-09-30 23:30:25 +08:00
it ( "opens management in the main content area while keeping the standalone deep link" , async () => {
2026-09-27 20:51:49 +08:00
requestMutationSpy . mockResolvedValue ({ hosts : [], files : [], incomplete : false });
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/remote-instances" : { available : true , profiles : [] },
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
2026-09-30 23:09:23 +08:00
const originalHash = window . location . hash ;
const originalTitle = document . title ;
2026-09-30 15:09:14 +08:00
expect ( within ( sidebar ). queryByRole ( "button" , { name : "Remote connections" })). not . toBeInTheDocument ();
fireEvent . pointerDown ( await within ( sidebar ). findByRole ( "button" , { name : "Switch host" }), { button : 0 , ctrlKey : false });
2026-10-09 17:47:21 +08:00
fireEvent . click ( await screen . findByRole ( "menuitem" , { name : "Manage connections" }));
2026-09-30 15:09:14 +08:00
expect ( await screen . findByRole ( "heading" , { name : "Remote connections" })). toBeVisible ();
2026-09-30 23:30:25 +08:00
expect ( screen . getByRole ( "main" )). toContainElement ( screen . getByRole ( "region" , { name : "Remote connections" }));
expect ( screen . queryByRole ( "dialog" )). not . toBeInTheDocument ();
2026-09-27 20:51:49 +08:00
expect ( sidebar ). toBeVisible ();
2026-09-30 21:44:18 +08:00
fireEvent . click ( await screen . findByRole ( "button" , { name : "Connect to remote nanobot" }));
2026-09-30 15:09:14 +08:00
fireEvent . pointerDown ( screen . getByRole ( "button" , { name : "Other ways" }), { button : 0 , ctrlKey : false });
2026-10-09 17:47:21 +08:00
fireEvent . click ( screen . getByRole ( "menuitem" , { name : "SSH connection" }));
2026-09-30 15:09:14 +08:00
const host = await screen . findByRole ( "textbox" , { name : "SSH address" });
2026-10-09 17:47:21 +08:00
expect ( screen . getByRole ( "dialog" , { name : "Add connection" })). toContainElement ( host );
2026-09-30 23:09:23 +08:00
expect ( window . location . hash ). toBe ( originalHash );
expect ( document . title ). toBe ( originalTitle );
2026-09-30 15:09:14 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : "Cancel" }));
2026-09-30 23:30:25 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : "Back" , exact : true }));
2026-09-27 20:51:49 +08:00
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "New topic" }));
expect ( window . location . hash ). toBe ( "#/new" );
expect ( screen . queryByRole ( "textbox" , { name : "SSH address" })). not . toBeInTheDocument ();
act (() => {
window . history . replaceState ( null , "" , "#/remote" );
window . dispatchEvent ( new PopStateEvent ( "popstate" ));
});
2026-09-30 21:44:18 +08:00
expect ( await screen . findByRole ( "button" , { name : "Connect to remote nanobot" })). toBeVisible ();
2026-09-30 15:09:14 +08:00
expect ( screen . queryByRole ( "dialog" )). not . toBeInTheDocument ();
expect ( within ( sidebar ). queryByRole ( "button" , { name : "Remote connections" })). not . toBeInTheDocument ();
});
2026-09-30 23:30:25 +08:00
it ( "lets sidebar navigation leave the management page without a second dismissal" , async () => {
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/remote-instances" : { available : true , profiles : [] },
});
render (< App />);
const sidebar = await screen . findByRole ( "navigation" , { name : "Sidebar navigation" });
fireEvent . pointerDown ( await within ( sidebar ). findByRole ( "button" , { name : "Switch host" }), { button : 0 , ctrlKey : false });
2026-10-09 17:47:21 +08:00
fireEvent . click ( await screen . findByRole ( "menuitem" , { name : "Manage connections" }));
2026-09-30 23:30:25 +08:00
expect ( await screen . findByRole ( "region" , { name : "Remote connections" })). toBeVisible ();
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Apps" }));
expect ( await screen . findByRole ( "heading" , { name : "Apps" })). toBeVisible ();
expect ( screen . queryByRole ( "region" , { name : "Remote connections" })). not . toBeInTheDocument ();
expect ( window . location . hash ). toBe ( "#/apps" );
});
2026-09-30 15:09:14 +08:00
it ( "closes the mobile sidebar when managing connections from its host menu" , async () => {
const user = userEvent . setup ();
requestMutationSpy . mockResolvedValue ({ hosts : [], files : [], incomplete : false });
vi . stubGlobal ( "matchMedia" , vi . fn (). mockImplementation (( query : string ) => ({
matches : ! query . includes ( "1024px" ), media : query , onchange : null ,
addListener : vi.fn (), removeListener : vi.fn (), addEventListener : vi.fn (),
removeEventListener : vi.fn (), dispatchEvent : vi.fn (),
})));
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/remote-instances" : { available : true , profiles : [] },
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
await user . click ( await screen . findByRole ( "button" , { name : "Toggle sidebar" }));
const sheet = await screen . findByRole ( "dialog" );
fireEvent . pointerDown ( await within ( sheet ). findByRole ( "button" , { name : "Switch host" }), { button : 0 , ctrlKey : false });
2026-10-09 17:47:21 +08:00
fireEvent . click ( await screen . findByRole ( "menuitem" , { name : "Manage connections" }));
2026-09-30 23:09:23 +08:00
await waitFor (() => expect ( sheet ). not . toBeInTheDocument ());
2026-09-30 23:30:25 +08:00
expect ( screen . getByRole ( "main" )). toContainElement ( screen . getByRole ( "region" , { name : "Remote connections" }));
expect ( screen . queryByRole ( "dialog" )). not . toBeInTheDocument ();
2026-09-30 15:09:14 +08:00
expect ( await screen . findByRole ( "heading" , { name : "Remote connections" })). toBeVisible ();
2026-09-30 23:09:23 +08:00
expect ( window . location . hash ). not . toBe ( "#/remote" );
2026-09-30 15:09:14 +08:00
expect ( screen . queryByRole ( "button" , { name : "Remote connections" })). not . toBeInTheDocument ();
2026-09-30 21:44:18 +08:00
await user . click ( screen . getByRole ( "button" , { name : "Connect to remote nanobot" }));
expect ( await screen . findByRole ( "dialog" , { name : "Connect to remote nanobot" })). toBeVisible ();
2026-09-30 15:09:14 +08:00
});
it ( "releases the mobile sidebar modal when switching to a server" , async () => {
const user = userEvent . setup ();
vi . stubGlobal ( "matchMedia" , vi . fn (). mockImplementation (( query : string ) => ({
matches : ! query . includes ( "1024px" ), media : query , onchange : null ,
addListener : vi.fn (), removeListener : vi.fn (), addEventListener : vi.fn (),
removeEventListener : vi.fn (), dispatchEvent : vi.fn (),
})));
const profile = { id : "3b968d52-081d-4898-9970-ff0a1fc93817" , name : "Team server" ,
host : "team" , port : null , ssh_config : "" , identity_file : "" ,
config_path : "~/.nanobot/config.json" , runtime_user : "" , connected : false };
requestMutationSpy . mockResolvedValue ({ ... profile , hostname : "team-host" , gateway_id : "remote-gateway" ,
url : "http://127.0.0.1:23456/#/?bootstrapSecret=test-only" });
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/remote-instances" : { available : true , profiles : [ profile ] },
});
render (< App />);
await user . click ( await screen . findByRole ( "button" , { name : "Toggle sidebar" }));
const sheet = await screen . findByRole ( "dialog" );
await user . click ( await within ( sheet ). findByRole ( "button" , { name : "Switch host" }));
await user . click ( await screen . findByRole ( "menuitem" , { name : "Team server team" }));
const frame = await screen . findByTitle ( "nanobot on Team server" );
fireEvent . load ( frame );
await waitFor (() => expect ( screen . queryByRole ( "dialog" )). not . toBeInTheDocument ());
await waitFor (() => expect ( document . body . style . pointerEvents ). not . toBe ( "none" ));
expect ( frame ). toBeVisible ();
2026-09-27 20:51:49 +08:00
});
it ( "opens a remote setup deep link after reloading without opening Settings" , async () => {
requestMutationSpy . mockResolvedValue ({ hosts : [], files : [], incomplete : false });
window . history . replaceState ( null , "" , "#/remote" );
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/remote-instances" : { available : true , profiles : [] },
});
render (< App />);
2026-09-30 21:44:18 +08:00
expect ( await screen . findByRole ( "button" , { name : "Connect to remote nanobot" })). toBeVisible ();
2026-09-30 15:09:14 +08:00
expect ( screen . queryByRole ( "dialog" )). not . toBeInTheDocument ();
2026-09-27 20:51:49 +08:00
expect ( screen . getByRole ( "navigation" , { name : "Sidebar navigation" })). toBeVisible ();
expect ( screen . queryByRole ( "navigation" , { name : "Settings sections" })). not . toBeInTheDocument ();
expect ( window . location . hash ). toBe ( "#/remote" );
});
2026-08-01 22:36:23 +08:00
it ( "highlights the blank new-topic destination immediately" , async () => {
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
const newTopicButton = within ( sidebar ). getByRole ( "button" , { name : "New topic" });
expect ( newTopicButton ). toHaveAttribute ( "aria-current" , "page" );
2026-10-06 00:46:38 +08:00
expect ( newTopicButton ). toHaveClass ( "transition-[width,padding,color,background-color]" );
2026-09-10 11:10:51 +08:00
expect ( newTopicButton ). toBeEnabled ();
2026-08-01 22:36:23 +08:00
});
2026-08-07 14:56:23 +08:00
it ( "keeps a just-created topic route while the session list catches up" , async () => {
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
2026-08-12 14:45:12 +08:00
const firstMessage = "keep this first turn visible" ;
2026-08-18 18:28:19 +08:00
fireEvent . change ( screen . getByRole ( "textbox" , { name : "Message input" }), {
2026-08-12 14:45:12 +08:00
target : { value : firstMessage },
2026-08-07 14:56:23 +08:00
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( createChatSpy ). toHaveBeenCalledTimes ( 1 ));
await waitFor (() =>
expect ( window . location . hash ). toBe (
`#/chat/ ${ encodeURIComponent ( "websocket:chat-1" ) } ` ,
),
);
2026-08-12 14:45:12 +08:00
expect ( await screen . findByText ( firstMessage )). toBeInTheDocument ();
2026-08-07 14:56:23 +08:00
});
2026-08-06 18:29:04 +08:00
it ( "creates a new temporary chat from the hero each time" , async () => {
2026-08-05 19:24:41 +08:00
const { unmount } = render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
2026-08-06 18:29:04 +08:00
expect ( within ( sidebar ). queryByRole ( "button" , { name : "Temporary chat" })). not . toBeInTheDocument ();
const firstToggle = screen . getByRole ( "button" , { name : "Temporary chat" });
expect ( firstToggle ). toHaveAttribute ( "aria-pressed" , "false" );
fireEvent . click ( firstToggle );
expect ( firstToggle ). toHaveAttribute ( "aria-pressed" , "true" );
expect ( window . location . hash ). toBe ( "" );
2026-08-05 19:24:41 +08:00
2026-08-06 18:29:04 +08:00
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "first private message" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
2026-08-05 19:24:41 +08:00
2026-08-07 11:20:08 +08:00
await waitFor (() => expect ( window . location . hash ). toMatch ( /^#\/temporary\/[0-9a-f-]+$/ ));
2026-08-06 18:29:04 +08:00
const firstHash = window . location . hash ;
2026-08-07 11:20:08 +08:00
expect ( firstHash ). toMatch ( /^#\/temporary\/[0-9a-f-]+$/ );
2026-08-06 18:29:04 +08:00
expect ( screen . queryByRole ( "button" , { name : "Temporary chat" })). not . toBeInTheDocument ();
expect ( createChatSpy ). not . toHaveBeenCalled ();
2026-08-05 19:24:41 +08:00
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "New topic" }));
expect ( discardTemporaryChatSpy ). not . toHaveBeenCalled ();
2026-08-06 18:29:04 +08:00
const secondToggle = screen . getByRole ( "button" , { name : "Temporary chat" });
expect ( secondToggle ). toHaveAttribute ( "aria-pressed" , "false" );
2026-08-05 19:24:41 +08:00
2026-08-06 18:29:04 +08:00
fireEvent . click ( secondToggle );
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "second private message" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
2026-08-07 11:20:08 +08:00
await waitFor (() => expect ( window . location . hash ). toMatch ( /^#\/temporary\/[0-9a-f-]+$/ ));
2026-08-06 18:29:04 +08:00
const secondHash = window . location . hash ;
2026-08-07 11:20:08 +08:00
expect ( secondHash ). toMatch ( /^#\/temporary\/[0-9a-f-]+$/ );
2026-08-06 18:29:04 +08:00
expect ( secondHash ). not . toBe ( firstHash );
expect ( screen . queryByRole ( "button" , { name : "Temporary chat" })). not . toBeInTheDocument ();
expect ( discardTemporaryChatSpy ). not . toHaveBeenCalled ();
expect ( within ( sidebar ). getByText ( "Temporary chats" )). toBeInTheDocument ();
expect ( within ( sidebar ). getByRole ( "button" , {
name : "first private message" ,
})). toBeInTheDocument ();
expect ( within ( sidebar ). getByRole ( "button" , {
name : "second private message" ,
})). toBeInTheDocument ();
fireEvent . click ( within ( sidebar ). getByRole ( "button" , {
name : "first private message" ,
}));
await waitFor (() => expect ( window . location . hash ). toBe ( firstHash ));
2026-08-07 13:27:53 +08:00
expect ( within ( screen . getByTestId ( "thread-header" )). getByText (
"first private message" ,
)). toBeInTheDocument ();
2026-10-07 15:19:55 +08:00
await waitFor (() => expect ( document . title ). toBe ( "first private message" ));
2026-08-06 18:29:04 +08:00
expect ( screen . queryByRole ( "button" , { name : "Temporary chat" })). not . toBeInTheDocument ();
2026-08-07 13:24:40 +08:00
fireEvent . click ( within ( sidebar ). getByRole ( "button" , {
name : "Close temporary chat: first private message" ,
}));
2026-08-06 18:29:04 +08:00
await waitFor (() => expect ( window . location . hash ). toBe ( secondHash ));
expect ( within ( sidebar ). queryByRole ( "button" , {
name : "first private message" ,
})). not . toBeInTheDocument ();
expect ( within ( sidebar ). getByRole ( "button" , {
name : "second private message" ,
})). toBeInTheDocument ();
expect ( discardTemporaryChatSpy ). toHaveBeenCalledTimes ( 1 );
2026-08-05 19:24:41 +08:00
unmount ();
2026-08-06 18:29:04 +08:00
await waitFor (() => expect ( discardTemporaryChatSpy ). toHaveBeenCalledTimes ( 2 ));
const discardedChatIds = discardTemporaryChatSpy . mock . calls . map (([ chatId ]) => chatId );
expect ( new Set ( discardedChatIds ). size ). toBe ( 2 );
expect ( discardedChatIds ). toEqual ([
2026-08-07 11:20:08 +08:00
"00000000-0000-4000-8000-000000000001" ,
"00000000-0000-4000-8000-000000000002" ,
2026-08-06 18:29:04 +08:00
]);
2026-08-05 19:24:41 +08:00
});
2026-08-06 18:29:04 +08:00
it ( "shows the temporary-chat control only on the new-topic hero" , async () => {
mockSessions = [{
key : "websocket:existing-chat" ,
channel : "websocket" ,
chatId : "existing-chat" ,
createdAt : "2026-08-06T10:00:00Z" ,
updatedAt : "2026-08-06T10:00:00Z" ,
preview : "Existing topic" ,
}];
2026-08-05 19:24:41 +08:00
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
2026-08-06 18:29:04 +08:00
const heroHeader = screen . getByTestId ( "thread-header" );
const heroTemporaryToggle = within ( heroHeader ). getByRole ( "button" , {
name : "Temporary chat" ,
});
const themeToggle = within ( heroHeader ). getByRole ( "button" , {
name : "Toggle theme from header" ,
});
expect ( within ( sidebar ). queryByRole ( "button" , { name : "Temporary chat" })). not . toBeInTheDocument ();
expect ( within ( screen . getByTestId ( "thread-composer-motion" )). queryByRole ( "button" , {
name : "Temporary chat" ,
})). not . toBeInTheDocument ();
expect ( heroTemporaryToggle . compareDocumentPosition ( themeToggle )
& Node . DOCUMENT_POSITION_FOLLOWING ). toBeTruthy ();
2026-08-05 19:24:41 +08:00
2026-08-08 23:43:42 +09:00
const user = userEvent . setup ();
await user . hover ( heroTemporaryToggle );
const temporaryTooltip = await screen . findByRole ( "tooltip" );
expect ( temporaryTooltip ). toHaveTextContent ( "Temporary chat" );
expect ( temporaryTooltip ). toHaveTextContent ( "Not saved to history or memory" );
2026-08-08 23:56:55 +09:00
expect ( within ( temporaryTooltip ). getByText (
2026-10-09 17:47:21 +08:00
"Ends on reload, close, or disconnection." ,
2026-08-08 23:56:55 +09:00
)). toHaveClass ( "font-medium" );
2026-08-08 23:43:42 +09:00
await user . unhover ( heroTemporaryToggle );
2026-08-06 18:29:04 +08:00
fireEvent . click ( within ( sidebar ). getByText ( "Existing topic" ));
expect ( window . location . hash ). toBe ( "#/chat/websocket%3Aexisting-chat" );
expect ( screen . queryByRole ( "button" , { name : "Temporary chat" })). not . toBeInTheDocument ();
2026-08-05 19:24:41 +08:00
2026-08-06 18:29:04 +08:00
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "New topic" }));
const temporaryToggle = screen . getByRole ( "button" , { name : "Temporary chat" });
2026-10-11 04:30:43 +08:00
expect ( temporaryToggle ). toHaveClass ( "h-8" , "w-8" , "rounded-control" );
2026-08-06 18:29:04 +08:00
expect ( within ( temporaryToggle ). queryByText ( "Temporary chat" )). not . toBeInTheDocument ();
fireEvent . click ( temporaryToggle );
expect ( temporaryToggle ). toHaveAttribute ( "aria-pressed" , "true" );
2026-10-06 00:46:38 +08:00
expect ( temporaryToggle ). toHaveClass ( "icon-action" );
2026-08-06 18:29:04 +08:00
expect ( within ( temporaryToggle ). getByTestId ( "temporary-chat-icon" )). toHaveClass (
"motion-safe:duration-150" ,
"text-[var(--temporary-control-active)]" ,
2026-08-05 19:24:41 +08:00
);
2026-08-06 18:29:04 +08:00
expect ( screen . queryByRole ( "tooltip" )). not . toBeInTheDocument ();
expect ( screen . queryByTestId ( "temporary-chat-outline" )). not . toBeInTheDocument ();
fireEvent . click ( temporaryToggle );
expect ( temporaryToggle ). toHaveAttribute ( "aria-pressed" , "false" );
expect ( within ( temporaryToggle ). getByTestId ( "temporary-chat-icon" )). toHaveClass (
"motion-safe:duration-75" ,
"text-current" ,
);
fireEvent . click ( temporaryToggle );
expect ( window . location . hash ). toBe ( "#/new" );
expect ( temporaryToggle ). toHaveAttribute ( "aria-pressed" , "true" );
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "start temporary chat" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
2026-08-07 11:20:08 +08:00
await waitFor (() => expect ( window . location . hash ). toMatch ( /^#\/temporary\/[0-9a-f-]+$/ ));
2026-08-06 18:29:04 +08:00
expect ( screen . queryByText ( "Not saved" )). not . toBeInTheDocument ();
2026-10-09 17:47:21 +08:00
expect ( screen . queryByRole ( "button" , { name : "Clear chat" })). not . toBeInTheDocument ();
2026-08-06 18:29:04 +08:00
expect ( screen . queryByRole ( "button" , { name : "Temporary chat" })). not . toBeInTheDocument ();
2026-08-05 19:24:41 +08:00
});
2026-08-06 18:29:04 +08:00
it ( "allows leaving a page with temporary chats without blocking" , async () => {
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
fireEvent . click ( screen . getByRole ( "button" , { name : "Temporary chat" }));
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "do not lose this" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
2026-08-07 11:20:08 +08:00
await waitFor (() => expect ( window . location . hash ). toMatch ( /^#\/temporary\/[0-9a-f-]+$/ ));
2026-08-06 18:29:04 +08:00
const beforeUnload = new Event ( "beforeunload" , { cancelable : true });
act (() => window . dispatchEvent ( beforeUnload ));
expect ( beforeUnload . defaultPrevented ). toBe ( false );
});
it ( "ends temporary chats quietly after a connection interruption" , async () => {
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
act (() => {
statusHandlers . forEach (( handler ) => handler ( "open" ));
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Temporary chat" }));
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "connection-sensitive message" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
2026-08-07 11:20:08 +08:00
await waitFor (() => expect ( window . location . hash ). toMatch ( /^#\/temporary\/[0-9a-f-]+$/ ));
2026-08-06 18:29:04 +08:00
act (() => {
statusHandlers . forEach (( handler ) => handler ( "reconnecting" ));
});
await waitFor (() => expect ( window . location . hash ). toBe ( "#/new" ));
expect ( screen . queryByRole ( "alert" )). not . toBeInTheDocument ();
expect ( screen . queryByText ( "connection-sensitive message" )). not . toBeInTheDocument ();
});
2026-09-09 14:40:35 +08:00
it ( "keeps the context-menu project through navigation and first-message creation" , async () => {
const projectScope = {
project_path : "/tmp/selected-project" ,
project_name : "selected-project" ,
access_mode : "full" as const ,
restrict_to_workspace : false ,
};
mockSessions = [{
key : "websocket:existing-chat" ,
channel : "websocket" ,
chatId : "existing-chat" ,
preview : "Existing topic" ,
workspaceScope : projectScope ,
}];
mockFetchRoutes ({
"/api/workspaces" : {
schema_version : 1 ,
default_access_mode : "full" ,
default_scope : { ... projectScope , project_path : "/tmp/workspace" , project_name : "workspace" },
2026-10-12 15:39:33 +08:00
controls : { can_change_project : true },
2026-09-09 14:40:35 +08:00
},
});
window . history . replaceState ( null , "" , "/#/chat/websocket%3Aexisting-chat" );
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const projectSection = screen . getByRole ( "region" , { name : "selected-project" });
fireEvent . contextMenu ( within ( projectSection ). getByRole ( "button" , { name : "selected-project" }));
fireEvent . click ( await screen . findByRole ( "menuitem" , { name : "New topic" }));
expect ( window . location . hash ). toBe ( "#/new" );
// Let queued browser navigation events settle before sending the first message.
await act ( async () => { await new Promise (( resolve ) => setTimeout ( resolve , 50 )); });
2026-10-09 17:47:21 +08:00
expect ( await screen . findByRole ( "button" , { name : "Switch directory" })). toHaveTextContent ( "selected-project" );
2026-09-09 14:40:35 +08:00
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "project topic" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( createChatSpy ). toHaveBeenCalledWith ( projectScope ));
});
2026-08-06 18:29:04 +08:00
it ( "uses the restricted default scope without offering project selection" , async () => {
2026-08-05 19:24:41 +08:00
mockFetchRoutes ({
"/api/workspaces" : {
schema_version : 1 ,
default_access_mode : "full" ,
default_scope : {
project_path : "/tmp/workspace" ,
project_name : "workspace" ,
access_mode : "full" ,
restrict_to_workspace : false ,
},
2026-10-12 15:39:33 +08:00
controls : { can_change_project : true },
2026-08-05 19:24:41 +08:00
},
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
2026-10-09 17:47:21 +08:00
expect ( await screen . findByRole ( "button" , { name : "Switch directory" })). toBeInTheDocument ();
2026-08-06 18:29:04 +08:00
act (() => {
sessionUpdateHandlers . forEach (( handler ) => handler ( "selected-chat" , "metadata" , {
project_path : "/tmp/selected-project" ,
project_name : "selected-project" ,
access_mode : "full" ,
restrict_to_workspace : false ,
}));
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Temporary chat" }));
2026-10-09 17:47:21 +08:00
expect ( screen . queryByRole ( "button" , { name : "Switch directory" })). not . toBeInTheDocument ();
2026-08-05 19:24:41 +08:00
expect ( screen . queryByText ( "Full Access" )). not . toBeInTheDocument ();
2026-08-06 18:29:04 +08:00
fireEvent . change ( screen . getByLabelText ( "Message input" ), {
target : { value : "temporary project check" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( sendMessageSpy ). toHaveBeenCalled ());
const options = sendMessageSpy . mock . calls . at ( - 1 ) ? .[ 3 ];
expect ( options ? . workspaceScope ). toMatchObject ({
project_path : "/tmp/workspace" ,
access_mode : "restricted" ,
restrict_to_workspace : true ,
});
2026-08-05 19:24:41 +08:00
});
2026-08-10 15:22:25 +08:00
it ( "preserves the first message when the gateway rejects a project" , async () => {
const consoleError = vi . spyOn ( console , "error" ). mockImplementation (() => {});
2026-10-07 17:51:37 +08:00
const projectPath = "C:\\missing-project" ;
const directory = ( path : string ) => ({
path , parent : null , entries : [], partial : false ,
truncated : false , host : "test-host" , platform : "Windows" ,
});
const directoryUrl = ( path : string ) => `/api/workspaces/directories? ${ new URLSearchParams ({ path , q : "" , hidden : "0" , partial : "1" } )}` ;
requestMutationSpy . mockResolvedValue ({ path : projectPath , name : "missing-project" });
2026-08-10 15:22:25 +08:00
createChatSpy . mockRejectedValueOnce (
new Error ( "workspace_scope_rejected:project_path must be an existing directory" ),
);
mockFetchRoutes ({
"/api/workspaces" : {
schema_version : 1 ,
2026-10-07 17:51:37 +08:00
default_access_mode : "default" ,
2026-08-10 15:22:25 +08:00
default_scope : {
project_path : "C:\\workspace" ,
project_name : "workspace" ,
access_mode : "restricted" ,
restrict_to_workspace : true ,
},
2026-10-12 15:39:33 +08:00
controls : { can_change_project : true , can_browse_directories : true , can_resolve_project : true },
2026-08-10 15:22:25 +08:00
},
2026-10-08 10:16:28 +08:00
[ directoryUrl ( "C:\\workspace" )] : directory ( "C:\\workspace" ),
2026-10-07 17:51:37 +08:00
[ directoryUrl ( "C:\\workspace\\" )] : directory ( "C:\\workspace" ),
[ directoryUrl ( projectPath )] : directory ( projectPath ),
[ directoryUrl ( ` ${ projectPath } \\` )] : directory ( projectPath ),
2026-08-10 15:22:25 +08:00
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
2026-10-09 17:47:21 +08:00
fireEvent . click ( await screen . findByRole ( "button" , { name : "Switch directory" }));
2026-10-08 15:10:20 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : /^Edit path:/ }));
2026-10-07 17:51:37 +08:00
fireEvent . change ( await screen . findByRole ( "combobox" ), {
target : { value : projectPath },
2026-08-10 15:22:25 +08:00
});
2026-10-08 15:10:20 +08:00
await waitFor (() => expect ( screen . getByRole ( "button" , { name : "Confirm" })). toBeEnabled ());
fireEvent . click ( screen . getByRole ( "button" , { name : "Confirm" }));
2026-10-07 17:51:37 +08:00
await waitFor (() => expect ( screen . queryByRole ( "dialog" )). not . toBeInTheDocument ());
2026-08-10 15:22:25 +08:00
const message = screen . getByLabelText ( "Message input" );
fireEvent . change ( message , { target : { value : "keep this first message" } });
fireEvent . click ( screen . getByRole ( "button" , { name : "Send message" }));
await waitFor (() => expect ( createChatSpy ). toHaveBeenCalledTimes ( 1 ));
expect ( message ). toHaveValue ( "keep this first message" );
2026-10-09 17:47:21 +08:00
const projectButton = screen . getByRole ( "button" , { name : "Switch directory" });
2026-08-10 15:22:25 +08:00
await waitFor (() => expect ( projectButton ). toHaveFocus ());
expect ( screen . getByRole ( "alert" )). toHaveTextContent (
"The gateway rejected this project or access mode. Choose an existing project or a different access mode, then try again." ,
);
fireEvent . click ( projectButton );
2026-10-08 15:10:20 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : /^Edit path:/ }));
2026-10-07 17:51:37 +08:00
const pathInput = await screen . findByRole ( "combobox" );
expect ( pathInput ). toHaveValue ( ` ${ projectPath } \\` );
expect ( pathInput ). toHaveAttribute ( "aria-invalid" , "true" );
expect ( pathInput ). toHaveFocus ();
2026-08-10 15:22:25 +08:00
expect ( screen . getByRole ( "alert" )). toHaveTextContent (
"The gateway rejected this project or access mode. Choose an existing project or a different access mode, then try again." ,
);
expect ( window . location . hash ). toBe ( "" );
consoleError . mockRestore ();
});
2026-09-10 11:10:51 +08:00
it ( "restores the standalone Channels page from a legacy restart route" , async () => {
2026-07-13 13:11:46 +08:00
localStorage . setItem ( "nanobot-webui.restartStartedAt" , String ( Date . now ()));
localStorage . setItem ( "nanobot-webui.restartRoute" , "#/settings?section=channels" );
window . history . replaceState ( null , "" , "/#/new" );
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/settings/nanobot-features" : {
features : [{
name : "websocket" ,
display_name : "Websocket" ,
type : "channel" ,
enabled : true ,
installed : true ,
ready : true ,
status : "enabled" ,
install_supported : true ,
requires_restart : true ,
}],
enabled_count : 1 ,
},
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
2026-07-24 00:55:06 +08:00
expect (
2026-09-10 11:10:51 +08:00
await screen . findByRole ( "heading" , { name : "Channels" }),
2026-07-24 00:55:06 +08:00
). toBeInTheDocument ();
2026-09-10 11:10:51 +08:00
expect ( within ( screen . getByRole ( "navigation" , { name : "Sidebar navigation" })). getByRole ( "button" , { name : "Channels" })). toHaveAttribute ( "aria-current" , "page" );
2026-07-13 13:11:46 +08:00
expect ( window . location . hash ). toBe ( "#/settings?section=channels" );
});
2026-10-12 11:36:42 +08:00
it . each ([ "before disconnect" , "after disconnect" ])( "finishes a requested restart when another tab clears its marker %s" , async ( clearWhen ) => {
mockDefaultChatId = "restart-fixture" ;
window . history . replaceState ( null , "" , "/#/settings?section=runtime" );
mockFetchRoutes ({ "/api/settings" : baseSettingsPayload () });
render (< App />);
fireEvent . click ( await screen . findByRole ( "button" , { name : "Restart" , exact : true }));
expect ( sendSystemCommandSpy ). toHaveBeenCalledWith ( "restart-fixture" , "/restart" );
expect ( screen . getByRole ( "button" , { name : "Restarting..." , exact : true })). toBeDisabled ();
act (() => {
if ( clearWhen === "before disconnect" ) localStorage . removeItem ( "nanobot-webui.restartStartedAt" );
for ( const handler of statusHandlers ) handler ( "reconnecting" );
localStorage . removeItem ( "nanobot-webui.restartStartedAt" );
for ( const handler of statusHandlers ) handler ( "open" );
});
await waitFor (() => expect ( screen . getByRole ( "button" , { name : "Restart" , exact : true })). toBeEnabled ());
expect ( createChatSpy ). not . toHaveBeenCalled ();
});
2026-09-23 17:27:34 +08:00
it ( "refreshes settings after the browser reconnects from a restart" , async () => {
let restartCompleted = false ;
let refreshedSettingsRequests = 0 ;
let releaseRefreshedSettings !: () => void ;
const refreshedSettingsReady = new Promise < void >(( resolve ) => {
releaseRefreshedSettings = resolve ;
});
const pendingSettings = {
... baseSettingsPayload (),
requires_restart : true ,
restart_required_sections : [ "runtime" ],
};
const refreshedSettings = {
... baseSettingsPayload (),
requires_restart : false ,
restart_required_sections : [],
};
localStorage . setItem ( "nanobot-webui.restartStartedAt" , String ( Date . now () - 2 _000 ));
window . history . replaceState ( null , "" , "/#/settings?section=runtime" );
mockFetchRoutes ({
"/api/settings" : () => {
if ( ! restartCompleted ) return pendingSettings ;
refreshedSettingsRequests += 1 ;
if ( refreshedSettingsRequests === 1 ) throw new Error ( "gateway is still starting" );
return refreshedSettingsReady . then (() => refreshedSettings );
},
});
render (< App />);
await waitFor (() => {
expect ( screen . getAllByText ( "Saved. Restart to apply changes." ). length ). toBeGreaterThan ( 0 );
}, { timeout : 10_000 });
restartCompleted = true ;
act (() => {
for ( const handler of statusHandlers ) handler ( "reconnecting" );
for ( const handler of statusHandlers ) handler ( "open" );
});
await waitFor (() => expect ( refreshedSettingsRequests ). toBeGreaterThan ( 1 ));
await act ( async () => {
releaseRefreshedSettings ();
await refreshedSettingsReady ;
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Back to chat" }));
await waitFor (() => expect ( window . location . hash ). toBe ( "#/new" ));
expect ( await screen . findByText ( HERO_GREETING_PATTERN , {}, { timeout : 10_000 })). toBeInTheDocument ();
}, 30 _000 );
2026-06-06 19:49:33 +08:00
it ( "opens Skills from the main sidebar" , async () => {
2026-07-27 21:31:34 +08:00
const longSkillDescription = [
"Work with GitHub repositories, issues, pull requests, releases, workflows," ,
"and code search through the GitHub CLI." ,
"Use this skill for repository maintenance, review automation, release preparation," ,
"and other GitHub workflows that need authenticated command-line access." ,
]. join ( " " );
2026-06-06 19:49:33 +08:00
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/settings/cli-apps" : { apps : [], installed_count : 0 , catalog_updated_at : "2026-04-18" },
"/api/settings/mcp-presets" : { presets : [], installed_count : 0 },
"/api/webui/skills" : {
skills : [
2026-07-27 21:19:42 +08:00
{
name : "cron" ,
description : "Schedule reminders." ,
source : "builtin" ,
enabled : true ,
deletable : false ,
available : true ,
},
2026-06-06 19:49:33 +08:00
{
name : "github" ,
description : "Work with GitHub." ,
source : "builtin" ,
2026-07-27 21:19:42 +08:00
enabled : true ,
deletable : false ,
2026-06-06 19:49:33 +08:00
available : false ,
unavailable_reason : "CLI: gh" ,
},
2026-07-27 21:19:42 +08:00
{
name : "custom-skill" ,
description : "A workspace skill." ,
source : "workspace" ,
enabled : true ,
deletable : true ,
available : true ,
},
2026-06-06 19:49:33 +08:00
],
},
"/api/webui/skills/github" : {
name : "github" ,
2026-07-27 21:31:34 +08:00
description : longSkillDescription ,
2026-06-06 19:49:33 +08:00
source : "builtin" ,
2026-07-27 21:19:42 +08:00
enabled : true ,
deletable : false ,
2026-06-06 19:49:33 +08:00
available : false ,
unavailable_reason : "CLI: gh" ,
requirements : {
bins : [ "gh" ],
env : [],
missing_bins : [ "gh" ],
missing_env : [],
},
2026-07-27 21:19:42 +08:00
install_options : [{
id : "brew" ,
kind : "brew" ,
label : "Install GitHub CLI (brew)" ,
command : "brew install gh" ,
}],
2026-06-06 19:49:33 +08:00
raw_markdown : "---\nname: github\n---\nUse GitHub CLI." ,
},
2026-08-10 15:43:54 +08:00
});
requestMutationSpy . mockResolvedValueOnce ({
skills : [
{
name : "cron" ,
description : "Schedule reminders." ,
source : "builtin" ,
enabled : true ,
deletable : false ,
available : true ,
2026-07-27 21:19:42 +08:00
},
2026-08-10 15:43:54 +08:00
{
name : "github" ,
description : "Work with GitHub." ,
source : "builtin" ,
enabled : false ,
deletable : false ,
available : false ,
unavailable_reason : "CLI: gh" ,
},
{
name : "custom-skill" ,
description : "A workspace skill." ,
source : "workspace" ,
enabled : true ,
deletable : true ,
available : true ,
},
],
last_action : { name : "github" , enabled : false , deleted : false },
2026-06-06 19:49:33 +08:00
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
const skillsButton = within ( sidebar ). getByRole ( "button" , { name : "Skills" });
fireEvent . click ( skillsButton );
expect ( await screen . findByRole ( "heading" , { name : "Skills" })). toBeInTheDocument ();
2026-07-27 21:19:42 +08:00
expect ( screen . getByRole ( "textbox" , { name : "Search installed skills" })). toBeInTheDocument ();
expect ( screen . getByRole ( "heading" , { name : "Custom" })). toBeInTheDocument ();
expect ( screen . getByRole ( "heading" , { name : "Built-in" })). toBeInTheDocument ();
2026-06-06 19:49:33 +08:00
expect ( screen . getByText ( "cron" )). toBeInTheDocument ();
expect ( screen . getByText ( "github" )). toBeInTheDocument ();
2026-07-27 21:19:42 +08:00
expect ( screen . getByText ( "Needs setup" )). toBeInTheDocument ();
2026-08-05 13:24:45 +08:00
expect (
screen . queryByText ( "Review the instruction skills this agent can load during a conversation." ),
). not . toBeInTheDocument ();
2026-06-06 19:49:33 +08:00
expect ( screen . getByRole ( "navigation" , { name : "Sidebar navigation" })). toBeInTheDocument ();
expect ( screen . queryByRole ( "navigation" , { name : "Settings sections" })). not . toBeInTheDocument ();
expect ( within ( sidebar ). getByRole ( "button" , { name : "Skills" })). toHaveAttribute (
"aria-current" ,
"page" ,
);
2026-10-07 15:19:55 +08:00
expect ( document . title ). toBe ( "Skills" );
2026-06-06 19:49:33 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : "Back to chat" }));
expect ( await screen . findByText ( HERO_GREETING_PATTERN )). toBeInTheDocument ();
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Skills" }));
expect ( await screen . findByRole ( "heading" , { name : "Skills" })). toBeInTheDocument ();
fireEvent . click ( screen . getByRole ( "button" , { name : "Open details for github" }));
expect ( await screen . findByRole ( "heading" , { name : "github" })). toBeInTheDocument ();
2026-07-27 21:31:34 +08:00
const showMore = await screen . findByRole ( "button" , { name : "Show more" });
expect ( showMore ). toHaveAttribute ( "aria-expanded" , "false" );
fireEvent . click ( showMore );
expect ( screen . getByRole ( "button" , { name : "Show less" })). toHaveAttribute (
"aria-expanded" ,
"true" ,
);
2026-07-27 21:19:42 +08:00
expect ( screen . getByText ( "Setup required" )). toBeInTheDocument ();
2026-08-05 13:24:45 +08:00
expect (
screen . queryByText (
"Allow the agent to load this skill when its requirements are ready." ,
),
). not . toBeInTheDocument ();
2026-07-27 21:19:42 +08:00
expect ( screen . getByText ( "brew install gh" )). toBeInTheDocument ();
expect ( screen . queryByText ( "Unavailable reason" )). not . toBeInTheDocument ();
expect ( screen . queryByText ( "Missing CLI" )). not . toBeInTheDocument ();
expect ( screen . getByRole ( "button" , { name : "Check again" })). toBeInTheDocument ();
fireEvent . click ( screen . getByText ( "Skill instructions" ));
2026-06-06 19:49:33 +08:00
expect ( screen . getByText ( /Use GitHub CLI/ )). toBeInTheDocument ();
2026-07-27 21:19:42 +08:00
const enabledSwitch = screen . getByRole ( "switch" , { name : "Disable github" });
expect ( enabledSwitch ). toHaveAttribute ( "aria-checked" , "true" );
2026-09-19 15:05:02 +08:00
expect ( enabledSwitch ). toHaveClass ( "h-5" , "w-9" , "bg-foreground" );
2026-07-27 21:19:42 +08:00
fireEvent . click ( enabledSwitch );
await waitFor (() => {
expect ( screen . getByRole ( "switch" , { name : "Enable github" })). toHaveAttribute (
"aria-checked" ,
"false" ,
);
});
2026-09-19 15:05:02 +08:00
expect ( screen . getByRole ( "switch" , { name : "Enable github" })). toHaveClass ( "h-5" , "w-9" , "bg-muted-foreground/25" );
2026-07-27 21:19:42 +08:00
});
it ( "deletes a custom skill from its detail sheet" , async () => {
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/settings/cli-apps" : { apps : [], installed_count : 0 , catalog_updated_at : "2026-04-18" },
"/api/settings/mcp-presets" : { presets : [], installed_count : 0 },
"/api/webui/skills" : {
skills : [
{
name : "custom-skill" ,
description : "A workspace skill." ,
source : "workspace" ,
enabled : true ,
deletable : true ,
available : true ,
},
],
},
"/api/webui/skills/custom-skill" : {
name : "custom-skill" ,
description : "A workspace skill." ,
source : "workspace" ,
enabled : true ,
deletable : true ,
available : true ,
requirements : {
bins : [],
env : [],
missing_bins : [],
missing_env : [],
},
raw_markdown : "---\nname: custom-skill\n---\nWorkspace instructions." ,
},
2026-08-10 15:43:54 +08:00
});
requestMutationSpy . mockResolvedValueOnce ({
skills : [],
last_action : { name : "custom-skill" , enabled : false , deleted : true },
2026-07-27 21:19:42 +08:00
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Skills" }));
fireEvent . click (
await screen . findByRole ( "button" , { name : "Open details for custom-skill" }),
);
expect ( await screen . findByRole ( "heading" , { name : "custom-skill" })). toBeInTheDocument ();
fireEvent . click ( screen . getByRole ( "button" , { name : "Delete" }));
expect ( screen . getByRole ( "heading" , { name : "Delete custom-skill?" })). toBeInTheDocument ();
fireEvent . click ( screen . getByRole ( "button" , { name : "Delete skill" }));
await waitFor (() => {
expect (
screen . queryByRole ( "button" , { name : "Open details for custom-skill" }),
). not . toBeInTheDocument ();
});
2026-10-07 21:28:53 +08:00
expect ( screen . getByText ( "No skills are available." )). toBeInTheDocument ();
2026-07-27 21:19:42 +08:00
});
it ( "discovers and installs a skill from skills.sh" , async () => {
2026-07-28 20:32:13 +08:00
let finishInstall !: ( value : unknown ) => void ;
const pendingInstall = new Promise < unknown >(( resolve ) => {
finishInstall = resolve ;
});
const installedPayload = {
skills : [
{
name : "react-testing" ,
description : "Test React apps." ,
source : "workspace" ,
available : true ,
},
{ name : "cron" , description : "Schedule reminders." , source : "builtin" , available : true },
],
last_action : {
installed : true ,
already_installed : false ,
name : "react-testing" ,
},
};
2026-07-27 21:19:42 +08:00
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/settings/cli-apps" : { apps : [], installed_count : 0 , catalog_updated_at : "2026-04-18" },
"/api/settings/mcp-presets" : { presets : [], installed_count : 0 },
"/api/webui/skills" : {
skills : [
{ name : "cron" , description : "Schedule reminders." , source : "builtin" , available : true },
],
},
2026-07-28 16:56:39 +08:00
"/api/webui/skills/trending?provider=all" : {
period : "mixed" ,
provider : "all" ,
2026-07-27 21:19:42 +08:00
install_supported : true ,
2026-07-28 16:56:39 +08:00
skills : [
{
id : "vercel-labs/skills/find-skills" ,
skill_id : "find-skills" ,
name : "find-skills" ,
source : "vercel-labs/skills" ,
provider : "skills_sh" ,
installs : 14_481 ,
url : "https://skills.sh/vercel-labs/skills/find-skills" ,
installed : false ,
install_supported : true ,
metric : "installs_24h" ,
rank : 18 ,
},
{
id : "skillhub:ima-skills" ,
skill_id : "ima-skills" ,
name : "ima-skills" ,
source : "@tencent-adm/ima-skills" ,
provider : "skillhub" ,
installs : 11_831 ,
downloads : 142_525 ,
2026-10-08 12:56:33 +08:00
url : "https://skillhub.cn/skills/tencent-adm/ima-skills" ,
2026-07-28 16:56:39 +08:00
installed : false ,
install_supported : true ,
metric : "installs_total" ,
version : "1.1.8" ,
verified : true ,
rank : 1 ,
},
],
2026-07-27 21:19:42 +08:00
},
"/api/webui/skills/trends?id=vercel-labs%2Fskills%2Ffind-skills" : {
trends : {
"vercel-labs/skills/find-skills" : [ 20 , 32 , 28 , 45 , 41 , 50 , 62 , 58 ],
},
},
2026-07-28 16:56:39 +08:00
"/api/webui/skills/search?q=React&provider=all" : {
2026-07-27 21:19:42 +08:00
query : "React" ,
2026-07-28 16:56:39 +08:00
provider : "all" ,
2026-07-27 21:19:42 +08:00
install_supported : true ,
2026-07-28 16:56:39 +08:00
skills : [
{
id : "acme/agent-skills/react-testing" ,
skill_id : "react-testing" ,
name : "React Testing" ,
source : "acme/agent-skills" ,
provider : "skills_sh" ,
installs : 42 ,
url : "https://skills.sh/acme/agent-skills/react-testing" ,
installed : false ,
install_supported : true ,
metric : "installs_total" ,
},
{
id : "skillhub:react" ,
skill_id : "react" ,
name : "React" ,
source : "@ivangdavila/react" ,
provider : "skillhub" ,
installs : 693 ,
downloads : 7_718 ,
2026-10-08 12:56:33 +08:00
url : "https://skillhub.cn/skills/ivangdavila/react" ,
2026-07-28 16:56:39 +08:00
installed : false ,
install_supported : true ,
metric : "installs_total" ,
version : "1.0.4" ,
},
],
2026-07-27 21:19:42 +08:00
},
"/api/webui/skills/trends?id=acme%2Fagent-skills%2Freact-testing" : {
trends : { "acme/agent-skills/react-testing" : [] },
},
});
2026-08-10 15:43:54 +08:00
requestMutationSpy . mockImplementationOnce (() => pendingInstall );
2026-07-27 21:19:42 +08:00
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Skills" }));
2026-07-28 15:37:49 +08:00
const discoverTab = await screen . findByRole ( "tab" , { name : "Discover" });
expect ( discoverTab . querySelector ( "svg" )). toBeNull ();
fireEvent . click ( discoverTab );
2026-07-28 16:56:39 +08:00
expect (
2026-10-09 17:47:21 +08:00
await screen . findByRole ( "heading" , { name : "Popular skills" }),
2026-07-28 16:56:39 +08:00
). toBeInTheDocument ();
2026-08-05 13:24:45 +08:00
expect (
screen . queryByText ( "Each marketplace keeps its own ranking and install metrics." ),
). not . toBeInTheDocument ();
2026-07-27 21:19:42 +08:00
expect ( screen . getByText ( "find-skills" )). toBeInTheDocument ();
2026-07-28 16:56:39 +08:00
expect ( screen . getByText ( "ima-skills" )). toBeInTheDocument ();
2026-10-08 12:56:33 +08:00
expect ( screen . getByRole ( "link" , { name : "Open ima-skills on SkillHub" })). toHaveAttribute (
"href" , "https://skillhub.cn/skills/tencent-adm/ima-skills" ,
);
2026-07-28 17:52:42 +08:00
expect ( screen . getAllByText ( "SkillHub" )). toHaveLength ( 2 );
expect ( screen . getAllByText ( "skills.sh" )). toHaveLength ( 2 );
2026-07-27 21:19:42 +08:00
expect ( screen . getByText ( /14,481 installs \/ 24h/ )). toBeInTheDocument ();
2026-08-29 15:21:43 +08:00
expect ( screen . queryByText ( /11,831 installs/ )). not . toBeInTheDocument ();
2026-07-28 18:36:38 +08:00
fireEvent . click ( screen . getByRole ( "tab" , { name : "SkillHub" }));
expect ( screen . getByText ( "ima-skills" )). toBeInTheDocument ();
expect ( screen . queryByText ( "find-skills" )). not . toBeInTheDocument ();
expect (
vi . mocked ( fetch ). mock . calls . some (
([ input ]) =>
String ( input ) === "/api/webui/skills/trending?provider=skillhub" ,
),
). toBe ( false );
fireEvent . click ( screen . getByRole ( "tab" , { name : "All" }));
expect ( screen . getByText ( "find-skills" )). toBeInTheDocument ();
expect ( screen . getByText ( "ima-skills" )). toBeInTheDocument ();
2026-07-27 21:19:42 +08:00
expect (
await screen . findByRole ( "img" , { name : "8-week install trend" }),
). toBeInTheDocument ();
2026-07-28 16:56:39 +08:00
fireEvent . change ( screen . getByRole ( "textbox" , { name : "Search skills" }), {
2026-07-27 21:19:42 +08:00
target : { value : "React" },
});
expect ( await screen . findByText ( "React Testing" )). toBeInTheDocument ();
2026-10-08 12:56:33 +08:00
expect ( screen . getByRole ( "link" , { name : "Open React on SkillHub" })). toHaveAttribute (
"href" , "https://skillhub.cn/skills/ivangdavila/react" ,
);
2026-07-28 16:56:39 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : "Install React Testing" }));
2026-07-27 21:19:42 +08:00
expect (
await screen . findByRole ( "heading" , { name : "Install React Testing?" }),
). toBeInTheDocument ();
fireEvent . click ( screen . getByRole ( "button" , { name : "Install skill" }));
await waitFor (() => {
2026-08-10 15:43:54 +08:00
expect ( requestMutationSpy ). toHaveBeenCalledWith (
"skill.install" ,
{
provider : "skills_sh" ,
source : "acme/agent-skills" ,
skill : "react-testing" ,
},
150 _000 ,
2026-07-27 21:19:42 +08:00
);
});
2026-07-28 20:32:13 +08:00
fireEvent . click ( screen . getByRole ( "tab" , { name : "Installed" }));
fireEvent . click ( screen . getByRole ( "tab" , { name : "Discover" }));
2026-07-28 16:56:39 +08:00
expect (
2026-07-28 20:32:13 +08:00
await screen . findByRole ( "button" , { name : "Install find-skills" }),
2026-07-28 16:56:39 +08:00
). toBeDisabled ();
2026-07-27 21:19:42 +08:00
2026-07-28 20:32:13 +08:00
await act ( async () => {
finishInstall ( installedPayload );
await pendingInstall ;
});
await waitFor (() => {
expect ( screen . getByRole ( "button" , { name : "Install find-skills" })). toBeEnabled ();
});
2026-07-27 21:19:42 +08:00
fireEvent . click ( screen . getByRole ( "tab" , { name : "Installed" }));
expect ( screen . getByText ( "react-testing" )). toBeInTheDocument ();
2026-06-06 19:49:33 +08:00
});
2026-06-13 20:08:18 +08:00
it ( "opens Automations from the main sidebar" , async () => {
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/webui/automations" : {
jobs : [
{
id : "job-1" ,
name : "Daily repo check" ,
enabled : true ,
protected : false ,
delete_after_run : false ,
schedule : { kind : "every" , every_ms : 86_400_000 },
payload : {
message : "Check the repo status" ,
kind : "agent_turn" ,
},
state : {
2026-09-12 23:31:35 +08:00
next_run_at_ms : currentMonthTimestamp ( 17 ),
2026-06-13 20:08:18 +08:00
last_status : "ok" ,
pending : false ,
run_history : [],
},
origin : {
session_key : "websocket:chat-a" ,
channel : "websocket" ,
chat_id : "chat-a" ,
title : "Release prep" ,
preview : "Check release blockers" ,
},
},
2026-06-14 00:32:53 +08:00
{
id : "external-quiz" ,
name : "WeChat quiz" ,
enabled : true ,
protected : false ,
delete_after_run : false ,
2026-06-16 00:59:42 +08:00
schedule : { kind : "cron" , expr : "30 9-23 * * *" , tz : "Asia/Shanghai" },
2026-06-14 00:32:53 +08:00
payload : {
message : "Send a quiz" ,
kind : "agent_turn" ,
},
state : {
2026-09-12 23:31:35 +08:00
next_run_at_ms : currentMonthTimestamp ( 17 , 11 , 30 ),
2026-06-14 00:32:53 +08:00
last_status : "ok" ,
pending : false ,
run_history : [],
},
origin : {
channel : "weixin" ,
2026-06-14 22:19:28 +08:00
title : "" ,
preview : "" ,
2026-06-14 00:32:53 +08:00
},
},
2026-06-13 20:08:18 +08:00
{
id : "heartbeat" ,
name : "heartbeat" ,
enabled : true ,
protected : true ,
schedule : { kind : "every" , every_ms : 60_000 },
payload : { message : "" , kind : "system_event" },
state : { next_run_at_ms : null , pending : false , run_history : [] },
origin : null ,
},
],
},
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
const automationsButton = within ( sidebar ). getByRole ( "button" , {
name : "Automations" ,
});
fireEvent . click ( automationsButton );
2026-09-12 23:31:35 +08:00
const heading = await screen . findByRole (
"heading" ,
{ name : "Automations" },
{ timeout : 5_000 },
);
2026-06-15 18:08:44 +08:00
expect ( heading ). toBeInTheDocument ();
const automationsMain = heading . closest ( "main" );
expect ( automationsMain ). not . toBeNull ();
expect ( within ( automationsMain as HTMLElement ). queryByText ( "Settings" )). not . toBeInTheDocument ();
2026-09-12 23:31:35 +08:00
expect (( await screen . findAllByText (
"Daily repo check" ,
{},
{ timeout : 5_000 },
)). length ). toBeGreaterThanOrEqual ( 1 );
2026-09-12 16:32:46 +08:00
expect ( screen . queryByText ( "Check the repo status" )). not . toBeInTheDocument ();
2026-09-11 19:10:15 +08:00
expect ( screen . queryByRole ( "dialog" )). not . toBeInTheDocument ();
fireEvent . click ( screen . getByRole ( "button" , { name : /Daily repo check/ }));
2026-09-12 16:32:46 +08:00
expect ( within ( screen . getByRole ( "dialog" , { name : "Daily repo check" })). getByText ( "Check the repo status" )). toBeVisible ();
2026-09-13 05:36:02 +08:00
const detail = within ( screen . getByRole ( "dialog" , { name : "Daily repo check" }));
expect ( detail . queryByText ( "Release prep" )). not . toBeInTheDocument ();
2026-10-05 01:51:59 +08:00
const user = userEvent . setup ();
await user . click ( detail . getByRole ( "button" , { name : "More actions" }));
expect ( screen . getByRole ( "menuitem" , { name : "Open a chat" })). toHaveAttribute (
2026-09-13 05:36:02 +08:00
"href" , "#/chat/websocket%3Achat-a" ,
);
2026-10-05 01:51:59 +08:00
await user . keyboard ( "{Escape}" );
expect ( detail . getByRole ( "button" , { name : "More actions" })). toHaveFocus ();
2026-09-12 23:31:35 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : "Close" , exact : true }));
2026-06-14 00:32:53 +08:00
expect ( screen . getByText ( "WeChat quiz" )). toBeInTheDocument ();
2026-09-11 19:10:15 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : /WeChat quiz/ }));
2026-06-14 00:32:53 +08:00
expect ( screen . getByText ( "WeChat" )). toBeInTheDocument ();
2026-09-12 23:31:35 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : "Close" , exact : true }));
2026-06-14 00:32:53 +08:00
expect ( screen . queryByText ( "weixin:wx-chat" )). not . toBeInTheDocument ();
expect ( screen . queryByText ( "memory with dream state" )). not . toBeInTheDocument ();
2026-09-13 05:36:02 +08:00
expect ( screen . queryByRole ( "button" , { name : /heartbeat/ })). not . toBeInTheDocument ();
expect ( screen . queryByRole ( "button" , { name : "System tasks 1" })). not . toBeInTheDocument ();
expect ( screen . queryByText ( "heartbeat" )). not . toBeInTheDocument ();
2026-06-13 20:08:18 +08:00
expect ( within ( sidebar ). getByRole ( "button" , { name : "Automations" })). toHaveAttribute (
"aria-current" ,
"page" ,
);
2026-10-07 15:19:55 +08:00
expect ( document . title ). toBe ( "Automations" );
2026-06-16 00:59:42 +08:00
2026-06-13 20:08:18 +08:00
});
2026-09-13 05:36:02 +08:00
it ( "keeps the automation chat link stable across live sidebar renames without duplicating titles" , async () => {
2026-09-11 19:10:15 +08:00
const key = "websocket:linked-chat" ;
mockSessions = [{
key , channel : "websocket" , chatId : "linked-chat" , createdAt : null , updatedAt : null ,
title : "Stored title" , preview : "Original preview" ,
}];
const sidebarState : SidebarStatePayload = {
schema_version : 1 , pinned_keys : [], archived_keys : [], session_order : [],
title_overrides : { [ key ] : "推特大战场" }, project_name_overrides : {},
tags_by_key : {}, collapsed_groups : {}, workbench : { version : 1 , tabs : {} },
view : { density : "comfortable" , show_previews : false , show_timestamps : false ,
show_archived : false , sort : "updated_desc" },
};
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/webui/sidebar-state" : sidebarState ,
"/api/webui/automations" : { jobs : [{
id : "reminder" , name : "Drink water" , enabled : true ,
schedule : { kind : "every" , every_ms : 60_000 },
2026-09-12 23:31:35 +08:00
payload : { message : "Take a break" },
state : { next_run_at_ms : currentMonthTimestamp ( 17 ) },
2026-09-11 19:10:15 +08:00
origin : { session_key : key , channel : "websocket" , chat_id : "linked-chat" ,
title : "Stored title" , preview : "Original preview" },
}] },
});
render (< App />);
const sidebar = await screen . findByRole ( "navigation" , { name : "Sidebar navigation" });
await within ( sidebar ). findByRole ( "button" , { name : "推特大战场" , exact : true });
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Automations" }));
fireEvent . click ( await screen . findByRole ( "button" , { name : /Drink water/ }));
const dialog = screen . getByRole ( "dialog" , { name : "Drink water" });
2026-09-13 05:36:02 +08:00
expect ( within ( dialog ). queryByText ( "推特大战场" )). not . toBeInTheDocument ();
expect ( within ( dialog ). queryByText ( "Stored title" )). not . toBeInTheDocument ();
2026-10-05 01:51:59 +08:00
const user = userEvent . setup ();
await user . click ( within ( dialog ). getByRole ( "button" , { name : "More actions" }));
expect ( screen . getByRole ( "menuitem" , { name : "Open a chat" })). toHaveAttribute (
2026-09-11 19:10:15 +08:00
"href" , "#/chat/websocket%3Alinked-chat" ,
);
for ( const title of [ "新会话名称" , "" ]) {
act (() => {
sidebarStateUpdateHandlers . forEach (( handler ) => handler ({
... sidebarState , title_overrides : title ? { [ key ] : title } : {},
}));
});
const expected = title || "Stored title" ;
expect ( within ( sidebar ). getByText ( expected )). toBeInTheDocument ();
2026-09-13 05:36:02 +08:00
expect ( within ( dialog ). queryByText ( expected )). not . toBeInTheDocument ();
2026-10-05 01:51:59 +08:00
expect ( screen . getByRole ( "menuitem" , { name : "Open a chat" })). toHaveAttribute (
2026-09-13 05:36:02 +08:00
"href" , "#/chat/websocket%3Alinked-chat" ,
);
2026-09-11 19:10:15 +08:00
}
2026-10-05 01:51:59 +08:00
await user . keyboard ( "{Escape}" );
expect ( within ( dialog ). getByRole ( "button" , { name : "More actions" })). toHaveFocus ();
2026-09-11 19:10:15 +08:00
expect ( requestMutationSpy ). not . toHaveBeenCalled ();
});
2026-06-15 00:59:23 +08:00
it ( "edits a past one-time automation without resubmitting its old schedule" , async () => {
const pastOneShot = {
id : "past-one-shot" ,
name : "Past one-shot" ,
enabled : true ,
protected : false ,
delete_after_run : true ,
schedule : { kind : "at" , at_ms : 1 },
payload : {
message : "Old one-shot message" ,
kind : "agent_turn" ,
},
state : {
next_run_at_ms : null ,
2026-09-12 23:31:35 +08:00
last_run_at_ms : currentMonthTimestamp ( 12 ),
2026-06-15 00:59:23 +08:00
last_status : "ok" ,
pending : false ,
run_history : [],
},
origin : {
session_key : "websocket:chat-a" ,
channel : "websocket" ,
chat_id : "chat-a" ,
title : "Release prep" ,
preview : "Check release blockers" ,
},
};
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/webui/automations" : { jobs : [ pastOneShot ] },
2026-08-10 15:43:54 +08:00
});
requestMutationSpy . mockResolvedValueOnce ({
jobs : [{
... pastOneShot ,
payload : { ... pastOneShot . payload , message : "Updated one-shot message" },
}],
2026-06-15 00:59:23 +08:00
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Automations" }));
2026-06-15 16:35:15 +08:00
expect (( await screen . findAllByText ( "Past one-shot" )). length ). toBeGreaterThanOrEqual ( 1 );
2026-09-11 19:10:15 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : /Past one-shot/ }));
2026-09-13 05:36:02 +08:00
const runDetail = within ( screen . getByRole ( "dialog" , { name : "Past one-shot" }));
expect ( runDetail . getByText ( "Completed" )). toBeVisible ();
expect ( runDetail . queryByRole ( "button" , { name : "Edit" , exact : true })). not . toBeInTheDocument ();
fireEvent . click ( runDetail . getByRole ( "button" , { name : "Close" , exact : true }));
fireEvent . click ( screen . getByRole ( "button" , { name : "Tasks" , exact : true }));
fireEvent . click ( screen . getByRole ( "button" , { name : /Past one-shot/ }));
2026-06-15 00:59:23 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : "Edit" }));
2026-10-09 17:47:21 +08:00
await screen . findByRole ( "dialog" , { name : "Edit task" });
2026-06-15 00:59:23 +08:00
expect ( screen . queryByText ( "Run time must be in the future." )). not . toBeInTheDocument ();
2026-06-15 15:22:01 +08:00
expect (
screen . queryByText ( "Update the prompt and schedule. The linked chat stays unchanged." ),
). not . toBeInTheDocument ();
expect ( screen . getByDisplayValue ( "Old one-shot message" )). toHaveClass (
"min-h-[160px]" ,
"resize-none" ,
);
2026-06-15 00:59:23 +08:00
fireEvent . change ( screen . getByDisplayValue ( "Old one-shot message" ), {
target : { value : "Updated one-shot message" },
});
fireEvent . click ( screen . getByRole ( "button" , { name : "Save" }));
await waitFor (() => {
2026-08-10 15:43:54 +08:00
expect ( requestMutationSpy ). toHaveBeenCalledWith (
"automation.update" ,
{
id : "past-one-shot" ,
values : {
name : "Past one-shot" ,
message : "Updated one-shot message" ,
},
},
20 _000 ,
2026-06-15 00:59:23 +08:00
);
});
});
2026-06-15 20:29:18 +08:00
it ( "keeps long automation details expandable without nested scrolling" , async () => {
const longMessage = [
"Review the release plan and prepare a concise status update for the channel." ,
"Include blockers, owners, follow-up dates, and any risky assumptions that changed since yesterday." ,
"Keep the output actionable and avoid repeating context that the team already confirmed in the thread." ,
"If a dependency looks stale, call it out explicitly and ask for a fresh owner update." ,
"This message is intentionally long enough to require progressive disclosure in the automation details panel." ,
"The full content should remain available without forcing the user into a small nested scroll area." ,
]. join ( "\n" );
const history = [
2026-09-12 23:31:35 +08:00
{ run_at_ms : currentMonthTimestamp ( 12 ), status : "error" , duration_ms : 900 , error : "oldest failure" },
{ run_at_ms : currentMonthTimestamp ( 13 ), status : "error" , duration_ms : 800 , error : "second oldest failure" },
{ run_at_ms : currentMonthTimestamp ( 14 ), status : "ok" , duration_ms : 700 },
{ run_at_ms : currentMonthTimestamp ( 15 ), status : "ok" , duration_ms : 600 },
{ run_at_ms : currentMonthTimestamp ( 16 ), status : "ok" , duration_ms : 500 },
{ run_at_ms : currentMonthTimestamp ( 17 ), status : "ok" , duration_ms : 400 },
2026-06-15 20:29:18 +08:00
];
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/webui/automations" : {
jobs : [
{
id : "long-details" ,
name : "Long detail automation" ,
enabled : true ,
protected : false ,
delete_after_run : false ,
schedule : { kind : "every" , every_ms : 3_600_000 },
payload : {
message : longMessage ,
kind : "agent_turn" ,
},
state : {
2026-09-12 23:31:35 +08:00
next_run_at_ms : currentMonthTimestamp ( 18 ),
2026-06-15 20:29:18 +08:00
last_status : "ok" ,
pending : false ,
run_history : history ,
},
origin : {
session_key : "websocket:chat-a" ,
channel : "websocket" ,
chat_id : "chat-a" ,
title : "Release prep" ,
preview : "Check release blockers" ,
},
},
],
},
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Automations" }));
2026-09-12 23:31:35 +08:00
fireEvent . click ( await screen . findByRole (
"button" ,
{ name : /Long detail automation.*Planned/ },
{ timeout : 5_000 },
));
2026-09-11 19:10:15 +08:00
const detailPanel = await screen . findByRole ( "dialog" , { name : "Long detail automation" });
const message = Array . from ( detailPanel . querySelectorAll ( "section p" )). find (
2026-06-15 20:29:18 +08:00
( node ) => node . textContent === longMessage ,
) as HTMLElement | undefined ;
expect ( message ). toBeTruthy ();
2026-09-11 19:10:15 +08:00
const preview = message ! . closest ( ".expandable-text" ) ! ;
expect ( preview ). toHaveAttribute ( "data-state" , "closed" );
2026-06-15 20:29:18 +08:00
fireEvent . click ( within ( detailPanel ). getByRole ( "button" , { name : "Show full message" }));
expect ( within ( detailPanel ). getByRole ( "button" , { name : "Show less" })). toBeInTheDocument ();
2026-09-11 19:10:15 +08:00
expect ( preview ). toHaveAttribute ( "data-state" , "open" );
expect ( preview ). toContainElement ( message ! );
2026-06-15 20:29:18 +08:00
2026-06-15 22:52:26 +08:00
expect ( within ( detailPanel ). queryByText ( "Recent health" )). not . toBeInTheDocument ();
expect ( within ( detailPanel ). queryByRole ( "button" , { name : /Run history/ })). not . toBeInTheDocument ();
expect ( within ( detailPanel ). queryByText ( /oldest failure/ )). not . toBeInTheDocument ();
expect ( within ( detailPanel ). queryByText ( "No error recorded" )). not . toBeInTheDocument ();
2026-06-15 20:29:18 +08:00
});
2026-06-13 20:08:18 +08:00
it ( "localizes the Automations surface" , async () => {
await i18n . changeLanguage ( "zh-CN" );
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
2026-06-13 21:30:31 +08:00
"/api/webui/automations" : {
jobs : [
{
id : "job-zh" ,
name : "每日检查" ,
enabled : true ,
protected : false ,
delete_after_run : false ,
schedule : { kind : "every" , every_ms : 86_400_000 },
payload : {
message : "检查仓库状态" ,
kind : "agent_turn" ,
},
state : {
2026-09-12 23:31:35 +08:00
next_run_at_ms : currentMonthTimestamp ( 17 ),
last_run_at_ms : currentMonthTimestamp ( 16 ),
2026-06-13 21:30:31 +08:00
last_status : "ok" ,
pending : false ,
run_history : [
{
2026-09-12 23:31:35 +08:00
run_at_ms : currentMonthTimestamp ( 16 ),
2026-06-13 21:30:31 +08:00
status : "ok" ,
duration_ms : 500 ,
},
],
},
origin : {
session_key : "websocket:chat-a" ,
channel : "websocket" ,
chat_id : "chat-a" ,
title : "发布准备" ,
preview : "检查发布阻塞项" ,
},
},
],
},
2026-06-13 20:08:18 +08:00
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "侧边栏导航" });
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "自动任务" }));
2026-06-15 18:08:44 +08:00
const heading = await screen . findByRole ( "heading" , { name : "自动任务" });
expect ( heading ). toBeInTheDocument ();
const automationsMain = heading . closest ( "main" );
expect ( automationsMain ). not . toBeNull ();
expect ( within ( automationsMain as HTMLElement ). queryByText ( "设置" )). not . toBeInTheDocument ();
2026-09-11 19:10:15 +08:00
expect ( screen . queryByText ( "任务队列" )). not . toBeInTheDocument ();
2026-06-15 16:35:15 +08:00
expect ( screen . getAllByText ( "每日检查" ). length ). toBeGreaterThanOrEqual ( 1 );
2026-09-12 16:32:46 +08:00
expect ( screen . queryByText ( "检查仓库状态" )). not . toBeInTheDocument ();
2026-09-12 23:31:35 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : /每日检查.*计划运行/ }));
2026-09-12 16:32:46 +08:00
const detail = within ( screen . getByRole ( "dialog" , { name : "每日检查" }));
expect ( detail . getByText ( "检查仓库状态" )). toBeVisible ();
2026-09-13 05:36:02 +08:00
expect ( detail . queryByText ( /每 1天/ )). not . toBeInTheDocument ();
fireEvent . click ( detail . getByRole ( "button" , { name : "任务信息" }));
expect ( within ( screen . getByRole ( "dialog" , { name : "任务信息" })). getByText ( /每 1天/ )). toBeVisible ();
2026-06-15 22:52:26 +08:00
expect ( screen . queryByText ( "最近健康状态" )). not . toBeInTheDocument ();
expect ( screen . queryByText ( "近期无问题" )). not . toBeInTheDocument ();
2026-06-13 20:08:18 +08:00
expect ( screen . queryByText ( "Workspace automations" )). not . toBeInTheDocument ();
2026-06-14 01:03:53 +08:00
expect ( screen . queryByRole ( "button" , { name : "刷新" })). not . toBeInTheDocument ();
2026-10-07 15:19:55 +08:00
expect ( document . title ). toBe ( "自动任务" );
2026-06-13 20:08:18 +08:00
});
2026-09-10 11:10:51 +08:00
it ( "resizes the sidebar, collapses at the drag threshold and restores its saved width" , async () => {
const view = render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const handle = screen . getByRole ( "separator" , { name : "Resize sidebar" });
const sidebar = screen . getByTestId ( "host-sidebar-flow" );
2026-09-11 19:36:57 +08:00
expect ( sidebar ). toHaveClass ( "group/sidebar" );
2026-09-10 11:10:51 +08:00
fireEvent . pointerDown ( handle , { button : 0 , pointerId : 1 , clientX : 272 });
2026-09-11 19:36:57 +08:00
expect ( sidebar ). toHaveAttribute ( "data-resizing" , "true" );
2026-09-10 11:10:51 +08:00
fireEvent . pointerMove ( handle , { pointerId : 1 , clientX : 360 });
2026-09-11 19:36:57 +08:00
expect ( sidebar ). toHaveStyle ({ width : "360px" });
2026-09-10 11:10:51 +08:00
fireEvent . pointerUp ( handle , { pointerId : 1 , clientX : 360 });
2026-09-11 19:36:57 +08:00
expect ( sidebar ). not . toHaveAttribute ( "data-resizing" );
2026-09-10 11:10:51 +08:00
expect ( sidebar ). toHaveStyle ({ width : "360px" });
expect ( localStorage . getItem ( "nanobot-webui.sidebar.width" )). toBe ( "360" );
fireEvent . pointerDown ( handle , { button : 0 , pointerId : 2 , clientX : 360 });
fireEvent . pointerMove ( handle , { pointerId : 2 , clientX : 150 });
expect ( sidebar ). toHaveStyle ({ width : "56px" });
fireEvent . pointerMove ( handle , { pointerId : 2 , clientX : 180 });
expect ( sidebar ). toHaveStyle ({ width : "56px" });
fireEvent . pointerMove ( handle , { pointerId : 2 , clientX : 240 });
fireEvent . pointerUp ( handle , { pointerId : 2 , clientX : 240 });
expect ( sidebar ). toHaveStyle ({ width : "240px" });
fireEvent . keyDown ( handle , { key : "Enter" });
expect ( sidebar ). toHaveStyle ({ width : "56px" });
view . unmount ();
render (< App />);
await waitFor (() => expect ( screen . getByTestId ( "host-sidebar-flow" )). toHaveStyle ({ width : "56px" }));
fireEvent . click ( within ( screen . getByRole ( "navigation" , { name : "Sidebar navigation" })). getByRole ( "button" , { name : "Toggle sidebar" }));
expect ( screen . getByTestId ( "host-sidebar-flow" )). toHaveStyle ({ width : "240px" });
fireEvent . keyDown ( screen . getByRole ( "separator" , { name : "Resize sidebar" }), { key : "ArrowRight" });
expect ( screen . getByTestId ( "host-sidebar-flow" )). toHaveStyle ({ width : "272px" });
});
2026-09-11 19:36:57 +08:00
it . each ([ "pointerUp" , "pointerCancel" , "lostPointerCapture" ] as const )( "keeps highlight easing while disabling navigation target lag until %s" , async ( finish ) => {
mockSessions = [{
key : "websocket:resize-test" , channel : "websocket" , chatId : "resize-test" ,
createdAt : "2026-04-16T10:00:00Z" , updatedAt : "2026-04-16T10:00:00Z" ,
title : "Resize test" , preview : "" ,
}];
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByTestId ( "host-sidebar-flow" );
await within ( sidebar ). findByTestId ( "chats-selection-highlight" );
const handle = within ( sidebar ). getByRole ( "separator" , { name : "Resize sidebar" });
for ( const label of [ "Apps" , "Skills" , "Automations" , "Channels" ]) {
expect ( within ( sidebar ). getByRole ( "button" , { name : label })). toHaveClass (
"group-data-[resizing=true]/sidebar:transition-none" ,
);
}
for ( const scope of [ "actions" , "chats" ]) {
const highlight = within ( sidebar ). getByTestId ( ` ${ scope } -selection-highlight` );
expect ( highlight ). not . toHaveClass (
"group-data-[resizing=true]/sidebar:transition-none" ,
);
expect ( highlight ). toHaveClass (
"transition-[transform,width,height]" ,
"duration-300" ,
"ease-out" ,
"motion-reduce:transition-none" ,
);
}
fireEvent . pointerDown ( handle , { button : 0 , pointerId : 1 , clientX : 272 });
fireEvent . pointerMove ( handle , { pointerId : 1 , clientX : 400 });
expect ( sidebar ). toHaveAttribute ( "data-resizing" , "true" );
expect ( sidebar ). toHaveStyle ({ width : "400px" });
fireEvent [ finish ]( handle , { pointerId : 1 , clientX : 400 });
expect ( sidebar ). not . toHaveAttribute ( "data-resizing" );
expect ( sidebar ). toHaveClass ( "transition-[width]" );
});
2026-09-03 00:01:39 +08:00
it ( "uses the shared sidebar controls and rail on the native host" , async () => {
2026-06-06 19:49:33 +08:00
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "Desktop chat" ,
},
];
vi . mocked ( fetchBootstrap ). mockResolvedValue ({
token : "tok" ,
2026-07-08 14:27:52 +08:00
api_token : "api-tok" ,
2026-06-06 19:49:33 +08:00
ws_path : "/" ,
expires_in : 300 ,
runtime_surface : "native" ,
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const flowSidebar = screen . getByTestId ( "host-sidebar-flow" );
expect ( flowSidebar ). toHaveStyle ({ width : "272px" });
2026-09-03 00:01:39 +08:00
expect ( screen . getByTestId ( "sidebar-brand-row" )). toHaveClass ( "pt-3" );
expect ( screen . getByTestId ( "sidebar-brand-mark" )). toHaveClass ( "mt-5" );
2026-09-10 11:10:51 +08:00
expect ( screen . getByRole ( "separator" , { name : "Resize sidebar" })). toHaveAttribute ( "aria-valuenow" , "272" );
2026-09-03 00:01:39 +08:00
expect ( screen . queryByTestId ( "host-sidebar-toggle" )). not . toBeInTheDocument ();
2026-06-06 19:49:33 +08:00
expect (
screen . getByRole ( "navigation" , { name : "Sidebar navigation" }),
). toBeInTheDocument ();
2026-09-10 11:10:51 +08:00
fireEvent . keyDown ( screen . getByRole ( "separator" , { name : "Resize sidebar" }), { key : "Enter" });
2026-09-03 00:01:39 +08:00
await waitFor (() => expect ( flowSidebar ). toHaveStyle ({ width : "56px" }));
2026-06-06 19:49:33 +08:00
expect (
2026-09-03 00:01:39 +08:00
screen . getByRole ( "navigation" , { name : "Sidebar navigation" }),
2026-06-06 19:49:33 +08:00
). toBeInTheDocument ();
2026-09-03 00:01:39 +08:00
fireEvent . click (
within ( screen . getByRole ( "navigation" , { name : "Sidebar navigation" }))
. getByRole ( "button" , { name : "Toggle sidebar" }),
2026-06-06 19:49:33 +08:00
);
2026-09-03 00:01:39 +08:00
await waitFor (() => expect ( flowSidebar ). toHaveStyle ({ width : "272px" }));
2026-06-06 19:49:33 +08:00
});
2026-09-03 10:23:38 +08:00
it ( "aligns native settings navigation below the titlebar without extra top padding" , async () => {
vi . mocked ( fetchBootstrap ). mockResolvedValue ({
token : "tok" ,
api_token : "api-tok" ,
ws_path : "/" ,
expires_in : 300 ,
runtime_surface : "native" ,
});
mockFetchRoutes ({ "/api/settings" : baseSettingsPayload () });
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Settings" }));
const backButton = await screen . findByRole ( "button" , { name : "Back to chat" });
expect ( backButton . closest ( "aside" )). toHaveClass ( "pt-10" , "lg:pt-10" );
expect ( backButton . closest ( "aside" )). not . toHaveClass ( "pt-[4.25rem]" );
expect ( backButton ). toHaveClass ( "-ml-1" );
});
2026-09-03 08:59:49 +08:00
it ( "uses native chrome when the host bridge overrides browser gateway metadata" , async () => {
2026-10-07 16:25:40 +08:00
Reflect . set ( window , "nanobotHost" , { getRuntimeInfo : vi.fn () });
2026-09-03 08:59:49 +08:00
vi . mocked ( fetchBootstrap ). mockResolvedValue ({
token : "tok" ,
api_token : "api-tok" ,
ws_path : "/" ,
expires_in : 300 ,
runtime_surface : "browser" ,
});
mockFetchRoutes ({
"/api/settings" : {
... baseSettingsPayload (),
surface : "browser" ,
runtime_surface : "browser" ,
},
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
await waitFor (() => {
expect ( screen . getByTestId ( "sidebar-brand-mark" )). toHaveClass ( "mt-5" );
});
expect ( document . documentElement ). toHaveClass ( "native-host" );
});
2026-04-18 18:51:53 +00:00
it ( "switches to the next session when deleting the active chat" , async () => {
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "First chat" ,
},
{
key : "websocket:chat-b" ,
channel : "websocket" ,
chatId : "chat-b" ,
createdAt : "2026-04-16T11:00:00Z" ,
updatedAt : "2026-04-16T11:00:00Z" ,
preview : "Second chat" ,
},
];
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
2026-05-06 14:15:36 +00:00
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
2026-04-18 18:51:53 +00:00
await waitFor (() =>
2026-05-06 14:15:36 +00:00
expect (
within ( sidebar ). getByRole ( "button" , { name : /^First chat$/ }),
). toBeInTheDocument (),
2026-04-18 18:51:53 +00:00
);
2026-07-24 10:21:02 +08:00
fireEvent . pointerDown ( screen . getByLabelText ( "Topic actions for First chat" ), {
2026-04-18 18:51:53 +00:00
button : 0 ,
});
fireEvent . click ( await screen . findByRole ( "menuitem" , { name : "Delete" }));
await waitFor (() =>
2026-07-24 10:21:02 +08:00
expect ( screen . getByText ( "Delete this topic?" )). toBeInTheDocument (),
2026-04-18 18:51:53 +00:00
);
fireEvent . click ( screen . getByRole ( "button" , { name : "Delete" }));
await waitFor (() =>
expect ( deleteChatSpy ). toHaveBeenCalledWith ( "websocket:chat-a" ),
);
await waitFor (() =>
expect (
2026-05-06 14:15:36 +00:00
within ( sidebar ). getByRole ( "button" , { name : /^Second chat$/ }),
2026-04-18 18:51:53 +00:00
). toBeInTheDocument (),
);
2026-07-24 10:21:02 +08:00
expect ( screen . queryByText ( "Delete this topic?" )). not . toBeInTheDocument ();
2026-04-18 18:51:53 +00:00
expect ( document . body . style . pointerEvents ). not . toBe ( "none" );
2026-04-19 06:39:06 +00:00
}, 15 _000 );
2026-04-25 18:05:06 +00:00
2026-08-12 14:45:12 +08:00
it ( "deletes multiple selected topics through one confirmation" , async () => {
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "First chat" ,
},
{
key : "websocket:chat-b" ,
channel : "websocket" ,
chatId : "chat-b" ,
createdAt : "2026-04-16T11:00:00Z" ,
updatedAt : "2026-04-16T11:00:00Z" ,
preview : "Second chat" ,
},
{
key : "websocket:chat-c" ,
channel : "websocket" ,
chatId : "chat-c" ,
createdAt : "2026-04-16T12:00:00Z" ,
updatedAt : "2026-04-16T12:00:00Z" ,
preview : "Third chat" ,
},
];
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
fireEvent . pointerDown ( within ( sidebar ). getByLabelText (
"Topic actions for First chat" ,
), { button : 0 });
fireEvent . click ( await screen . findByRole ( "menuitem" , { name : "Select" }));
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Second chat" }));
expect ( within ( sidebar ). getByText ( "2 selected" )). toBeInTheDocument ();
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Delete" }));
expect ( await screen . findByText ( "Delete 2 conversations?" )). toBeInTheDocument ();
fireEvent . click ( screen . getByRole ( "button" , { name : "Delete" }));
await waitFor (() => expect ( deleteChatSpy ). toHaveBeenCalledTimes ( 2 ));
expect ( deleteChatSpy . mock . calls . map (([ key ]) => key )). toEqual ([
"websocket:chat-a" ,
"websocket:chat-b" ,
]);
expect ( getSessionAutomationsSpy ). toHaveBeenCalledWith ( "websocket:chat-a" );
expect ( getSessionAutomationsSpy ). toHaveBeenCalledWith ( "websocket:chat-b" );
expect ( within ( sidebar ). getByRole ( "button" , { name : "Third chat" }))
. toBeInTheDocument ();
}, 15 _000 );
2026-06-12 18:13:25 +08:00
it ( "shows localized bound automations in the first delete confirmation" , async () => {
2026-06-12 17:02:29 +08:00
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "First chat" ,
},
{
key : "websocket:chat-b" ,
channel : "websocket" ,
chatId : "chat-b" ,
createdAt : "2026-04-16T11:00:00Z" ,
updatedAt : "2026-04-16T11:00:00Z" ,
preview : "Second chat" ,
},
];
2026-06-12 18:13:25 +08:00
getSessionAutomationsSpy . mockResolvedValue ([
{
id : "job-1" ,
name : "Daily repo check" ,
enabled : true ,
schedule : { kind : "every" , every_ms : 86_400_000 },
payload : { message : "Check the repo" },
state : { next_run_at_ms : Date.UTC ( 2026 , 3 , 17 , 10 , 0 , 0 ) },
2026-06-12 17:02:29 +08:00
},
2026-06-12 18:13:25 +08:00
]);
await i18n . changeLanguage ( "zh-CN" );
2026-06-12 17:02:29 +08:00
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
2026-06-12 18:13:25 +08:00
const sidebar = screen . getByRole ( "navigation" , { name : "侧边栏导航" });
2026-06-12 17:02:29 +08:00
await waitFor (() =>
expect (
within ( sidebar ). getByRole ( "button" , { name : /^First chat$/ }),
). toBeInTheDocument (),
);
2026-07-24 10:21:02 +08:00
fireEvent . pointerDown ( screen . getByLabelText ( /First chat.*话题操作/ ), {
2026-06-12 17:02:29 +08:00
button : 0 ,
});
2026-06-12 18:13:25 +08:00
fireEvent . click ( await screen . findByRole ( "menuitem" , { name : "删除" }));
2026-06-12 17:02:29 +08:00
await waitFor (() =>
expect ( screen . getByText ( "Daily repo check" )). toBeInTheDocument (),
);
2026-06-12 18:13:25 +08:00
expect ( getSessionAutomationsSpy ). toHaveBeenCalledWith ( "websocket:chat-a" );
2026-06-12 17:02:29 +08:00
expect (
2026-10-09 17:47:21 +08:00
screen . getByText ( "删除话题也会删除关联的自动任务" ),
2026-06-12 17:02:29 +08:00
). toBeInTheDocument ();
2026-06-12 18:13:25 +08:00
expect (
2026-10-09 17:47:21 +08:00
screen . queryByText ( "Deleting this topic also deletes its linked automations." ),
2026-06-12 18:13:25 +08:00
). not . toBeInTheDocument ();
2026-06-12 17:02:29 +08:00
2026-06-16 11:41:05 +08:00
fireEvent . click ( screen . getByRole ( "button" , { name : "删除" }));
2026-06-12 17:02:29 +08:00
await waitFor (() =>
expect ( deleteChatSpy ). toHaveBeenCalledWith ( "websocket:chat-a" , {
deleteAutomations : true ,
}),
);
expect ( deleteChatSpy ). toHaveBeenCalledTimes ( 1 );
expect ( screen . queryByText ( "Daily repo check" )). not . toBeInTheDocument ();
}, 15 _000 );
2026-10-04 23:41:41 +08:00
it ( "closes the mobile drawer when selecting a new or current topic without a search tooltip" , async () => {
2026-09-21 13:44:42 +08:00
restoreBrowserFocus = mockBrowserFocus ();
2026-09-21 12:59:15 +08:00
const user = userEvent . setup ();
mockSessions = [ "First" , "Second" ]. map (( title , index ) => ({
key : `websocket:mobile- ${ index } ` ,
channel : "websocket" ,
chatId : `mobile- ${ index } ` ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : ` ${ title } mobile chat` ,
}));
vi . stubGlobal ( "matchMedia" , vi . fn (). mockImplementation (( query : string ) => ({
matches : ! query . includes ( "1024px" ),
media : query ,
onchange : null ,
addListener : vi.fn (),
removeListener : vi.fn (),
addEventListener : vi.fn (),
removeEventListener : vi.fn (),
dispatchEvent : vi.fn (),
})));
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
2026-10-04 23:41:41 +08:00
for ( const title of [ "First" , "First" , "Second" ]) {
2026-09-21 12:59:15 +08:00
await user . click ( await screen . findByRole ( "button" , { name : "Toggle sidebar" }));
const sheet = await screen . findByRole ( "dialog" );
await waitFor (() => expect ( sheet ). toHaveFocus ());
expect ( screen . queryByRole ( "tooltip" )). not . toBeInTheDocument ();
await user . click ( await within ( sheet ). findByRole ( "button" , { name : ` ${ title } mobile chat` }));
await waitFor (() => expect ( screen . queryByRole ( "dialog" )). not . toBeInTheDocument ());
2026-10-07 15:19:55 +08:00
await waitFor (() => expect ( document . title ). toBe ( ` ${ title } mobile chat` ));
2026-09-21 12:59:15 +08:00
expect ( screen . getByRole ( "button" , { name : ` ${ title } mobile chat` }))
. toHaveAttribute ( "aria-current" , "page" );
}
});
2026-05-19 22:42:38 +08:00
it ( "keeps the mobile session action menu inside the sidebar sheet" , async () => {
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "Existing chat" ,
},
];
vi . stubGlobal (
"matchMedia" ,
vi . fn (). mockImplementation (( query : string ) => ({
matches : ! query . includes ( "1024px" ),
media : query ,
onchange : null ,
addListener : vi.fn (),
removeListener : vi.fn (),
addEventListener : vi.fn (),
removeEventListener : vi.fn (),
dispatchEvent : vi.fn (),
})),
);
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
fireEvent . click ( screen . getByRole ( "button" , { name : "Toggle sidebar" }));
const sheet = await screen . findByRole ( "dialog" );
const mobileSidebar = within ( sheet ). getByRole ( "navigation" , {
name : "Sidebar navigation" ,
});
await waitFor (() =>
expect (
within ( mobileSidebar ). getByRole ( "button" , { name : /^Existing chat$/ }),
). toBeInTheDocument (),
);
fireEvent . pointerDown (
2026-07-24 10:21:02 +08:00
within ( mobileSidebar ). getByLabelText ( "Topic actions for Existing chat" ),
2026-05-19 22:42:38 +08:00
{ button : 0 },
);
const deleteItem = await within ( sheet ). findByRole ( "menuitem" , {
name : "Delete" ,
});
expect ( deleteItem ). toBeInTheDocument ();
fireEvent . click ( deleteItem );
await waitFor (() =>
2026-07-24 10:21:02 +08:00
expect ( screen . getByText ( "Delete this topic?" )). toBeInTheDocument (),
2026-05-19 22:42:38 +08:00
);
}, 15 _000 );
it ( "applies persisted sidebar workspace state from the gateway" , async () => {
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "First chat" ,
},
{
key : "websocket:chat-b" ,
channel : "websocket" ,
chatId : "chat-b" ,
createdAt : "2026-04-16T11:00:00Z" ,
updatedAt : "2026-04-16T11:00:00Z" ,
preview : "Second chat" ,
},
];
const initialState = {
schema_version : 1 ,
pinned_keys : [ "websocket:chat-b" ],
archived_keys : [ "websocket:chat-a" ],
title_overrides : { "websocket:chat-b" : "Roadmap" },
tags_by_key : {},
collapsed_groups : {},
view : {
density : "comfortable" ,
show_previews : false ,
show_timestamps : false ,
show_archived : false ,
sort : "updated_desc" ,
},
updated_at : null ,
};
vi . stubGlobal (
"fetch" ,
vi . fn (). mockImplementation ( async ( url : string | URL | Request ) => {
const href = String ( url );
if ( href === "/api/webui/sidebar-state" ) {
return { ok : true , json : async () => initialState };
}
return { ok : false , status : 404 };
}),
);
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
2026-08-10 15:43:54 +08:00
act (() => {
statusHandlers . forEach (( handler ) => handler ( "open" ));
});
2026-05-19 22:42:38 +08:00
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
await waitFor (() =>
expect ( within ( sidebar ). getByText ( "Pinned" )). toBeInTheDocument (),
);
expect ( within ( sidebar ). getByRole ( "button" , { name : /^Roadmap$/ })). toBeInTheDocument ();
expect ( within ( sidebar ). queryByRole ( "button" , { name : /^First chat$/ })). not . toBeInTheDocument ();
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Show archived" }));
await waitFor (() =>
expect ( within ( sidebar ). getByText ( "Archived" )). toBeInTheDocument (),
);
expect ( within ( sidebar ). getByRole ( "button" , { name : /^First chat$/ })). toBeInTheDocument ();
2026-08-06 18:21:16 +08:00
expect ( setSidebarStateSpy ). toHaveBeenCalledWith (
expect . objectContaining ({
view : expect.objectContaining ({ show_archived : true }),
}),
);
2026-05-19 22:42:38 +08:00
2026-05-29 03:42:53 +08:00
expect ( within ( sidebar ). queryByRole ( "button" , { name : "View" })). not . toBeInTheDocument ();
2026-05-19 22:42:38 +08:00
});
it ( "sorts chats by displayed title when A-Z is persisted" , async () => {
mockSessions = [
{
key : "websocket:zulu" ,
channel : "websocket" ,
chatId : "zulu" ,
createdAt : "2026-04-16T12:00:00Z" ,
updatedAt : "2026-04-16T12:00:00Z" ,
title : "Zulu work" ,
preview : "later" ,
},
{
key : "websocket:new" ,
channel : "websocket" ,
chatId : "new" ,
createdAt : "2026-04-15T12:00:00Z" ,
updatedAt : "2026-04-15T12:00:00Z" ,
preview : "hi nanobot" ,
},
{
key : "websocket:alpha" ,
channel : "websocket" ,
chatId : "alpha" ,
createdAt : "2026-04-14T12:00:00Z" ,
updatedAt : "2026-04-14T12:00:00Z" ,
title : "Alpha plan" ,
preview : "earlier" ,
},
];
const initialState = {
schema_version : 1 ,
pinned_keys : [],
archived_keys : [],
title_overrides : {},
tags_by_key : {},
collapsed_groups : {},
view : {
density : "comfortable" ,
show_previews : false ,
show_timestamps : false ,
show_archived : false ,
sort : "title_asc" ,
},
updated_at : null ,
};
vi . stubGlobal (
"fetch" ,
vi . fn (). mockImplementation ( async ( url : string | URL | Request ) => {
const href = String ( url );
if ( href === "/api/webui/sidebar-state" ) {
return { ok : true , json : async () => initialState };
}
return { ok : false , status : 404 };
}),
);
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
await waitFor (() =>
2026-07-24 10:21:02 +08:00
expect ( within ( sidebar ). getByText ( "Topics" )). toBeInTheDocument (),
2026-05-19 22:42:38 +08:00
);
2026-07-24 10:21:02 +08:00
const group = within ( sidebar ). getByText ( "Topics" ). closest ( "section" );
2026-05-19 22:42:38 +08:00
expect ( group ). toBeTruthy ();
const labels = within ( group as HTMLElement )
. getAllByRole ( "button" )
. map (( button ) => button . textContent ? . trim ())
. filter ( Boolean );
2026-07-24 10:21:02 +08:00
expect ( labels ). toEqual ([ "Alpha plan" , "New topic" , "Zulu work" ]);
2026-05-19 22:42:38 +08:00
});
it ( "shows running and completed session indicators in the sidebar" , async () => {
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "Working chat" ,
},
{
key : "websocket:chat-b" ,
channel : "websocket" ,
chatId : "chat-b" ,
createdAt : "2026-04-16T11:00:00Z" ,
updatedAt : "2026-04-16T11:00:00Z" ,
preview : "Quiet chat" ,
},
];
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
await waitFor (() =>
expect (
within ( sidebar ). getByRole ( "button" , { name : /^Working chat$/ }),
). toBeInTheDocument (),
);
act (() => {
for ( const handler of runStatusHandlers ) handler ( "chat-a" , 12 _345 );
});
2026-08-14 17:03:11 +08:00
expect ( within ( sidebar ). getByRole ( "img" , { name : "Agent running" })). toBeInTheDocument ();
2026-05-19 22:42:38 +08:00
act (() => {
for ( const handler of runStatusHandlers ) handler ( "chat-a" , null );
});
2026-08-14 17:03:11 +08:00
expect ( within ( sidebar ). queryByRole ( "img" , { name : "Agent running" }))
. not . toBeInTheDocument ();
expect ( within ( sidebar ). getByRole ( "img" , { name : "New activity" })). toBeInTheDocument ();
2026-05-19 22:42:38 +08:00
await act ( async () => {
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : /^Working chat$/ }));
});
2026-08-14 17:03:11 +08:00
expect ( within ( sidebar ). queryByRole ( "img" , { name : "New activity" }))
. not . toBeInTheDocument ();
2026-05-19 22:42:38 +08:00
});
2026-06-15 17:30:06 +08:00
it ( "does not show an updated dot later when the active session finishes" , async () => {
2026-05-30 23:45:26 +08:00
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "Active work" ,
},
{
key : "websocket:chat-b" ,
channel : "websocket" ,
chatId : "chat-b" ,
createdAt : "2026-04-16T11:00:00Z" ,
updatedAt : "2026-04-16T11:00:00Z" ,
preview : "Other chat" ,
},
];
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
await waitFor (() =>
expect (
within ( sidebar ). getByRole ( "button" , { name : /^Active work$/ }),
). toBeInTheDocument (),
);
await act ( async () => {
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : /^Active work$/ }));
});
await waitFor (() => expect ( document . title ). toContain ( "Active work" ));
act (() => {
for ( const handler of runStatusHandlers ) handler ( "chat-a" , 12 _345 );
});
2026-08-14 17:03:11 +08:00
expect ( within ( sidebar ). getByRole ( "img" , { name : "Agent running" })). toBeInTheDocument ();
2026-05-30 23:45:26 +08:00
act (() => {
for ( const handler of runStatusHandlers ) handler ( "chat-a" , null );
});
2026-08-14 17:03:11 +08:00
expect ( within ( sidebar ). queryByRole ( "img" , { name : "Agent running" }))
. not . toBeInTheDocument ();
expect ( within ( sidebar ). queryByRole ( "img" , { name : "New activity" }))
. not . toBeInTheDocument ();
2026-05-30 23:45:26 +08:00
await act ( async () => {
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : /^Other chat$/ }));
});
2026-08-14 17:03:11 +08:00
expect ( within ( sidebar ). queryByRole ( "img" , { name : "New activity" }))
. not . toBeInTheDocument ();
2026-06-15 17:30:06 +08:00
});
it ( "marks inactive sessions when a thread update arrives" , async () => {
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "Open chat" ,
},
{
key : "websocket:chat-b" ,
channel : "websocket" ,
chatId : "chat-b" ,
createdAt : "2026-04-16T11:00:00Z" ,
updatedAt : "2026-04-16T11:00:00Z" ,
preview : "Scheduled update target" ,
},
];
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
await act ( async () => {
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : /^Open chat$/ }));
});
act (() => {
for ( const handler of sessionUpdateHandlers ) handler ( "chat-b" , "thread" );
});
2026-08-14 17:03:11 +08:00
expect ( within ( sidebar ). getByRole ( "img" , { name : "New activity" })). toBeInTheDocument ();
2026-06-15 17:30:06 +08:00
await act ( async () => {
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : /^Scheduled update target$/ }));
});
2026-08-14 17:03:11 +08:00
expect ( within ( sidebar ). queryByRole ( "img" , { name : "New activity" }))
. not . toBeInTheDocument ();
2026-05-30 23:45:26 +08:00
});
2026-05-19 22:42:38 +08:00
it ( "restores sidebar run indicators after a page reload" , async () => {
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "Running after reload" ,
runStartedAt : 12_345 ,
},
{
key : "websocket:chat-b" ,
channel : "websocket" ,
chatId : "chat-b" ,
createdAt : "2026-04-16T11:00:00Z" ,
updatedAt : "2026-04-16T11:00:00Z" ,
preview : "Completed after reload" ,
},
];
localStorage . setItem (
2026-06-15 17:30:06 +08:00
"nanobot-webui.sidebar.session-updates.v1" ,
2026-05-19 22:42:38 +08:00
JSON . stringify ([ "chat-b" ]),
);
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
await waitFor (() =>
2026-08-14 17:03:11 +08:00
expect ( within ( sidebar ). getByRole ( "img" , { name : "Agent running" })). toBeInTheDocument (),
2026-05-19 22:42:38 +08:00
);
2026-08-14 17:03:11 +08:00
expect ( within ( sidebar ). getByRole ( "img" , { name : "New activity" })). toBeInTheDocument ();
2026-05-19 22:42:38 +08:00
expect ( attachSpy ). toHaveBeenCalledWith ( "chat-a" );
});
2026-06-02 11:29:18 +08:00
it ( "restores the active chat from the URL hash after a page reload" , async () => {
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "Active after reload" ,
},
{
key : "websocket:chat-b" ,
channel : "websocket" ,
chatId : "chat-b" ,
createdAt : "2026-04-16T11:00:00Z" ,
updatedAt : "2026-04-16T11:00:00Z" ,
preview : "Other chat" ,
},
];
window . history . replaceState (
null ,
"" ,
`/#/chat/ ${ encodeURIComponent ( "websocket:chat-a" ) } ` ,
);
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
2026-10-07 15:19:55 +08:00
await waitFor (() => expect ( document . title ). toBe ( "Active after reload" ));
2026-06-02 11:29:18 +08:00
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
expect (
within ( sidebar ). getByRole ( "button" , { name : /^Active after reload$/ }),
). toBeInTheDocument ();
expect ( window . location . hash ). toBe (
`#/chat/ ${ encodeURIComponent ( "websocket:chat-a" ) } ` ,
);
});
2026-05-08 15:31:52 +00:00
it ( "opens the settings view from the sidebar footer" , async () => {
2026-09-10 11:10:51 +08:00
mockFetchRoutes ({ "/api/settings" : baseSettingsPayload () });
2026-04-25 18:05:06 +00:00
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
2026-09-10 11:10:51 +08:00
fireEvent . click ( within ( screen . getByRole ( "navigation" , { name : "Sidebar navigation" }))
. getByRole ( "button" , { name : "Settings" }));
const nav = await screen . findByRole ( "navigation" , { name : "Settings sections" });
for ( const name of [ "Overview" , "Appearance" , "Models" , "Capabilities" , "System" , "Advanced" , "About" ]) {
expect ( within ( nav ). getByRole ( "button" , { name , exact : true })). toBeInTheDocument ();
}
fireEvent . click ( within ( nav ). getByRole ( "button" , { name : "Appearance" , exact : true }));
expect ( await screen . findByRole ( "switch" , { name : "Brand logos" })). toBeInTheDocument ();
fireEvent . click ( within ( nav ). getByRole ( "button" , { name : "Models" , exact : true }));
expect ( await screen . findByText ( "Model presets" )). toBeInTheDocument ();
fireEvent . click ( within ( nav ). getByRole ( "button" , { name : "Capabilities" , exact : true }));
2026-05-24 13:38:37 +08:00
expect ( screen . getByRole ( "switch" , { name : "Image generation" })). toBeInTheDocument ();
2026-09-10 11:10:51 +08:00
fireEvent . click ( within ( nav ). getByRole ( "button" , { name : "About" , exact : true }));
expect ( await screen . findByRole ( "button" , { name : "Check for updates" })). toBeInTheDocument ();
2026-04-25 18:05:06 +00:00
});
2026-05-06 14:15:36 +00:00
2026-06-02 11:29:18 +08:00
it ( "restores the settings section from the URL hash after a page reload" , async () => {
2026-06-06 19:49:33 +08:00
mockFetchRoutes ({ "/api/settings" : baseSettingsPayload () });
2026-06-09 01:08:49 +08:00
window . history . replaceState ( null , "" , "/#/settings?section=voice" );
2026-06-02 11:29:18 +08:00
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
2026-09-10 11:10:51 +08:00
expect ( await screen . findByRole ( "dialog" , { name : "Transcription" })). toBeInTheDocument ();
2026-06-09 01:08:49 +08:00
expect ( window . location . hash ). toBe ( "#/settings?section=voice" );
2026-06-02 11:29:18 +08:00
});
2026-08-05 13:24:45 +08:00
it ( "keeps the backend timezone without writing settings on mount" , async () => {
const initialSettings = baseSettingsPayload ();
mockFetchRoutes ({
"/api/settings" : initialSettings ,
});
window . history . replaceState ( null , "" , "/#/settings?section=runtime" );
render (< App />);
expect ( await screen . findByText ( "UTC" )). toBeInTheDocument ();
expect (
2026-08-10 15:43:54 +08:00
requestMutationSpy . mock . calls . some (([ action ]) => action === "settings.agent.update" ),
). toBe ( false );
2026-10-09 17:47:21 +08:00
expect ( screen . queryByRole ( "heading" , { name : "Region and timezone" })). not . toBeInTheDocument ();
2026-08-05 13:24:45 +08:00
expect (
screen . queryByText ( "Used for schedules and time-aware replies." ),
). not . toBeInTheDocument ();
expect ( screen . queryByRole ( "button" , { name : "Save" })). not . toBeInTheDocument ();
expect ( screen . queryByPlaceholderText ( "Search timezone" )). not . toBeInTheDocument ();
const systemSection = screen . getByRole ( "heading" , { name : "System" }). closest ( "section" );
expect ( systemSection ). not . toBeNull ();
const system = within ( systemSection as HTMLElement );
2026-09-10 11:10:51 +08:00
expect ( system . getByText ( "Timezone" )). toBeInTheDocument ();
expect ( within ( screen . getByRole ( "complementary" )). getByRole ( "button" , { name : "Restart" , exact : true })). toBeInTheDocument ();
2026-08-05 13:24:45 +08:00
expect (
system . queryByText ( "Restart nanobot to apply runtime changes." ),
). not . toBeInTheDocument ();
});
2026-07-13 13:11:46 +08:00
it ( "falls back to Overview for the retired Files settings URL" , async () => {
mockFetchRoutes ({ "/api/settings" : baseSettingsPayload () });
window . history . replaceState ( null , "" , "/#/settings?section=files" );
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
2026-07-24 00:55:06 +08:00
expect (
await screen . findByRole ( "navigation" , { name : "Settings sections" }),
). toBeInTheDocument ();
expect ( screen . queryByRole ( "heading" , { name : "Overview" })). not . toBeInTheDocument ();
2026-07-13 13:11:46 +08:00
});
2026-06-02 11:29:18 +08:00
it ( "updates the URL hash when switching settings sections" , async () => {
2026-06-06 19:49:33 +08:00
mockFetchRoutes ({ "/api/settings" : baseSettingsPayload () });
2026-06-02 11:29:18 +08:00
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Settings" }));
2026-07-24 00:55:06 +08:00
expect (
await screen . findByRole ( "navigation" , { name : "Settings sections" }),
). toBeInTheDocument ();
2026-06-02 11:29:18 +08:00
expect ( window . location . hash ). toBe ( "#/settings" );
const settingsNav = screen . getByRole ( "navigation" , { name : "Settings sections" });
2026-08-01 22:36:23 +08:00
const overviewButton = within ( settingsNav ). getByRole ( "button" , {
name : "Overview" ,
exact : true ,
});
const modelsButton = within ( settingsNav ). getByRole ( "button" , {
name : "Models" ,
exact : true ,
});
const settingsHighlight = within ( settingsNav ). getByTestId (
"settings-selection-highlight" ,
);
expect ( overviewButton ). toHaveAttribute ( "aria-current" , "page" );
expect ( overviewButton ). not . toHaveClass ( "bg-sidebar-accent" );
2026-10-06 00:46:38 +08:00
expect ( overviewButton ). toHaveClass ( "transition-[color,background-color]" );
2026-08-01 22:36:23 +08:00
expect ( settingsHighlight ). toHaveAttribute ( "data-active-id" , "overview" );
fireEvent . click ( modelsButton );
2026-06-02 11:29:18 +08:00
2026-07-24 00:55:06 +08:00
expect ( await screen . findByText ( "Model presets" )). toBeInTheDocument ();
expect ( screen . queryByRole ( "heading" , { name : "Models" })). not . toBeInTheDocument ();
2026-06-02 11:29:18 +08:00
expect ( window . location . hash ). toBe ( "#/settings?section=models" );
2026-08-01 22:36:23 +08:00
expect ( modelsButton ). toHaveAttribute ( "aria-current" , "page" );
expect ( settingsHighlight ). toHaveAttribute ( "data-active-id" , "models" );
2026-06-09 01:08:49 +08:00
2026-08-01 22:36:23 +08:00
const voiceButton = within ( settingsNav ). getByRole ( "button" , {
2026-09-10 11:10:51 +08:00
name : "Capabilities" ,
2026-08-01 22:36:23 +08:00
exact : true ,
});
fireEvent . click ( voiceButton );
2026-06-09 01:08:49 +08:00
2026-09-10 11:10:51 +08:00
expect ( await screen . findByRole ( "switch" , { name : "Transcription" })). toBeInTheDocument ();
expect ( window . location . hash ). toBe ( "#/settings?section=capabilities" );
2026-08-01 22:36:23 +08:00
expect ( voiceButton ). toHaveAttribute ( "aria-current" , "page" );
2026-09-10 11:10:51 +08:00
expect ( settingsHighlight ). toHaveAttribute ( "data-active-id" , "capabilities" );
2026-06-02 11:29:18 +08:00
});
2026-07-28 03:17:55 +08:00
it ( "transitions between Apps and Skills without replacing the sidebar" , async () => {
2026-06-06 19:49:33 +08:00
mockFetchRoutes ({
"/api/settings" : baseSettingsPayload (),
"/api/settings/cli-apps" : { apps : [], installed_count : 0 , catalog_updated_at : "2026-04-18" },
"/api/settings/mcp-presets" : { presets : [], installed_count : 0 },
2026-07-28 03:17:55 +08:00
"/api/webui/skills" : { skills : [] },
2026-06-06 19:49:33 +08:00
});
2026-05-25 20:07:02 +08:00
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
const appsButton = within ( sidebar ). getByRole ( "button" , { name : "Apps" });
fireEvent . click ( appsButton );
expect ( await screen . findByRole ( "heading" , { name : "Apps" })). toBeInTheDocument ();
2026-08-05 13:24:45 +08:00
expect ( screen . queryByText ( "Add tools to nanobot, then @ them in chat." )). not . toBeInTheDocument ();
2026-05-25 20:07:02 +08:00
expect ( screen . getByRole ( "navigation" , { name : "Sidebar navigation" })). toBeInTheDocument ();
expect ( screen . queryByRole ( "navigation" , { name : "Settings sections" })). not . toBeInTheDocument ();
expect ( within ( sidebar ). getByRole ( "button" , { name : "Apps" })). toHaveAttribute (
"aria-current" ,
"page" ,
);
2026-08-01 22:36:23 +08:00
expect ( within ( sidebar ). getByTestId ( "actions-selection-highlight" )). toHaveAttribute (
"data-active-id" ,
"utility:apps" ,
);
expect ( within ( sidebar ). queryAllByRole ( "button" , { current : "page" })). toHaveLength ( 1 );
2026-07-28 03:17:55 +08:00
expect ( screen . getByTestId ( "settings-section-transition" )). toHaveAttribute (
"data-settings-section" ,
"apps" ,
);
expect ( screen . getByTestId ( "settings-section-transition" )). toHaveClass (
"animate-in" ,
"fade-in-0" ,
"slide-in-from-bottom-1" ,
"duration-200" ,
"motion-reduce:animate-none" ,
);
2026-10-07 15:19:55 +08:00
expect ( document . title ). toBe ( "Apps" );
2026-07-28 03:17:55 +08:00
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Skills" }));
expect ( await screen . findByRole ( "heading" , { name : "Skills" })). toBeInTheDocument ();
await waitFor (() => {
expect ( screen . getByTestId ( "settings-section-transition" )). toHaveAttribute (
"data-settings-section" ,
"skills" ,
);
});
expect ( screen . getByRole ( "navigation" , { name : "Sidebar navigation" })). toBeInTheDocument ();
expect ( within ( sidebar ). getByRole ( "button" , { name : "Skills" })). toHaveAttribute (
"aria-current" ,
"page" ,
);
2026-08-01 22:36:23 +08:00
expect ( within ( sidebar ). getByTestId ( "actions-selection-highlight" )). toHaveAttribute (
"data-active-id" ,
"utility:skills" ,
);
2026-10-07 15:19:55 +08:00
expect ( document . title ). toBe ( "Skills" );
2026-05-25 20:07:02 +08:00
});
2026-05-12 22:27:22 +08:00
it ( "returns from settings to the blank start page when no session was active" , async () => {
2026-05-08 15:35:18 +00:00
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "First chat" ,
},
{
key : "websocket:chat-b" ,
channel : "websocket" ,
chatId : "chat-b" ,
createdAt : "2026-04-16T11:00:00Z" ,
updatedAt : "2026-04-16T11:00:00Z" ,
preview : "Second chat" ,
},
];
vi . stubGlobal (
"fetch" ,
vi . fn ( async ( input : RequestInfo | URL ) => {
2026-09-10 11:10:51 +08:00
if ( String ( input ) === "/api/settings" ) {
2026-05-08 15:35:18 +00:00
return {
ok : true ,
status : 200 ,
json : async () => ({
agent : {
model : "openai/gpt-4o" ,
provider : "openai" ,
resolved_provider : "openai" ,
has_api_key : true ,
2026-05-19 22:42:38 +08:00
model_preset : "default" ,
max_tokens : 8192 ,
context_window_tokens : 65536 ,
temperature : 0.1 ,
reasoning_effort : null ,
timezone : "UTC" ,
tool_hint_max_length : 40 ,
2026-05-08 15:35:18 +00:00
},
2026-05-19 22:42:38 +08:00
model_presets : [
{
name : "default" ,
label : "Default" ,
active : true ,
is_default : true ,
model : "openai/gpt-4o" ,
provider : "openai" ,
max_tokens : 8192 ,
context_window_tokens : 65536 ,
temperature : 0.1 ,
reasoning_effort : null ,
},
],
2026-05-08 15:35:18 +00:00
providers : [{ name : "openai" , label : "OpenAI" , configured : true }],
2026-05-09 06:48:26 +00:00
web_search : {
provider : "duckduckgo" ,
api_key_hint : null ,
base_url : null ,
2026-05-19 22:42:38 +08:00
max_results : 5 ,
timeout : 30 ,
2026-05-09 06:48:26 +00:00
providers : [
{ name : "duckduckgo" , label : "DuckDuckGo" , credential : "none" },
{ name : "brave" , label : "Brave Search" , credential : "api_key" },
],
},
2026-05-19 22:42:38 +08:00
web : {
enable : true ,
proxy : null ,
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 : [
{
name : "openrouter" ,
label : "OpenRouter" ,
configured : false ,
api_key_hint : null ,
api_base : null ,
default_api_base : "https://openrouter.ai/api/v1" ,
},
],
},
2026-05-08 15:35:18 +00:00
runtime : {
config_path : "/tmp/config.json" ,
2026-05-19 22:42:38 +08:00
workspace_path : "/tmp/workspace" ,
gateway_host : "127.0.0.1" ,
gateway_port : 18790 ,
heartbeat : {
enabled : true ,
interval_s : 1800 ,
},
dream : {
schedule : "every 2h" ,
},
unified_session : false ,
},
advanced : {
restrict_to_workspace : false ,
2026-05-29 03:42:53 +08:00
webui_allow_local_service_access : true ,
webui_default_access_mode : "default" ,
private_service_protection_enabled : true ,
2026-05-19 22:42:38 +08:00
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-19 22:42:38 +08:00
exec_path_append_set : false ,
2026-05-08 15:35:18 +00:00
},
requires_restart : false ,
}),
};
}
return { ok : false , status : 404 , json : async () => ({}) };
}),
);
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
2026-07-24 10:21:02 +08:00
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "New topic" }));
2026-05-08 15:35:18 +00:00
await waitFor (() => expect ( document . title ). toBe ( "nanobot" ));
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Settings" }));
2026-07-24 00:55:06 +08:00
expect (
await screen . findByRole ( "navigation" , { name : "Settings sections" }),
). toBeInTheDocument ();
2026-05-08 15:35:18 +00:00
fireEvent . click ( screen . getByRole ( "button" , { name : "Back to chat" }));
2026-05-12 22:27:22 +08:00
await waitFor (() => expect ( document . title ). toBe ( "nanobot" ));
2026-05-29 03:42:53 +08:00
expect ( screen . getByText ( HERO_GREETING_PATTERN )). toBeInTheDocument ();
2026-05-08 15:35:18 +00:00
});
2026-05-19 22:42:38 +08:00
it ( "filters sessions in the centered search dialog" , async () => {
2026-05-06 14:15:36 +00:00
mockSessions = [
{
key : "websocket:chat-alpha" ,
channel : "websocket" ,
chatId : "chat-alpha" ,
createdAt : new Date (). toISOString (),
updatedAt : new Date (). toISOString (),
2026-05-13 16:39:07 +00:00
title : "Q2 roadmap" ,
2026-05-06 14:15:36 +00:00
preview : "Project planning notes" ,
},
{
key : "websocket:chat-beta" ,
channel : "websocket" ,
chatId : "chat-beta" ,
createdAt : "2026-04-15T10:00:00Z" ,
updatedAt : "2026-04-15T10:00:00Z" ,
preview : "Travel ideas" ,
},
];
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
2026-05-13 16:39:07 +00:00
expect ( within ( sidebar ). getByText ( "Q2 roadmap" )). toBeInTheDocument ();
2026-05-06 14:15:36 +00:00
expect ( within ( sidebar ). getByText ( "Travel ideas" )). toBeInTheDocument ();
2026-07-24 10:21:02 +08:00
const newChatButton = within ( sidebar ). getByRole ( "button" , { name : "New topic" });
2026-05-19 22:42:38 +08:00
const searchButton = within ( sidebar ). getByRole ( "button" , { name : "Search" });
expect (
2026-09-10 11:10:51 +08:00
searchButton . compareDocumentPosition ( newChatButton ) &
2026-05-19 22:42:38 +08:00
Node . DOCUMENT_POSITION_FOLLOWING ,
). toBeTruthy ();
2026-05-06 14:15:36 +00:00
2026-05-19 22:42:38 +08:00
fireEvent . click ( searchButton );
const dialog = await screen . findByRole ( "dialog" , { name : "Search" });
expect ( dialog ). toHaveClass ( "origin-center" );
expect ( dialog . className ). not . toContain ( "translate-x" );
expect ( dialog . className ). not . toContain ( "translate-y" );
2026-05-24 13:38:37 +08:00
expect ( dialog . querySelector ( "kbd" )). toBeNull ();
2026-05-19 22:42:38 +08:00
expect ( within ( dialog ). getByText ( "Q2 roadmap" )). toBeInTheDocument ();
expect ( within ( dialog ). getByText ( "Travel ideas" )). toBeInTheDocument ();
expect ( within ( dialog ). queryByText ( "websocket" )). not . toBeInTheDocument ();
expect ( within ( dialog ). queryByText ( "#1" )). not . toBeInTheDocument ();
fireEvent . change ( within ( dialog ). getByRole ( "textbox" , { name : "Search" }), {
2026-05-13 16:39:07 +00:00
target : { value : "planning" },
2026-05-06 14:15:36 +00:00
});
2026-05-19 22:42:38 +08:00
expect ( within ( dialog ). getByText ( "Q2 roadmap" )). toBeInTheDocument ();
expect ( within ( dialog ). queryByText ( "Travel ideas" )). not . toBeInTheDocument ();
expect ( within ( sidebar ). getByText ( "Travel ideas" )). toBeInTheDocument ();
2026-05-13 16:39:07 +00:00
2026-05-19 22:42:38 +08:00
fireEvent . change ( within ( dialog ). getByRole ( "textbox" , { name : "Search" }), {
2026-05-13 16:39:07 +00:00
target : { value : "road q2" },
});
2026-05-19 22:42:38 +08:00
expect ( within ( dialog ). getByText ( "Q2 roadmap" )). toBeInTheDocument ();
expect ( within ( dialog ). queryByText ( "Travel ideas" )). not . toBeInTheDocument ();
fireEvent . click ( within ( dialog ). getByRole ( "button" , { name : /Q2 roadmap/ }));
await waitFor (() =>
expect ( screen . queryByRole ( "dialog" , { name : "Search" })). not . toBeInTheDocument (),
);
2026-05-06 14:15:36 +00:00
});
2026-08-12 14:45:12 +08:00
it ( "keeps panes adjacent and orders tabs by their latest updated pane" , async () => {
mockSessions = [
{
key : "websocket:alpha" ,
channel : "websocket" ,
chatId : "alpha" ,
createdAt : "2026-08-01T10:00:00Z" ,
updatedAt : "2026-08-01T10:00:00Z" ,
title : "Alpha tab" ,
preview : "" ,
},
{
key : "websocket:alpha-child" ,
channel : "websocket" ,
chatId : "alpha-child" ,
createdAt : "2026-08-05T10:00:00Z" ,
updatedAt : "2026-08-05T10:00:00Z" ,
title : "Alpha child" ,
preview : "" ,
},
{
key : "websocket:beta" ,
channel : "websocket" ,
chatId : "beta" ,
createdAt : "2026-08-04T10:00:00Z" ,
updatedAt : "2026-08-04T10:00:00Z" ,
title : "Beta tab" ,
preview : "" ,
},
];
vi . stubGlobal ( "fetch" , vi . fn (). mockImplementation ( async ( url : string | URL | Request ) => {
if ( String ( url ) === "/api/webui/sidebar-state" ) {
return {
ok : true ,
json : async () => ({
workbench : {
version : 1 ,
tabs : {
"tab:websocket:alpha" : {
explicit : true ,
title : "Alpha tab" ,
paneKeys : [ "websocket:alpha" , "websocket:alpha-child" ],
layout : "columns" ,
},
"tab:websocket:beta" : {
explicit : false ,
title : null ,
paneKeys : [ "websocket:beta" ],
layout : "columns" ,
},
},
},
}),
};
}
return { ok : false , status : 404 };
}));
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
2026-08-14 07:22:07 +09:00
const alphaTab = await within ( sidebar ). findByRole ( "button" , { name : "Group: Alpha tab" });
2026-08-12 14:45:12 +08:00
const betaTab = within ( sidebar ). getByRole ( "button" , { name : "Beta tab" });
expect ( alphaTab . compareDocumentPosition ( betaTab ) & Node . DOCUMENT_POSITION_FOLLOWING )
. toBeTruthy ();
const alphaGroup = alphaTab . closest ( "[data-sidebar-tab-group]" ) as HTMLElement ;
2026-08-14 17:03:11 +08:00
const alphaChild = within ( alphaGroup ). getByRole ( "button" , { name : "Alpha child" });
const alphaRoot = within ( alphaGroup ). getByRole ( "button" , { name : "Alpha tab" });
expect ( alphaChild . compareDocumentPosition ( alphaRoot ) & Node . DOCUMENT_POSITION_FOLLOWING )
. toBeTruthy ();
2026-08-12 14:45:12 +08:00
});
it ( "uses one active pane without workbench editing controls on mobile" , async () => {
vi . stubGlobal ( "matchMedia" , vi . fn (( query : string ) => ({
matches : query.includes ( "max-width: 767px" ),
media : query ,
onchange : null ,
addListener : vi.fn (),
removeListener : vi.fn (),
addEventListener : vi.fn (),
removeEventListener : vi.fn (),
dispatchEvent : vi.fn (),
})));
mockSessions = [
{
key : "websocket:alpha" ,
channel : "websocket" ,
chatId : "alpha" ,
createdAt : "2026-08-01T10:00:00Z" ,
updatedAt : "2026-08-01T10:00:00Z" ,
title : "Alpha tab" ,
preview : "" ,
},
{
key : "websocket:alpha-child" ,
channel : "websocket" ,
chatId : "alpha-child" ,
createdAt : "2026-08-05T10:00:00Z" ,
updatedAt : "2026-08-05T10:00:00Z" ,
title : "Alpha child" ,
preview : "" ,
},
];
window . history . replaceState (
null ,
"" ,
"/#/chat/websocket%3Aalpha-child" ,
);
vi . stubGlobal ( "fetch" , vi . fn (). mockImplementation ( async ( url : string | URL | Request ) => {
if ( String ( url ) === "/api/webui/sidebar-state" ) {
return {
ok : true ,
json : async () => ({
workbench : {
version : 1 ,
tabs : {
"tab:websocket:alpha" : {
explicit : true ,
title : "Alpha tab" ,
paneKeys : [ "websocket:alpha" , "websocket:alpha-child" ],
layout : "bsp" ,
},
},
},
}),
};
}
return { ok : false , status : 404 };
}));
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const grid = await screen . findByTestId ( "pane-grid" );
await waitFor (() => expect ( Array . from ( grid . children ). map (
( pane ) => pane . getAttribute ( "aria-label" ),
)). toEqual ([ "Alpha child" ]));
2026-10-09 17:47:21 +08:00
expect ( screen . queryByRole ( "button" , { name : "Layout" })). not . toBeInTheDocument ();
2026-08-12 14:45:12 +08:00
expect ( screen . queryByRole ( "button" , { name : "Add pane" })). not . toBeInTheDocument ();
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
fireEvent . pointerDown ( within ( sidebar ). getByRole ( "button" , {
name : "Alpha child pane actions" ,
}), { button : 0 , ctrlKey : false });
expect ( await screen . findByRole ( "menuitem" , { name : "Delete" })). toBeInTheDocument ();
expect ( screen . queryByRole ( "menuitem" , { name : "Remove" })). not . toBeInTheDocument ();
expect ( screen . queryByRole ( "menuitem" , { name : "Move to" })). not . toBeInTheDocument ();
});
it ( "materializes a singleton tab without linking it to another pane" , async () => {
mockSessions = [
{
key : "websocket:solo" ,
channel : "websocket" ,
chatId : "solo" ,
createdAt : "2026-08-05T10:00:00Z" ,
updatedAt : "2026-08-05T10:00:00Z" ,
title : "Solo pane" ,
preview : "" ,
},
{
key : "websocket:other" ,
channel : "websocket" ,
chatId : "other" ,
createdAt : "2026-08-04T10:00:00Z" ,
updatedAt : "2026-08-04T10:00:00Z" ,
title : "Other pane" ,
preview : "" ,
},
];
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
act (() => {
statusHandlers . forEach (( handler ) => handler ( "open" ));
});
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
2026-08-14 07:22:07 +09:00
expect ( within ( sidebar ). queryByRole ( "button" , { name : "Group: Solo pane" }))
2026-08-12 14:45:12 +08:00
. not . toBeInTheDocument ();
setSidebarStateSpy . mockClear ();
fireEvent . pointerDown ( within ( sidebar ). getByRole ( "button" , {
name : "Topic actions for Solo pane" ,
}), { button : 0 , ctrlKey : false });
fireEvent . click ( await screen . findByRole ( "menuitem" , { name : "Create group" }));
const tabButton = await within ( sidebar ). findByRole ( "button" , {
2026-08-14 07:22:07 +09:00
name : "Group: Solo pane" ,
2026-08-12 14:45:12 +08:00
});
const tabGroup = tabButton . closest ( "[data-sidebar-tab-group]" ) as HTMLElement ;
expect ( within ( tabGroup ). getByRole ( "list" , { name : "Panes in Solo pane" }))
. toBeInTheDocument ();
expect ( within ( tabGroup ). getAllByRole ( "button" , { name : "Solo pane" }))
. toHaveLength ( 1 );
2026-08-14 07:22:07 +09:00
expect ( within ( sidebar ). queryByRole ( "button" , { name : "Group: Other pane" }))
2026-08-12 14:45:12 +08:00
. not . toBeInTheDocument ();
await waitFor (() => expect ( setSidebarStateSpy ). toHaveBeenCalledWith (
expect . objectContaining ({
workbench : expect.objectContaining ({
tabs : expect.objectContaining ({
"tab:websocket:solo" : expect . objectContaining ({ explicit : true }),
}),
}),
}),
));
2026-08-14 06:51:38 +09:00
fireEvent . pointerDown ( within ( tabGroup ). getByRole ( "button" , {
name : "Topic actions for Solo pane" ,
}), { button : 0 , ctrlKey : false });
fireEvent . click ( await screen . findByRole ( "menuitem" , { name : "Rename" }));
const renameDialog = await screen . findByRole ( "dialog" , { name : "Rename group" });
expect ( within ( renameDialog ). getByText ( "Give this group a name." )). toBeInTheDocument ();
expect ( within ( renameDialog ). getByPlaceholderText ( "Group name" )). toHaveValue ( "Solo pane" );
2026-08-12 14:45:12 +08:00
});
it ( "restores a created pane group from gateway state after remount" , async () => {
mockSessions = [
{
key : "websocket:solo" ,
channel : "websocket" ,
chatId : "solo" ,
createdAt : "2026-08-05T10:00:00Z" ,
updatedAt : "2026-08-05T10:00:00Z" ,
title : "Solo pane" ,
preview : "" ,
},
{
key : "websocket:other" ,
channel : "websocket" ,
chatId : "other" ,
createdAt : "2026-08-04T10:00:00Z" ,
updatedAt : "2026-08-04T10:00:00Z" ,
title : "Other pane" ,
preview : "" ,
},
];
let persistedState : SidebarStatePayload | null = null ;
vi . stubGlobal ( "fetch" , vi . fn (). mockImplementation ( async ( url : string | URL | Request ) => {
if ( String ( url ) === "/api/webui/sidebar-state" ) {
return {
ok : true ,
json : async () => persistedState ?? {},
};
}
return { ok : false , status : 404 };
}));
setSidebarStateSpy . mockImplementation ( async ( state : SidebarStatePayload ) => {
persistedState = state ;
return state ;
});
const firstRender = render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
act (() => {
statusHandlers . forEach (( handler ) => handler ( "open" ));
});
const firstSidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
fireEvent . pointerDown ( within ( firstSidebar ). getByRole ( "button" , {
name : "Topic actions for Solo pane" ,
}), { button : 0 , ctrlKey : false });
fireEvent . click ( await screen . findByRole ( "menuitem" , { name : "Create group" }));
await waitFor (() => expect ( persistedState ? . workbench . tabs [ "tab:websocket:solo" ])
. toEqual ( expect . objectContaining ({ explicit : true })));
firstRender . unmount ();
connectSpy . mockClear ();
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const secondSidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
2026-08-14 07:22:07 +09:00
expect ( await within ( secondSidebar ). findByRole ( "button" , { name : "Group: Solo pane" }))
2026-08-12 14:45:12 +08:00
. toBeInTheDocument ();
});
it ( "keeps panes and layout scoped to the current topic tab" , async () => {
vi . stubGlobal ( "matchMedia" , vi . fn (( query : string ) => ({
matches : false ,
media : query ,
onchange : null ,
addListener : vi.fn (),
removeListener : vi.fn (),
addEventListener : vi.fn (),
removeEventListener : vi.fn (),
dispatchEvent : vi.fn (),
})));
createChatSpy . mockResolvedValueOnce ( "chat-pane" );
mockSessions = [
{
key : "websocket:chat-alpha" ,
channel : "websocket" ,
chatId : "chat-alpha" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
title : "Alpha" ,
preview : "Alpha notes" ,
},
{
key : "websocket:chat-beta" ,
channel : "websocket" ,
chatId : "chat-beta" ,
createdAt : "2026-04-16T11:00:00Z" ,
updatedAt : "2026-04-16T11:00:00Z" ,
title : "Beta" ,
preview : "Beta notes" ,
},
];
window . history . replaceState (
null ,
"" ,
"/#/chat/websocket%3Achat-alpha" ,
);
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const grid = await screen . findByTestId ( "pane-grid" );
expect ( Array . from ( grid . children ). map (( pane ) => pane . getAttribute ( "aria-label" )))
. toEqual ([ "Alpha" ]);
2026-10-09 17:47:21 +08:00
expect ( screen . queryByRole ( "button" , { name : "Layout" }))
2026-08-12 14:45:12 +08:00
. not . toBeInTheDocument ();
fireEvent . click ( screen . getByRole ( "button" , { name : "Add pane" }));
expect ( screen . queryByRole ( "dialog" , { name : "Search" })). not . toBeInTheDocument ();
await waitFor (() => expect ( createChatSpy ). toHaveBeenCalledTimes ( 1 ));
await waitFor (() => expect ( grid . children ). toHaveLength ( 2 ));
2026-10-09 17:47:21 +08:00
expect ( screen . getByRole ( "button" , { name : "Layout" })). toBeInTheDocument ();
2026-08-12 14:45:12 +08:00
expect ( window . location . hash ). toBe ( "#/chat/websocket%3Achat-pane" );
expect ( Array . from ( grid . children ). map (( pane ) => pane . getAttribute ( "aria-label" )))
. toEqual ([ "Alpha" , "New topic" ]);
const activeComposer = screen . getByTestId ( "active-pane-composer" );
2026-08-18 18:28:19 +08:00
const paneInput = within ( activeComposer ). getByRole ( "textbox" , {
2026-08-12 14:45:12 +08:00
name : "Message New topic" ,
});
expect ( paneInput ). toHaveClass ( "min-h-[50px]" );
fireEvent . change ( paneInput , { target : { value : "route this to the new pane" } });
fireEvent . keyDown ( paneInput , { key : "Enter" });
await waitFor (() => expect ( sendMessageSpy ). toHaveBeenCalled ());
expect ( sendMessageSpy . mock . calls . at ( - 1 ) ? .[ 0 ]). toBe ( "chat-pane" );
2026-10-09 17:47:21 +08:00
fireEvent . pointerDown ( screen . getByRole ( "button" , { name : "Layout" }), {
2026-08-12 14:45:12 +08:00
button : 0 ,
ctrlKey : false ,
});
fireEvent . click ( screen . getByRole ( "menuitemradio" , { name : "Rows" }));
expect ( grid ). toHaveAttribute ( "data-layout" , "rows" );
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
const paneTopicButton = within ( sidebar )
. getAllByRole ( "button" , { name : "New topic" })
. find (( button ) => button . closest ( "[data-sidebar-pane]" ));
expect ( paneTopicButton ). toBeDefined ();
expect ( paneTopicButton ? . closest ( "[data-sidebar-pane]" ))
. toHaveAttribute ( "data-sidebar-pane" , "websocket:chat-pane" );
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Beta" }));
await waitFor (() => {
const nextGrid = screen . getByTestId ( "pane-grid" );
expect ( Array . from ( nextGrid . children ). map (( pane ) => pane . getAttribute ( "aria-label" )))
. toEqual ([ "Beta" ]);
expect ( nextGrid ). toHaveAttribute ( "data-layout" , "columns" );
});
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Alpha" }));
await waitFor (() => {
const restoredGrid = screen . getByTestId ( "pane-grid" );
expect ( Array . from ( restoredGrid . children ). map (( pane ) => pane . getAttribute ( "aria-label" )))
. toEqual ([ "Alpha" , "New topic" ]);
expect ( restoredGrid ). toHaveAttribute ( "data-layout" , "rows" );
});
2026-08-29 11:44:03 +08:00
const alphaGroupButton = within ( sidebar ). getByRole ( "button" , {
name : "Group: Alpha" ,
});
const alphaGroup = alphaGroupButton . closest ( "[data-sidebar-tab-group]" ) as HTMLElement ;
fireEvent . pointerDown ( within ( alphaGroup ). getByLabelText ( "Topic actions for Alpha" ), {
button : 0 ,
ctrlKey : false ,
});
fireEvent . click ( await screen . findByRole ( "menuitem" , { name : "Rename" }));
const renameDialog = await screen . findByRole ( "dialog" , { name : "Rename group" });
fireEvent . change ( within ( renameDialog ). getByPlaceholderText ( "Group name" ), {
target : { value : "Research" },
});
fireEvent . click ( within ( renameDialog ). getByRole ( "button" , { name : "Save" }));
expect ( await within ( sidebar ). findByRole ( "button" , { name : "Group: Research" }))
. toBeInTheDocument ();
2026-08-12 14:45:12 +08:00
fireEvent . pointerDown ( within ( sidebar ). getByRole ( "button" , {
name : "New topic pane actions" ,
}), { button : 0 , ctrlKey : false });
fireEvent . click ( screen . getByRole ( "menuitem" , {
name : "Remove" ,
}));
await waitFor (() => expect ( screen . getByTestId ( "pane-grid" ). children ). toHaveLength ( 1 ));
2026-08-29 11:44:03 +08:00
const researchGroup = within ( sidebar ). getByRole ( "button" , {
name : "Group: Research" ,
}). closest ( "[data-sidebar-tab-group]" ) as HTMLElement ;
expect ( within ( researchGroup ). getByRole ( "list" , { name : "Panes in Research" }))
. toBeInTheDocument ();
expect ( within ( researchGroup ). getByRole ( "button" , { name : "Alpha" }))
. toBeInTheDocument ();
2026-08-12 14:45:12 +08:00
expect ( within ( sidebar ). getAllByRole ( "button" , { name : "New topic" })). toHaveLength ( 2 );
});
2026-08-29 11:44:03 +08:00
it ( "keeps a named group and its remaining pane active after deleting a pane" , async () => {
mockSessions = [
{
key : "websocket:new-pane" ,
channel : "websocket" ,
chatId : "new-pane" ,
createdAt : "2026-08-05T12:00:00Z" ,
updatedAt : "2026-08-05T12:00:00Z" ,
title : "New topic" ,
preview : "" ,
},
{
key : "websocket:unrelated" ,
channel : "websocket" ,
chatId : "unrelated" ,
createdAt : "2026-08-05T11:00:00Z" ,
updatedAt : "2026-08-05T11:00:00Z" ,
title : "Unrelated" ,
preview : "" ,
},
{
key : "websocket:alpha" ,
channel : "websocket" ,
chatId : "alpha" ,
createdAt : "2026-08-05T10:00:00Z" ,
updatedAt : "2026-08-05T10:00:00Z" ,
title : "Alpha" ,
preview : "" ,
},
];
window . history . replaceState ( null , "" , "/#/chat/websocket%3Anew-pane" );
vi . stubGlobal ( "fetch" , vi . fn (). mockImplementation ( async ( url : string | URL | Request ) => {
if ( String ( url ) === "/api/webui/sidebar-state" ) {
return {
ok : true ,
json : async () => ({
workbench : {
version : 1 ,
tabs : {
"tab:websocket:alpha" : {
explicit : false ,
title : "Research" ,
paneKeys : [ "websocket:alpha" , "websocket:new-pane" ],
layoutPaneKeys : [ "websocket:alpha" , "websocket:new-pane" ],
layout : "columns" ,
splitRatios : [],
},
},
},
}),
};
}
return { ok : false , status : 404 };
}));
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
expect ( await within ( sidebar ). findByRole ( "button" , { name : "Group: Research" }))
. toBeInTheDocument ();
fireEvent . pointerDown ( within ( sidebar ). getByRole ( "button" , {
name : "New topic pane actions" ,
}), { button : 0 , ctrlKey : false });
fireEvent . click ( await screen . findByRole ( "menuitem" , { name : "Delete" }));
expect ( await screen . findByText ( "Delete this topic?" )). toBeInTheDocument ();
fireEvent . click ( screen . getByRole ( "button" , { name : "Delete" }));
await waitFor (() => expect ( deleteChatSpy ). toHaveBeenCalledWith ( "websocket:new-pane" ));
await waitFor (() => expect ( window . location . hash ). toBe ( "#/chat/websocket%3Aalpha" ));
expect ( within ( sidebar ). getByRole ( "button" , { name : "Group: Research" }))
. toBeInTheDocument ();
expect ( screen . getByTestId ( "pane-grid" ). children ). toHaveLength ( 1 );
expect ( screen . getByTestId ( "pane-grid" ). firstElementChild )
. toHaveAttribute ( "aria-label" , "Alpha" );
}, 15 _000 );
2026-05-22 01:55:37 +08:00
it ( "opens search from the keyboard shortcut" , async () => {
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "Existing chat" ,
},
];
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
fireEvent . keyDown ( window , { key : "k" , metaKey : true });
const dialog = await screen . findByRole ( "dialog" , { name : "Search" });
expect ( within ( dialog ). queryByText ( "Global actions" )). not . toBeInTheDocument ();
expect ( within ( dialog ). getByText ( "Existing chat" )). toBeInTheDocument ();
const textbox = within ( dialog ). getByRole ( "textbox" , { name : "Search" });
fireEvent . change ( textbox , { target : { value : "missing" } });
expect ( within ( dialog ). queryByText ( "Existing chat" )). not . toBeInTheDocument ();
fireEvent . change ( textbox , { target : { value : "existing" } });
expect ( within ( dialog ). getByText ( "Existing chat" )). toBeInTheDocument ();
fireEvent . keyDown ( textbox , { key : "Enter" });
await waitFor (() =>
expect ( screen . queryByRole ( "dialog" , { name : "Search" })). not . toBeInTheDocument (),
);
expect ( createChatSpy ). not . toHaveBeenCalled ();
});
2026-09-10 11:10:51 +08:00
it . each ([
[ "apps" , "1" , "Digit1" , true ],
[ "skills" , "2" , "Digit2" , true ],
[ "automations" , "3" , "Digit3" , true ],
[ "settings" , "," , "Comma" , false ],
])( "opens %s using its sidebar shortcut" , async ( route , key , code , shiftKey ) => {
mockFetchRoutes ({ "/api/settings" : baseSettingsPayload () });
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
fireEvent . keyDown ( window , { key , code , shiftKey , ctrlKey : true });
await waitFor (() => expect ( window . location . hash ). toContain ( "#/" + route ));
});
2026-06-04 11:03:06 +08:00
it . each ([
[ "Command" , { metaKey : true }],
[ "Control" , { ctrlKey : true }],
])( "starts a new chat from the %s keyboard shortcut" , async ( _label , modifier ) => {
2026-06-04 06:47:50 +08:00
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "Existing chat" ,
},
];
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
2026-06-04 11:03:06 +08:00
fireEvent . keyDown ( window , { key : "O" , shiftKey : true , ... modifier });
2026-06-04 06:47:50 +08:00
expect ( window . location . hash ). toBe ( "#/new" );
});
2026-06-04 11:03:06 +08:00
it ( "closes search when starting a new chat from the keyboard shortcut" , async () => {
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "Existing chat" ,
},
];
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
fireEvent . keyDown ( window , { key : "k" , metaKey : true });
expect ( await screen . findByRole ( "dialog" , { name : "Search" })). toBeInTheDocument ();
fireEvent . keyDown ( window , { key : "O" , shiftKey : true , metaKey : true });
await waitFor (() =>
expect ( screen . queryByRole ( "dialog" , { name : "Search" })). not . toBeInTheDocument (),
);
expect ( window . location . hash ). toBe ( "#/new" );
});
2026-09-10 11:10:51 +08:00
it ( "exposes the new chat keyboard shortcut in the sidebar tooltip" , async () => {
2026-06-04 11:03:06 +08:00
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
2026-07-24 10:21:02 +08:00
const newChatButton = within ( sidebar ). getByRole ( "button" , { name : "New topic" });
2026-09-10 11:10:51 +08:00
expect ( newChatButton ). toHaveTextContent ( "" );
await userEvent . setup (). hover ( newChatButton );
const tooltip = await screen . findByRole ( "tooltip" );
expect ( tooltip ). toHaveTextContent ( "New topic" );
expect ( tooltip . querySelector ( "kbd" )). toHaveTextContent ( "Ctrl+Shift+O" );
2026-06-04 13:54:52 +08:00
expect ( newChatButton ). toHaveAttribute (
"aria-keyshortcuts" ,
"Meta+Shift+O Control+Shift+O" ,
);
});
2026-09-10 11:10:51 +08:00
it ( "uses macOS shortcut glyphs in the sidebar tooltip" , async () => {
2026-06-04 13:54:52 +08:00
setNavigatorPlatform ( "MacIntel" );
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
2026-09-10 11:10:51 +08:00
await userEvent . setup (). hover ( within ( sidebar ). getByRole ( "button" , { name : "New topic" }));
const tooltip = await screen . findByRole ( "tooltip" );
expect ( tooltip ). toHaveTextContent ( "New topic" );
expect ( tooltip . querySelector ( "kbd" )). toHaveTextContent ( "⌘⇧O" );
2026-06-04 11:03:06 +08:00
});
2026-05-22 01:55:37 +08:00
it ( "keeps large sidebars light while search still covers every chat" , async () => {
mockSessions = Array . from ({ length : 170 }, ( _ , index ) => {
const chatId = `chat- ${ index } ` ;
return {
key : `websocket: ${ chatId } ` ,
channel : "websocket" as const ,
chatId ,
createdAt : new Date ( Date . UTC ( 2026 , 3 , 16 , 12 , 0 - index )). toISOString (),
updatedAt : new Date ( Date . UTC ( 2026 , 3 , 16 , 12 , 0 - index )). toISOString (),
title : index === 169 ? "Hidden target" : `Bulk chat ${ index } ` ,
preview : "" ,
};
});
render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
await waitFor (() =>
expect ( within ( sidebar ). getByRole ( "button" , { name : "Bulk chat 0" })). toBeInTheDocument (),
);
expect ( within ( sidebar ). queryByText ( "Hidden target" )). not . toBeInTheDocument ();
expect ( within ( sidebar ). getByRole ( "button" , { name : "Show 10 more" })). toBeInTheDocument ();
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "Search" }));
const dialog = await screen . findByRole ( "dialog" , { name : "Search" });
fireEvent . change ( within ( dialog ). getByRole ( "textbox" , { name : "Search" }), {
target : { value : "hidden" },
});
expect ( within ( dialog ). getByText ( "Hidden target" )). toBeInTheDocument ();
});
2026-05-06 14:15:36 +00:00
it ( "opens a blank start page without creating an empty chat" , async () => {
mockSessions = [
{
key : "websocket:chat-a" ,
channel : "websocket" ,
chatId : "chat-a" ,
createdAt : "2026-04-16T10:00:00Z" ,
updatedAt : "2026-04-16T10:00:00Z" ,
preview : "Existing chat" ,
},
];
const matchMedia = vi . fn (). mockImplementation (( query : string ) => ({
matches : query.includes ( "1024px" ),
media : query ,
onchange : null ,
addListener : vi.fn (),
removeListener : vi.fn (),
addEventListener : vi.fn (),
removeEventListener : vi.fn (),
dispatchEvent : vi.fn (),
}));
vi . stubGlobal ( "matchMedia" , matchMedia );
const { container } = render (< App />);
await waitFor (() => expect ( connectSpy ). toHaveBeenCalled ());
fireEvent . click ( screen . getByRole ( "button" , { name : "Toggle theme from header" }));
expect ( toggleThemeSpy ). toHaveBeenCalledTimes ( 1 );
2026-09-10 11:10:51 +08:00
fireEvent . keyDown ( screen . getByRole ( "separator" , { name : "Resize sidebar" }), { key : "Enter" });
2026-05-29 03:42:53 +08:00
const sidebarAside = container . querySelector ( "aside.lg\\:block" ) as HTMLElement ;
await waitFor (() => expect ( sidebarAside . style . width ). toBe ( "56px" ));
2026-05-06 14:15:36 +00:00
2026-07-24 10:21:02 +08:00
expect ( screen . queryByRole ( "button" , { name : "Start a new topic" })). not . toBeInTheDocument ();
2026-05-22 00:31:55 +08:00
const rail = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
2026-07-24 10:21:02 +08:00
expect ( within ( rail ). getByRole ( "button" , { name : "New topic" })). toBeInTheDocument ();
2026-05-22 00:31:55 +08:00
expect ( within ( rail ). getByRole ( "button" , { name : "Search" })). toBeInTheDocument ();
2026-05-29 03:42:53 +08:00
expect ( within ( rail ). queryByRole ( "button" , { name : "View" })). not . toBeInTheDocument ();
2026-05-22 00:31:55 +08:00
expect ( within ( rail ). queryByText ( "Existing chat" )). not . toBeInTheDocument ();
fireEvent . click ( within ( rail ). getByRole ( "button" , { name : "Toggle sidebar" }));
2026-05-29 03:42:53 +08:00
await waitFor (() => expect ( sidebarAside . style . width ). toBe ( "272px" ));
2026-05-06 14:15:36 +00:00
const sidebar = screen . getByRole ( "navigation" , { name : "Sidebar navigation" });
2026-07-24 10:21:02 +08:00
fireEvent . click ( within ( sidebar ). getByRole ( "button" , { name : "New topic" }));
2026-05-06 14:15:36 +00:00
expect ( createChatSpy ). not . toHaveBeenCalled ();
2026-05-29 03:42:53 +08:00
expect ( screen . getByText ( HERO_GREETING_PATTERN )). toBeInTheDocument ();
2026-07-24 10:21:02 +08:00
expect ( screen . queryByRole ( "button" , { name : "Start a new topic" })). not . toBeInTheDocument ();
2026-05-06 14:15:36 +00:00
expect ( screen . getByRole ( "button" , { name : "Toggle theme from header" })). toBeInTheDocument ();
2026-05-08 15:31:52 +00:00
expect ( within ( sidebar ). getByRole ( "button" , { name : "Settings" })). toBeInTheDocument ();
2026-05-06 14:15:36 +00:00
expect ( within ( sidebar ). getByText ( "Existing chat" )). toBeInTheDocument ();
});
2026-05-18 00:53:36 +08:00
it ( "refreshes the bootstrap token before REST settings auth expires" , async () => {
vi . useFakeTimers ();
vi . mocked ( fetchBootstrap )
. mockResolvedValueOnce ({
token : "tok-1" ,
2026-07-08 14:27:52 +08:00
api_token : "api-tok-1" ,
2026-05-18 00:53:36 +08:00
ws_path : "/" ,
expires_in : 30 ,
})
. mockResolvedValueOnce ({
token : "tok-2" ,
2026-07-08 14:27:52 +08:00
api_token : "api-tok-2" ,
2026-05-18 00:53:36 +08:00
ws_path : "/" ,
expires_in : 300 ,
});
vi . mocked ( deriveWsUrl ). mockImplementation (
( _wsPath : string , token : string ) => `ws://test?token= ${ token } ` ,
);
const { unmount } = render (< App />);
await act ( async () => {});
expect ( connectSpy ). toHaveBeenCalled ();
expect ( fetchBootstrap ). toHaveBeenCalledTimes ( 1 );
await act ( async () => {
await vi . advanceTimersByTimeAsync ( 15 _000 );
});
expect ( fetchBootstrap ). toHaveBeenCalledTimes ( 2 );
expect ( updateUrlSpy ). toHaveBeenCalledWith ( "ws://test?token=tok-2" );
unmount ();
});
2026-07-30 10:25:22 +08:00
2026-10-11 18:15:39 +08:00
it . each ([ "sending" , "failed" ])( "explains an undelivered pairing reply (%s) without empty code slots" , async ( delivery_status ) => {
mockFetchRoutes ({ "/api/settings/pairing" : { requests : [{
code : "ABCD-EFGH" , channel : "feishu" , sender_id : "alice" , delivery_status ,
}] } });
render (< App />);
const popup = await screen . findByRole ( "dialog" , { name : "Pair account" });
expect ( within ( popup ). getByText ( "Already received a code?" ). closest ( "details" )). not . toHaveAttribute ( "open" );
expect ( within ( popup ). getByText ( /another private message to retry/ )). toBeVisible ();
if ( delivery_status === "failed" ) expect ( within ( popup ). getByRole ( "alert" )). toBeVisible ();
fireEvent . click ( within ( popup ). getByText ( "Already received a code?" ));
expect ( within ( popup ). getByRole ( "textbox" , { name : "Pairing code" })). toBeEnabled ();
expect ( requestMutationSpy ). not . toHaveBeenCalledWith ( "settings.pairing.approve" , expect . anything (), expect . anything ());
});
it . each ([ undefined , "sent" ])( "keeps legacy/delivered pairing usable behind a failed request (%s)" , async ( delivery_status ) => {
mockFetchRoutes ({ "/api/settings/pairing" : { requests : [
{ code : "ABCD-EFGH" , channel : "feishu" , sender_id : "alice" , delivery_status : "failed" },
{ code : "IJKL-MNOP" , channel : "feishu.second" , sender_id : "bob" , delivery_status },
] } });
render (< App />);
const popup = await screen . findByRole ( "dialog" , { name : "Pair account" });
expect ( within ( popup ). getByRole ( "textbox" , { name : "Pairing code" })). toBeEnabled ();
expect ( within ( popup ). queryByRole ( "alert" )). not . toBeInTheDocument ();
expect ( within ( popup ). getByText ( "2 pending" )). toBeVisible ();
});
2026-07-30 10:25:22 +08:00
it ( "reuses an in-flight pairing poll when the page becomes visible again" , async () => {
let resolvePairing !: ( response : Response ) => void ;
const pendingPairing = new Promise < Response >(( resolve ) => {
resolvePairing = resolve ;
});
const fetchMock = vi . fn (( input : RequestInfo | URL ) => (
String ( input ) === "/api/settings/pairing"
? pendingPairing
: Promise.resolve ({ ok : false , status : 404 } as Response )
));
vi . stubGlobal ( "fetch" , fetchMock );
const visibilityDescriptor = Object . getOwnPropertyDescriptor ( document , "visibilityState" );
const setVisibility = ( state : DocumentVisibilityState ) => {
Object . defineProperty ( document , "visibilityState" , {
configurable : true ,
value : state ,
});
document . dispatchEvent ( new Event ( "visibilitychange" ));
};
try {
render (< App />);
await waitFor (() => {
expect ( fetchMock . mock . calls . filter (([ input ]) => (
String ( input ) === "/api/settings/pairing"
))). toHaveLength ( 1 );
});
act (() => setVisibility ( "hidden" ));
act (() => setVisibility ( "visible" ));
expect ( fetchMock . mock . calls . filter (([ input ]) => (
String ( input ) === "/api/settings/pairing"
))). toHaveLength ( 1 );
await act ( async () => {
resolvePairing ( jsonResponse ({ requests : [] }));
await pendingPairing ;
});
} finally {
if ( visibilityDescriptor ) {
Object . defineProperty ( document , "visibilityState" , visibilityDescriptor );
} else {
delete ( document as Document & {
visibilityState? : DocumentVisibilityState ;
}). visibilityState ;
}
}
});
2026-04-18 18:51:53 +00:00
});