session-tab-switch-probe.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. import { expect, type Page } from "@playwright/test"
  2. import { classifySessionSwitch, isStableDestination, type SessionSwitchSample } from "./session-tab-switch-metrics"
  3. type SessionSwitchProbe = {
  4. samples: SessionSwitchSample[]
  5. stop: () => void
  6. }
  7. async function installSessionSwitchProbe(
  8. page: Page,
  9. input: { destinationIDs: string[]; sourceIDs: string[]; lastID: string; href: string },
  10. ) {
  11. await page.evaluate(({ destinationIDs, sourceIDs, lastID, href }) => {
  12. const destination = new Set(destinationIDs)
  13. const source = new Set(sourceIDs)
  14. const samples: SessionSwitchSample[] = []
  15. let started: number | undefined
  16. let running = true
  17. const reviewLevels: Record<string, string> = {
  18. panel: "#review-panel",
  19. tabs: '#review-panel [data-component="tabs"]',
  20. body: '#review-panel [data-slot="session-review-v2-body"]',
  21. review: '#review-panel [data-component="session-review-v2"]',
  22. preview: '#review-panel [data-slot="session-review-v2-preview"]',
  23. scroll: '#review-panel [data-slot="session-review-v2-diff-scroll"]',
  24. file: '#review-panel [data-component="file"][data-mode="diff"]',
  25. }
  26. const initialReviewNodes: Record<string, Element | null> = {}
  27. const sample = () => {
  28. if (!running || started === undefined) return
  29. setTimeout(() => {
  30. if (!running || started === undefined) return
  31. const observedAtMs = performance.now() - started
  32. const reviewPanel = document.querySelector<HTMLElement>("#review-panel")
  33. const reviewFile = reviewPanel?.querySelector('[data-component="file"][data-mode="diff"]')
  34. const initialReviewFile = initialReviewNodes.file
  35. const replacedLevels = Object.entries(reviewLevels).flatMap(([name, selector]) => {
  36. const initial = initialReviewNodes[name]
  37. if (!initial) return []
  38. const current = document.querySelector(selector)
  39. return current && current !== initial ? [name] : []
  40. })
  41. const review = reviewPanel
  42. ? {
  43. fileHost: !!reviewFile,
  44. fileHostReplaced: !!initialReviewFile && !!reviewFile && reviewFile !== initialReviewFile,
  45. header:
  46. reviewPanel
  47. .querySelector<HTMLElement>('[data-slot="session-review-v2-file-header"]')
  48. ?.textContent?.trim() ?? "",
  49. replacedLevels,
  50. }
  51. : undefined
  52. const root = [...document.querySelectorAll<HTMLElement>(".scroll-view__viewport")].find((element) =>
  53. element.querySelector("[data-timeline-row]"),
  54. )
  55. if (root) {
  56. const view = root.getBoundingClientRect()
  57. const visible = [...root.querySelectorAll<HTMLElement>("[data-message-id]")]
  58. .filter((element) => {
  59. const rect = element.getBoundingClientRect()
  60. return rect.bottom > view.top && rect.top < view.bottom
  61. })
  62. .map((element) => element.dataset.messageId!)
  63. const hasVisibleRows = [...root.querySelectorAll<HTMLElement>("[data-timeline-key]")].some((element) => {
  64. const rect = element.getBoundingClientRect()
  65. return rect.bottom > view.top && rect.top < view.bottom
  66. })
  67. const spacer = root.querySelector<HTMLElement>('[data-timeline-row="bottom-spacer"]')?.getBoundingClientRect()
  68. samples.push({
  69. observedAtMs,
  70. destination: visible.filter((id) => destination.has(id)),
  71. source: visible.filter((id) => source.has(id)),
  72. hasVisibleRows,
  73. last: visible.includes(lastID),
  74. bottomErrorPx: spacer ? spacer.bottom - view.bottom : undefined,
  75. review,
  76. })
  77. } else {
  78. samples.push({ observedAtMs, destination: [], source: [], hasVisibleRows: false, last: false, review })
  79. }
  80. requestAnimationFrame(sample)
  81. }, 0)
  82. }
  83. document.addEventListener(
  84. "click",
  85. (event) => {
  86. const link = event.target instanceof Element ? event.target.closest("a") : undefined
  87. if (link?.getAttribute("href") !== href) return
  88. started = performance.now()
  89. for (const [name, selector] of Object.entries(reviewLevels)) {
  90. initialReviewNodes[name] = document.querySelector(selector)
  91. }
  92. requestAnimationFrame(sample)
  93. },
  94. { capture: true, once: true },
  95. )
  96. ;(window as Window & { __sessionSwitchProbe?: SessionSwitchProbe }).__sessionSwitchProbe = {
  97. samples,
  98. stop: () => {
  99. running = false
  100. },
  101. }
  102. }, input)
  103. }
  104. async function waitForStableSessionSwitch(page: Page) {
  105. await page.waitForFunction(() => {
  106. const samples = (window as Window & { __sessionSwitchProbe?: SessionSwitchProbe }).__sessionSwitchProbe?.samples
  107. if (!samples) return false
  108. return samples.some((_, index) => {
  109. const stable = samples.slice(index, index + 3)
  110. return (
  111. stable.length === 3 &&
  112. stable.every(
  113. (sample) =>
  114. sample.destination.length > 0 &&
  115. sample.source.length === 0 &&
  116. sample.last &&
  117. Math.abs(sample.bottomErrorPx ?? Infinity) <= 1,
  118. )
  119. )
  120. })
  121. })
  122. }
  123. async function collectSessionSwitchResult(page: Page) {
  124. const samples = await page.evaluate(() => {
  125. const probe = (window as Window & { __sessionSwitchProbe?: SessionSwitchProbe }).__sessionSwitchProbe!
  126. probe.stop()
  127. return probe.samples
  128. })
  129. return classifySessionSwitch(samples)
  130. }
  131. export async function measureSessionSwitch(
  132. page: Page,
  133. input: { destinationIDs: string[]; sourceIDs: string[]; lastID: string; href: string; switch: () => Promise<void> },
  134. ) {
  135. const { switch: run, ...probe } = input
  136. await installSessionSwitchProbe(page, probe)
  137. await run()
  138. await waitForStableSessionSwitch(page)
  139. return collectSessionSwitchResult(page)
  140. }
  141. export async function waitForStableTimeline(page: Page, lastID: string) {
  142. const samples: Pick<SessionSwitchSample, "last" | "bottomErrorPx">[] = []
  143. await expect
  144. .poll(
  145. async () => {
  146. samples.push(
  147. await page.evaluate(
  148. (lastID) =>
  149. new Promise<Pick<SessionSwitchSample, "last" | "bottomErrorPx">>((resolve) => {
  150. requestAnimationFrame(() =>
  151. setTimeout(() => {
  152. const root = [...document.querySelectorAll<HTMLElement>(".scroll-view__viewport")].find((element) =>
  153. element.querySelector("[data-timeline-row]"),
  154. )
  155. if (!root) {
  156. resolve({ last: false })
  157. return
  158. }
  159. const view = root.getBoundingClientRect()
  160. const last = [...root.querySelectorAll<HTMLElement>("[data-message-id]")].some((element) => {
  161. if (element.dataset.messageId !== lastID) return false
  162. const rect = element.getBoundingClientRect()
  163. return rect.bottom > view.top && rect.top < view.bottom
  164. })
  165. const spacer = root
  166. .querySelector<HTMLElement>('[data-timeline-row="bottom-spacer"]')
  167. ?.getBoundingClientRect()
  168. resolve({ last, bottomErrorPx: spacer ? spacer.bottom - view.bottom : undefined })
  169. }, 0),
  170. )
  171. }),
  172. lastID,
  173. ),
  174. )
  175. return isStableDestination(samples.slice(-3))
  176. },
  177. { timeout: 30_000, intervals: [0] },
  178. )
  179. .toBe(true)
  180. }