v4SessionPaneLayoutParity.test.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. import { readFileSync } from "node:fs";
  2. import { resolve } from "node:path";
  3. import { createElement } from "react";
  4. import { renderToStaticMarkup } from "react-dom/server";
  5. import { describe, expect, it, vi } from "vitest";
  6. import type {
  7. ConversationSnapshot,
  8. PendingInteraction,
  9. SubagentRow,
  10. UserInputRow,
  11. } from "@zcode/shared/zcode-protocol-v4";
  12. import { SessionPane } from "@/v4/SessionPane.js";
  13. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  14. import type {
  15. OpenScopedSubagentSideTabRequest,
  16. OpenScopedWorkflowRunSideTabRequest,
  17. } from "@/lib/workspaceSidePane.js";
  18. import {
  19. CONVERSATION_CONTENT_WITHOUT_STATUS_PANEL_WIDTH_CLASS_NAME,
  20. CONVERSATION_CONTENT_WITH_STATUS_PANEL_WIDTH_CLASS_NAME,
  21. } from "@/v4/conversationLayout.js";
  22. const projectionState = vi.hoisted(() => ({
  23. current: null as {
  24. status: "live";
  25. snapshot: ConversationSnapshot;
  26. subscriptionId: string;
  27. lastError: string | null;
  28. optimisticCommands: readonly [];
  29. loadingOlder: boolean;
  30. } | null,
  31. }));
  32. const statusPanelCapture = vi.hoisted(() => ({
  33. composerProps: [] as Array<Record<string, unknown>>,
  34. props: [] as Array<Record<string, unknown>>,
  35. }));
  36. const conversationTelemetryState = vi.hoisted(() => ({
  37. current: null as null | {
  38. acceptPromptSeed: ReturnType<typeof vi.fn>;
  39. attachForeground: ReturnType<typeof vi.fn>;
  40. },
  41. }));
  42. // Bugfix:本文件只验证 SessionPane 布局骨架,隔离闲时入口对真实 TabStore 的依赖。
  43. vi.mock("@/v4/OffPeakNewTaskEntry.js", () => ({
  44. OffPeakNewTaskEntry: () => null,
  45. }));
  46. // 同理隔离推荐提示词容器:它通过 useWorkspaceServicesResolution 依赖 TabStoreProvider,
  47. // 而本文件只挂 SessionPane 验证布局,不提供 Tab store。
  48. vi.mock("@/v4/ConversationDraftSuggestedPromptsContainer.js", () => ({
  49. ConversationDraftSuggestedPromptsContainer: () => null,
  50. }));
  51. vi.mock("@/v4/telemetry/ConversationTelemetryAttachment.js", () => ({
  52. useScopedConversationTelemetrySupervisor: () => conversationTelemetryState.current,
  53. useScopedConversationTelemetryForegroundEnabled: () =>
  54. conversationTelemetryState.current !== null,
  55. }));
  56. vi.mock("@/v4/useConversationProjection.js", () => ({
  57. useConversationProjection: () => projectionState.current,
  58. }));
  59. vi.mock("@/v4/V4ConversationContext.js", () => ({
  60. useV4Conversation: () => ({
  61. layer: {
  62. acquire: vi.fn(),
  63. },
  64. sendCommand: vi.fn(),
  65. attachmentPut: vi.fn(),
  66. }),
  67. }));
  68. vi.mock("@/store/StoreProvider.js", () => ({
  69. useZCodeStoreWithDefault: (_selector: unknown, fallback: unknown) => fallback,
  70. }));
  71. vi.mock("@/hooks/useSettingService.js", () => ({
  72. useSettings: () => ({
  73. settings: { zcodeInteractionBehavior: "queue" },
  74. loading: false,
  75. error: null,
  76. update: vi.fn(async () => {}),
  77. refresh: vi.fn(async () => {}),
  78. }),
  79. }));
  80. vi.mock("@/hooks/useServices.js", () => ({
  81. useOptionalServices: () => null,
  82. useServices: () => ({
  83. zcodeSessionService: {
  84. updateProviderRegistry: vi.fn(),
  85. },
  86. zcodeTaskService: {
  87. restartWorkspaceProcess: vi.fn(),
  88. },
  89. }),
  90. }));
  91. vi.mock("@/v4/composer/useDraftConfigControl.js", () => ({
  92. buildDraftCreateConfigPayload: () => ({}),
  93. useDraftConfigControl: () => ({
  94. modelSelectionRead: { state: { status: "loading" }, reload: vi.fn() },
  95. captureAcceptedModelSelection: () => vi.fn(),
  96. draftConfig: {},
  97. draftConfigRef: { current: {} },
  98. resolveInitialDraftConfig: vi.fn(() => ({})),
  99. acceptAuthoritativeDraftModelConfig: vi.fn(),
  100. handleDraftSelectModel: vi.fn(),
  101. handleDraftSelectThought: vi.fn(),
  102. handleDraftSwitchMode: vi.fn(),
  103. }),
  104. }));
  105. vi.mock("@/v4/composer/useDraftSessionPrewarm.js", () => ({
  106. useDraftSessionPrewarm: () => ({
  107. binding: null,
  108. }),
  109. }));
  110. vi.mock("@/v4/ConversationComposer.js", async () => {
  111. const React = await import("react");
  112. return {
  113. ConversationComposer: (props: Record<string, unknown>) => {
  114. statusPanelCapture.composerProps.push(props);
  115. return React.createElement(
  116. "div",
  117. {
  118. "data-testid": "mock-composer",
  119. "data-blocking-request-id": (props.blockingRequestId as string | null) ?? "",
  120. "data-centered": props.centered ? "true" : "false",
  121. "data-draft-mode": props.draftMode ? "true" : "false",
  122. },
  123. "composer",
  124. );
  125. },
  126. };
  127. });
  128. vi.mock("@/v4/ConversationHeader.js", async () => {
  129. const React = await import("react");
  130. return {
  131. ConversationHeader: () => React.createElement("div", { "data-testid": "mock-header" }),
  132. };
  133. });
  134. vi.mock("@/v4/ConversationStatusPanel.js", async () => {
  135. const React = await import("react");
  136. return {
  137. ConversationStatusPanel: (props: Record<string, unknown>) => {
  138. statusPanelCapture.props.push(props);
  139. return React.createElement("div", { "data-testid": "mock-status" });
  140. },
  141. };
  142. });
  143. vi.mock("@/v4/ConversationQueuePanel.js", async () => {
  144. const React = await import("react");
  145. return {
  146. ConversationQueuePanel: () => React.createElement("div", { "data-testid": "mock-queue" }),
  147. };
  148. });
  149. vi.mock("@/v4/V4InteractionDialogs.js", async () => {
  150. const React = await import("react");
  151. return {
  152. V4InteractionDialogs: () => React.createElement("div", { "data-testid": "mock-interactions" }),
  153. };
  154. });
  155. vi.mock("@/request-security-edition/V4ProviderRuntimeHeadersController.js", async () => {
  156. const React = await import("react");
  157. return {
  158. V4ProviderRuntimeHeadersController: () =>
  159. React.createElement("div", { "data-testid": "mock-runtime-headers" }),
  160. };
  161. });
  162. vi.mock("@/v4/ConversationDraftEmptyState.js", async () => {
  163. const React = await import("react");
  164. return {
  165. ConversationDraftEmptyState: (props: { compactForRemoteControl?: boolean }) =>
  166. React.createElement("div", {
  167. "data-testid": "mock-draft-empty",
  168. "data-compact-remote": props.compactForRemoteControl ? "true" : "false",
  169. }),
  170. };
  171. });
  172. vi.mock("@/v4/ConversationTurnGroup.js", async () => {
  173. const React = await import("react");
  174. return {
  175. ConversationTurnGroup: () => React.createElement("div", { "data-testid": "mock-turn-group" }),
  176. };
  177. });
  178. function userInputRow(): UserInputRow {
  179. return {
  180. rowId: 1,
  181. turnId: "turn-1",
  182. createdAt: 1_777_777_777,
  183. createdAtSeq: 1,
  184. kind: "userInput",
  185. text: "hello",
  186. origin: "realUser",
  187. };
  188. }
  189. function subagentRow(overrides: Partial<SubagentRow> = {}): SubagentRow {
  190. return {
  191. rowId: 2,
  192. turnId: "turn-1",
  193. createdAt: 1_777_777_778,
  194. createdAtSeq: 2,
  195. kind: "subagent",
  196. subagentType: "Explore",
  197. status: "running",
  198. summaryText: "正在后台探索",
  199. backgrounded: true,
  200. workId: "work-agent",
  201. childSessionId: "child-session",
  202. ...overrides,
  203. };
  204. }
  205. function pendingPermissionInteraction(): PendingInteraction {
  206. return {
  207. interactionId: "perm-1",
  208. kind: "permission",
  209. anchorRowId: null,
  210. createdAt: 1_777_777_778,
  211. payload: {
  212. kind: "permission",
  213. toolCallId: "tool-call-1",
  214. toolName: "Bash",
  215. summary: "Tool has side effects and requires approval",
  216. detail: { command: "touch quickSort.js" },
  217. options: [
  218. { optionId: "allow_once", label: "允许", kind: "allowOnce" },
  219. { optionId: "allow_always", label: "始终允许", kind: "allowAlways" },
  220. { optionId: "deny", label: "拒绝", kind: "deny" },
  221. ],
  222. },
  223. };
  224. }
  225. function pendingStructuredUserInputInteraction(): PendingInteraction {
  226. return {
  227. interactionId: "ask-1",
  228. kind: "userInput",
  229. anchorRowId: null,
  230. createdAt: 1_777_777_779,
  231. payload: {
  232. kind: "userInput",
  233. prompt: "选择实现形式",
  234. freeText: false,
  235. toolName: "AskUserQuestion",
  236. toolCallId: "tool-call-ask-1",
  237. questions: [
  238. {
  239. question: "你想把这个番茄时钟作为什么形式存在?",
  240. header: "形式",
  241. options: [
  242. { value: "page", label: "独立新页面", description: "通过导航访问" },
  243. { value: "widget", label: "独立小工具视图", description: "可复用组件" },
  244. ],
  245. },
  246. ],
  247. },
  248. };
  249. }
  250. function makeSnapshot(overrides: Partial<ConversationSnapshot> = {}): ConversationSnapshot {
  251. const snapshot: ConversationSnapshot = {
  252. protocolVersion: 1,
  253. sessionId: "session-1",
  254. logEpoch: "epoch-1",
  255. seq: 1,
  256. revision: 1,
  257. control: {
  258. phase: "completedSuccess",
  259. sessionEnded: true,
  260. canStop: false,
  261. stopState: "idle",
  262. stopTargetKind: "unknown",
  263. activeWorks: [],
  264. lastError: null,
  265. apiRetry: null,
  266. },
  267. availability: {
  268. fork: { allowed: true },
  269. compact: { allowed: true },
  270. switchModelConfig: { allowed: true },
  271. setFollowupMode: { allowed: true },
  272. queueEdit: { allowed: true },
  273. sendQueuedNow: { allowed: true },
  274. pauseGoal: { allowed: false, reasonCode: "noGoalToPause" },
  275. resumeGoal: { allowed: false, reasonCode: "noGoalToResume" },
  276. },
  277. inputRouting: { mode: "startNow" },
  278. meta: { title: "Session", titleSource: "generated" },
  279. config: { provider: "", model: "", thought: "", followupMode: "queue" },
  280. usage: {
  281. contextWindow: null,
  282. cumulative: {
  283. inputTokens: 0,
  284. outputTokens: 0,
  285. cacheReadTokens: 0,
  286. cacheWriteTokens: 0,
  287. },
  288. },
  289. queue: { items: [], autoDrain: true },
  290. pendingInteractions: [],
  291. pendingCommands: [],
  292. backgroundWorks: [],
  293. goal: null,
  294. plan: null,
  295. rows: { window: [userInputRow()], totalCount: 1, firstRowId: 1 },
  296. };
  297. return { ...snapshot, ...overrides };
  298. }
  299. function renderPane({
  300. compactForRemoteControl = false,
  301. onOpenSubagentSession,
  302. onOpenWorkflowRun,
  303. onSummaryPanelVariantOverrideChange,
  304. snapshot = makeSnapshot(),
  305. sessionId = "session-1",
  306. }: {
  307. compactForRemoteControl?: boolean;
  308. onOpenSubagentSession?: (request: OpenScopedSubagentSideTabRequest) => void;
  309. onOpenWorkflowRun?: (request: OpenScopedWorkflowRunSideTabRequest) => void;
  310. onSummaryPanelVariantOverrideChange?: (variant: "panel" | "mini" | null) => void;
  311. snapshot?: ConversationSnapshot;
  312. sessionId?: string | null;
  313. } = {}): string {
  314. statusPanelCapture.props = [];
  315. statusPanelCapture.composerProps = [];
  316. projectionState.current = {
  317. status: "live",
  318. snapshot,
  319. subscriptionId: "sub-1",
  320. lastError: null,
  321. optimisticCommands: [],
  322. loadingOlder: false,
  323. };
  324. return renderToStaticMarkup(
  325. createElement(
  326. ZCodeIntlProvider,
  327. { initialLocale: "zh-CN" },
  328. createElement(SessionPane, {
  329. paneId: "workspace-main",
  330. sessionId,
  331. workspacePath: "/workspace",
  332. compactForRemoteControl,
  333. ...(onOpenSubagentSession ? { onOpenSubagentSession } : {}),
  334. ...(onOpenWorkflowRun ? { onOpenWorkflowRun } : {}),
  335. ...(onSummaryPanelVariantOverrideChange ? { onSummaryPanelVariantOverrideChange } : {}),
  336. }),
  337. ),
  338. );
  339. }
  340. describe("SessionPane v4 chat layout parity", () => {
  341. it("renders the draft greeting and the composer in the shared timeline viewport", () => {
  342. const html = renderPane({ sessionId: null });
  343. expect(html).toContain('data-v4-conversation-drop-target="true"');
  344. expect(html).toContain('data-v4-timeline-scroll="true"');
  345. expect(html).toContain('data-testid="mock-draft-empty"');
  346. expect(html).toContain('data-v4-composer-dock="true"');
  347. expect(html).toMatch(
  348. /class="[^"]*flex[^"]*min-h-full[^"]*before:min-h-\[52px\][^"]*after:min-h-4/u,
  349. );
  350. expect(html).toMatch(/data-v4-composer-dock="true" class="[^"]*mt-3[^"]*"/u);
  351. expect(html).not.toContain("@media(max-height:700px)");
  352. const timelineSource = readFileSync(
  353. resolve(process.cwd(), "packages/ui/src/v4/ConversationTimeline.tsx"),
  354. "utf8",
  355. );
  356. expect(timelineSource).not.toContain('matchMedia("(max-height: 700px)")');
  357. expect(timelineSource).toMatch(
  358. /element\.scrollTop = responsiveCenteredEmptyLayout[\s\S]*?\? 0[\s\S]*?: element\.scrollHeight/u,
  359. );
  360. const emptyStateSource = readFileSync(
  361. resolve(process.cwd(), "packages/ui/src/v4/ConversationDraftEmptyState.tsx"),
  362. "utf8",
  363. );
  364. expect(emptyStateSource).not.toContain("100vw");
  365. expect(emptyStateSource).toContain("resolveGreetingFontSizePx");
  366. expect(emptyStateSource).toContain("new ResizeObserver");
  367. expect(emptyStateSource).toContain("data-v4-draft-greeting");
  368. expect(html).toContain('data-compact-remote="false"');
  369. expect(timelineSource).not.toContain("setDesktopWindowContentMinimumHeight");
  370. expect(timelineSource).not.toContain("draftWindowMinimumHeight");
  371. expect(timelineSource).not.toContain("useOptionalPlatform");
  372. expect(timelineSource).not.toMatch(/min-height:703px/u);
  373. expect(html).toContain('data-draft-mode="true"');
  374. expect(html).toContain('data-centered="true"');
  375. expect(html).not.toContain("发送第一条消息开始对话");
  376. });
  377. it("keeps the mobile remote draft on the original compact centered layout", () => {
  378. const html = renderPane({ sessionId: null, compactForRemoteControl: true });
  379. expect(html).toContain('data-compact-remote="true"');
  380. expect(html).toMatch(/class="[^"]*justify-center[^"]*gap-4/u);
  381. expect(html).not.toContain("before:min-h-[52px]");
  382. });
  383. it("scopes narrow-width shrinking to mobile remote conversations", () => {
  384. const desktopHtml = renderPane({ compactForRemoteControl: false });
  385. const mobileHtml = renderPane({ compactForRemoteControl: true });
  386. const readSessionPaneClassName = (html: string) =>
  387. html.match(/data-v4-conversation-drop-target="true"[^>]*class="([^"]*)"/u)?.[1] ?? "";
  388. const readTimelineClassName = (html: string) =>
  389. html.match(/data-v4-timeline-scroll="true"[^>]*class="([^"]*)"/u)?.[1] ?? "";
  390. expect(readSessionPaneClassName(mobileHtml)).toContain("min-w-0");
  391. expect(readTimelineClassName(mobileHtml)).toContain("min-w-0");
  392. expect(readSessionPaneClassName(desktopHtml)).not.toContain("min-w-0");
  393. expect(readTimelineClassName(desktopHtml)).not.toContain("min-w-0");
  394. });
  395. it("keeps constrained desktop draft content reachable through the timeline scroll viewport", () => {
  396. const timelineSource = readFileSync(
  397. resolve(process.cwd(), "packages/ui/src/v4/ConversationTimeline.tsx"),
  398. "utf8",
  399. );
  400. // 回归原因:内容可达性必须由 timeline 自身承担,不能依赖原生窗口反向扩高。
  401. expect(timelineSource).not.toContain('"h-full min-h-0 overflow-hidden"');
  402. expect(timelineSource).toMatch(/centeredEmptyLayout[\s\S]*?"flex[^"]*min-h-full[^"]*"/u);
  403. });
  404. it("keeps a bound empty session blank while preserving the bottom composer dock", () => {
  405. const html = renderPane({
  406. snapshot: makeSnapshot({
  407. rows: { window: [], totalCount: 0, firstRowId: null },
  408. }),
  409. });
  410. expect(html).toContain('data-v4-timeline-scroll="true"');
  411. expect(html).toContain('data-v4-composer-dock="true"');
  412. expect(html).toContain('data-testid="mock-composer"');
  413. expect(html).not.toContain("v4-timeline-empty");
  414. expect(html).not.toContain("发送第一条消息开始对话");
  415. });
  416. it("renders the composer inside the timeline scroll viewport with shared content width", () => {
  417. const html = renderPane();
  418. expect(html).toContain('data-v4-timeline-scroll="true"');
  419. expect(html).toMatch(
  420. /data-v4-timeline-scroll="true"[^>]*class="[^"]*overflow-x-hidden[^"]*overflow-y-auto/,
  421. );
  422. expect(html).toContain('data-v4-timeline-content-column="true"');
  423. expect(html).toContain('data-v4-composer-dock="true"');
  424. expect(html.indexOf('data-v4-timeline-scroll="true"')).toBeLessThan(
  425. html.indexOf('data-v4-composer-dock="true"'),
  426. );
  427. expect(html.indexOf('data-v4-composer-dock="true"')).toBeLessThan(
  428. html.indexOf('data-testid="mock-composer"'),
  429. );
  430. expect(html).toContain("@container/conversation");
  431. expect(html).toContain(CONVERSATION_CONTENT_WITHOUT_STATUS_PANEL_WIDTH_CLASS_NAME);
  432. expect(html).toContain(
  433. "transition-[width,max-width,transform] duration-150 ease-out @min-[1280px]/conversation:transition-[transform]",
  434. );
  435. expect(html).not.toContain("transition-transform duration-150 ease-out");
  436. });
  437. it("TN08:composer 只在内容列接收事件,不遮挡左侧问题导航", () => {
  438. const html = renderPane();
  439. expect(html).toMatch(/data-v4-composer-dock="true" class="[^"]*pointer-events-none/);
  440. expect(html).toMatch(/data-v4-composer-dock-content="true" class="[^"]*pointer-events-auto/);
  441. });
  442. it("keeps transparent composer bottom padding and masks only the message layer", () => {
  443. const html = renderPane();
  444. expect(html).toContain('data-v4-timeline-message-layer="true"');
  445. expect(html).toContain("px-4 pb-4");
  446. expect(html).not.toContain("px-4 pb-4 max-md:px-2");
  447. expect(html).not.toContain("max-md:pb-2");
  448. expect(html).not.toContain("h-4 bg-background max-md:h-2");
  449. expect(html).toContain("mask-repeat:no-repeat");
  450. const timelineSource = readFileSync(
  451. resolve(process.cwd(), "packages/ui/src/v4/ConversationTimeline.tsx"),
  452. "utf8",
  453. );
  454. expect(timelineSource).toContain("COMPOSER_MESSAGE_MASK_TRANSPARENT_HEIGHT_PX = 96");
  455. expect(timelineSource).toContain("COMPOSER_MESSAGE_MASK_FADE_PX = 24");
  456. expect(timelineSource).toContain("isAtBottom({");
  457. expect(timelineSource).toContain('messageLayer.style.maskImage = "none"');
  458. expect(timelineSource).toContain(
  459. "viewportHeight - COMPOSER_MESSAGE_MASK_TRANSPARENT_HEIGHT_PX",
  460. );
  461. expect(timelineSource).toContain("black ${opaqueEnd}px, transparent ${transparentStart}px");
  462. const maskSyncSource = timelineSource.slice(
  463. timelineSource.indexOf("const syncMessageLayerMask = useCallback"),
  464. timelineSource.indexOf("const syncTurnNavigatorViewport = useCallback"),
  465. );
  466. expect(maskSyncSource).not.toContain("getBoundingClientRect");
  467. expect(timelineSource).not.toContain("data-v4-composer-mask-target");
  468. // Bug 回归:composer 的纵向 mask 如果和正文 max-width 共用一层,会把 Markdown
  469. // 表格增强模式越出正文列的左右区域一起裁掉。mask 层必须全宽,正文宽度下沉到历史区和 live tail。
  470. expect(timelineSource).toContain(
  471. 'className="relative w-full flex-1 [mask-repeat:no-repeat] [-webkit-mask-repeat:no-repeat]"',
  472. );
  473. expect(timelineSource).toMatch(
  474. /data-v4-timeline-virtual-history="true"[\s\S]*?contentWidthClassName/,
  475. );
  476. expect(timelineSource).toMatch(/data-v4-running-live-tail="true"[\s\S]*?contentWidthClassName/);
  477. });
  478. it("anchors the back-to-bottom control to the composer dock above input", () => {
  479. const html = renderPane();
  480. expect(html).toContain('data-v4-back-to-bottom-anchor="composer-dock"');
  481. expect(html.indexOf('data-v4-composer-dock="true"')).toBeLessThan(
  482. html.indexOf('data-v4-back-to-bottom-anchor="composer-dock"'),
  483. );
  484. expect(html.indexOf('data-v4-back-to-bottom-anchor="composer-dock"')).toBeLessThan(
  485. html.indexOf('data-testid="mock-composer"'),
  486. );
  487. });
  488. it("uses the z-code-2 icon-only back-to-bottom control", () => {
  489. const timelineSource = readFileSync(
  490. resolve(process.cwd(), "packages/ui/src/v4/ConversationTimeline.tsx"),
  491. "utf8",
  492. );
  493. expect(timelineSource).toContain('<ArrowDownIcon className="size-4" />');
  494. expect(timelineSource).not.toMatch(/>\s*回到底部\s*</);
  495. expect(timelineSource).toContain('id: "chat.scrollToBottom"');
  496. });
  497. it("renders pending permission before the composer inside the composer dock", () => {
  498. conversationTelemetryState.current = {
  499. acceptPromptSeed: vi.fn(),
  500. attachForeground: vi.fn(() => () => {}),
  501. };
  502. const html = renderPane({
  503. snapshot: makeSnapshot({
  504. pendingInteractions: [pendingPermissionInteraction()],
  505. }),
  506. });
  507. conversationTelemetryState.current = null;
  508. const dockIndex = html.indexOf('data-v4-composer-dock="true"');
  509. const interactionIndex = html.indexOf('data-testid="mock-interactions"');
  510. const composerIndex = html.indexOf('data-testid="mock-composer"');
  511. expect(dockIndex).toBeGreaterThanOrEqual(0);
  512. expect(interactionIndex).toBeGreaterThanOrEqual(0);
  513. expect(composerIndex).toBeGreaterThanOrEqual(0);
  514. expect(dockIndex).toBeLessThan(interactionIndex);
  515. expect(interactionIndex).toBeLessThan(composerIndex);
  516. // 2026-08-17:Start Plan runtime headers 应答方已迁出 SessionPane,改由 Root 的
  517. // V4WorkspaceProviderRuntimeHeadersBridge 按 workspace 常驻挂载(web 远控新建会话
  518. // 在桌面没有 pane 时也必须有应答方),pane 内不再渲染该控制器。
  519. expect(html).not.toContain('data-testid="mock-runtime-headers"');
  520. expect(html).toContain('data-blocking-request-id="perm-1"');
  521. });
  522. it("普通 Web 没有 desktop-continuous attachment 时不挂一次性 runtime header controller", () => {
  523. conversationTelemetryState.current = null;
  524. const html = renderPane();
  525. expect(html).not.toContain('data-testid="mock-runtime-headers"');
  526. });
  527. it("renders structured user input before the composer inside the composer dock", () => {
  528. const html = renderPane({
  529. snapshot: makeSnapshot({
  530. pendingInteractions: [pendingStructuredUserInputInteraction()],
  531. }),
  532. });
  533. const dockIndex = html.indexOf('data-v4-composer-dock="true"');
  534. const interactionIndex = html.indexOf('data-testid="mock-interactions"');
  535. const composerIndex = html.indexOf('data-testid="mock-composer"');
  536. expect(dockIndex).toBeGreaterThanOrEqual(0);
  537. expect(interactionIndex).toBeGreaterThanOrEqual(0);
  538. expect(composerIndex).toBeGreaterThanOrEqual(0);
  539. expect(dockIndex).toBeLessThan(interactionIndex);
  540. expect(interactionIndex).toBeLessThan(composerIndex);
  541. expect(html).toContain('data-blocking-request-id="ask-1"');
  542. });
  543. it("offsets the conversation column and composer when the status panel can sit inline", () => {
  544. vi.stubGlobal("window", {
  545. innerWidth: 1280,
  546. addEventListener: vi.fn(),
  547. removeEventListener: vi.fn(),
  548. });
  549. try {
  550. const html = renderPane({
  551. snapshot: makeSnapshot({
  552. goal: {
  553. targetId: "goal-inline",
  554. objective: "Keep status panel inline with the conversation column",
  555. summaryTitle: null,
  556. timeUsedSeconds: 0,
  557. activeRunStartedAtMs: null,
  558. status: "active",
  559. iteration: 1,
  560. verifications: [],
  561. iterations: [],
  562. },
  563. }),
  564. });
  565. expect(html).toContain("@min-[1280px]/conversation:-translate-x-42");
  566. expect(html).toContain(CONVERSATION_CONTENT_WITH_STATUS_PANEL_WIDTH_CLASS_NAME);
  567. expect(html).toContain('data-v4-timeline-content-column="true"');
  568. expect(html).toContain('data-v4-composer-dock="true"');
  569. expect(statusPanelCapture.props.at(-1)?.layoutMode).toBe("auto");
  570. } finally {
  571. vi.unstubAllGlobals();
  572. }
  573. });
  574. it("wires pause/resume callbacks only from authoritative goal availability", () => {
  575. const active = makeSnapshot();
  576. active.goal = {
  577. targetId: "goal-controls",
  578. objective: "Restore goal controls",
  579. summaryTitle: null,
  580. timeUsedSeconds: 3,
  581. activeRunStartedAtMs: null,
  582. status: "active",
  583. iteration: 0,
  584. verifications: [],
  585. iterations: [],
  586. };
  587. active.availability = {
  588. ...active.availability,
  589. pauseGoal: { allowed: true },
  590. resumeGoal: { allowed: false, reasonCode: "goalNotPaused" },
  591. };
  592. renderPane({ snapshot: active });
  593. expect(statusPanelCapture.props.at(-1)?.onPauseGoal).toEqual(expect.any(Function));
  594. expect(statusPanelCapture.props.at(-1)?.onResumeGoal).toBeUndefined();
  595. const paused = makeSnapshot({
  596. goal: { ...active.goal, status: "paused" },
  597. availability: {
  598. ...active.availability,
  599. pauseGoal: { allowed: false, reasonCode: "goalNotActive" },
  600. resumeGoal: { allowed: true },
  601. },
  602. });
  603. renderPane({ snapshot: paused });
  604. expect(statusPanelCapture.props.at(-1)?.onPauseGoal).toBeUndefined();
  605. expect(statusPanelCapture.props.at(-1)?.onResumeGoal).toEqual(expect.any(Function));
  606. });
  607. it("keeps scoped Agent detail opening on remote compact while hiding the directory", () => {
  608. const onOpenSubagentSession = vi.fn();
  609. const row = subagentRow();
  610. const snapshot = makeSnapshot({
  611. backgroundWorks: [
  612. {
  613. workId: "work-agent",
  614. kind: "subagent",
  615. title: "分析状态面板",
  616. status: "running",
  617. startedAt: 1_777_777_778,
  618. anchorRowId: row.rowId,
  619. childSessionId: "child-session",
  620. },
  621. ],
  622. rows: { window: [userInputRow(), row], totalCount: 2, firstRowId: 1 },
  623. });
  624. renderPane({ snapshot, onOpenSubagentSession });
  625. const panelProps = statusPanelCapture.props.at(-1);
  626. if (!panelProps) throw new Error("Status panel props were not captured");
  627. expect(panelProps.parentSessionId).toBe("session-1");
  628. expect(panelProps.runningSubagents).toEqual([]);
  629. expect(panelProps.onOpenSubagentSession).toEqual(expect.any(Function));
  630. (
  631. panelProps.onOpenSubagentSession as (request: {
  632. rootSessionId: string;
  633. parentSessionId: string;
  634. childSessionId: string;
  635. subagentType: string;
  636. title: string;
  637. }) => void
  638. )({
  639. rootSessionId: "session-1",
  640. parentSessionId: "session-1",
  641. childSessionId: "child-session",
  642. subagentType: "Explore",
  643. title: "分析状态面板",
  644. });
  645. expect(onOpenSubagentSession).toHaveBeenCalledWith({
  646. workspacePath: "/workspace",
  647. rootSessionId: "session-1",
  648. parentSessionId: "session-1",
  649. childSessionId: "child-session",
  650. subagentType: "Explore",
  651. title: "分析状态面板",
  652. });
  653. renderPane({
  654. compactForRemoteControl: true,
  655. snapshot,
  656. onOpenSubagentSession,
  657. });
  658. expect(statusPanelCapture.props.at(-1)?.isWebRemoteControl).toBe(true);
  659. expect(statusPanelCapture.props.at(-1)?.isMobileViewport).toBe(false);
  660. expect(statusPanelCapture.props.at(-1)?.onOpenSubagentSession).toEqual(expect.any(Function));
  661. expect(statusPanelCapture.props.at(-1)?.onOpenSubagentDirectory).toBeUndefined();
  662. });
  663. it("wires the Composer background entry to panel expansion and controlled Running state", () => {
  664. const onSummaryPanelVariantOverrideChange = vi.fn();
  665. const snapshot = makeSnapshot({
  666. backgroundWorks: [
  667. {
  668. workId: "work-bash",
  669. kind: "bash",
  670. title: "Run checks",
  671. status: "running",
  672. startedAt: 1_777_777_778,
  673. anchorRowId: null,
  674. },
  675. ],
  676. });
  677. renderPane({ snapshot, onSummaryPanelVariantOverrideChange });
  678. const composerProps = statusPanelCapture.composerProps.at(-1);
  679. const panelProps = statusPanelCapture.props.at(-1);
  680. expect(composerProps?.onOpenRunningBackgroundWorks).toEqual(expect.any(Function));
  681. expect(panelProps?.terminalSectionOpen).toBe(false);
  682. expect(panelProps?.onTerminalSectionOpenChange).toEqual(expect.any(Function));
  683. expect(panelProps?.agentSectionOpen).toBe(false);
  684. expect(panelProps?.onAgentSectionOpenChange).toEqual(expect.any(Function));
  685. (composerProps?.onOpenRunningBackgroundWorks as (() => void) | undefined)?.();
  686. expect(onSummaryPanelVariantOverrideChange).toHaveBeenCalledWith("panel");
  687. });
  688. it("keeps the Composer Agent count while the directory projection catches up", () => {
  689. const snapshot = makeSnapshot({
  690. backgroundWorks: [
  691. {
  692. workId: "work-agent",
  693. kind: "subagent",
  694. title: "后台分析",
  695. status: "running",
  696. startedAt: 1_777_777_778,
  697. anchorRowId: null,
  698. childSessionId: "child-session",
  699. },
  700. ],
  701. subagents: {
  702. revision: 2,
  703. childSessionIds: ["child-session"],
  704. running: [],
  705. endedTotal: 0,
  706. },
  707. });
  708. renderPane({ snapshot });
  709. const composerProps = statusPanelCapture.composerProps.at(-1);
  710. expect(composerProps?.runningSubagentCount).toBe(1);
  711. expect(composerProps?.onOpenRunningBackgroundWorks).toEqual(expect.any(Function));
  712. });
  713. // composer 徽标直达(docs/dynamic-workflow/presentation.md):唯一在跑的工作流
  714. // 点徽标直接开详情 side tab,胶囊不动;其他形态照旧展开胶囊。
  715. describe("Composer background entry with dwf workflow runs", () => {
  716. const workflowWork = {
  717. workId: "dwfrun-1",
  718. kind: "workflow" as const,
  719. title: "发布前检查",
  720. status: "running" as const,
  721. startedAt: 1_777_777_778,
  722. anchorRowId: null,
  723. };
  724. const workflowRun = {
  725. runId: "dwfrun-1",
  726. toolCallId: "tool-wf-1",
  727. status: "running" as const,
  728. usage: { spentTokens: 0, nodesUsed: 0 },
  729. actors: [],
  730. nodes: [],
  731. lastEventSequence: 0,
  732. };
  733. it("opens the run details directly when one workflow is the only running activity", () => {
  734. const onSummaryPanelVariantOverrideChange = vi.fn();
  735. const onOpenWorkflowRun = vi.fn();
  736. const snapshot = makeSnapshot({
  737. backgroundWorks: [workflowWork],
  738. workflowRuns: { revision: 1, runs: [workflowRun] },
  739. });
  740. renderPane({ snapshot, onOpenWorkflowRun, onSummaryPanelVariantOverrideChange });
  741. const composerProps = statusPanelCapture.composerProps.at(-1);
  742. expect(composerProps?.backgroundWorkOpenTarget).toBe("workflow-run");
  743. (composerProps?.onOpenRunningBackgroundWorks as (() => void) | undefined)?.();
  744. expect(onOpenWorkflowRun).toHaveBeenCalledWith({
  745. parentSessionId: "session-1",
  746. runId: "dwfrun-1",
  747. toolCallId: "tool-wf-1",
  748. workflowName: "发布前检查",
  749. workspacePath: "/workspace",
  750. });
  751. expect(onSummaryPanelVariantOverrideChange).not.toHaveBeenCalled();
  752. });
  753. it("falls back to panel expansion when another kind runs alongside the workflow", () => {
  754. const onSummaryPanelVariantOverrideChange = vi.fn();
  755. const onOpenWorkflowRun = vi.fn();
  756. const snapshot = makeSnapshot({
  757. backgroundWorks: [
  758. workflowWork,
  759. {
  760. workId: "work-bash",
  761. kind: "bash",
  762. title: "Run checks",
  763. status: "running",
  764. startedAt: 1_777_777_778,
  765. anchorRowId: null,
  766. },
  767. ],
  768. workflowRuns: { revision: 1, runs: [workflowRun] },
  769. });
  770. renderPane({ snapshot, onOpenWorkflowRun, onSummaryPanelVariantOverrideChange });
  771. const composerProps = statusPanelCapture.composerProps.at(-1);
  772. expect(composerProps?.backgroundWorkOpenTarget).toBe("panel");
  773. (composerProps?.onOpenRunningBackgroundWorks as (() => void) | undefined)?.();
  774. expect(onOpenWorkflowRun).not.toHaveBeenCalled();
  775. expect(onSummaryPanelVariantOverrideChange).toHaveBeenCalledWith("panel");
  776. });
  777. it("falls back to panel expansion when the host cannot open run details", () => {
  778. const onSummaryPanelVariantOverrideChange = vi.fn();
  779. const snapshot = makeSnapshot({
  780. backgroundWorks: [workflowWork],
  781. workflowRuns: { revision: 1, runs: [workflowRun] },
  782. });
  783. renderPane({ snapshot, onSummaryPanelVariantOverrideChange });
  784. const composerProps = statusPanelCapture.composerProps.at(-1);
  785. expect(composerProps?.backgroundWorkOpenTarget).toBe("panel");
  786. (composerProps?.onOpenRunningBackgroundWorks as (() => void) | undefined)?.();
  787. expect(onSummaryPanelVariantOverrideChange).toHaveBeenCalledWith("panel");
  788. });
  789. });
  790. });