1
0

session-timeline-benchmark.fixture.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. import { base64Encode } from "@opencode-ai/core/util/encode"
  2. import type { Page } from "@playwright/test"
  3. import { mockOpenCodeServer } from "../../utils/mock-server"
  4. import { expectAppVisible, expectSessionTitle } from "../../utils/waits"
  5. import { expect } from "../benchmark"
  6. const directory = "C:/OpenCode/TimelineStateRegression"
  7. const projectID = "proj_timeline_state_regression"
  8. const sessionID = "ses_timeline_state_regression"
  9. const userMessageID = "msg_user_regression"
  10. const assistantMessageID = "msg_assistant_regression"
  11. const editPartID = "prt_0001_edit"
  12. export const textPartID = "prt_9999_text"
  13. const title = "Timeline collapse state regression"
  14. const model = { providerID: "opencode", modelID: "claude-opus-4-6", variant: "max" }
  15. type EventPayload = {
  16. directory: string
  17. payload: Record<string, unknown>
  18. }
  19. const userMessage = {
  20. info: {
  21. id: userMessageID,
  22. sessionID,
  23. role: "user",
  24. time: { created: 1700000000000 },
  25. summary: { diffs: [] },
  26. agent: "build",
  27. model,
  28. },
  29. parts: [
  30. {
  31. id: "prt_user_text",
  32. sessionID,
  33. messageID: userMessageID,
  34. type: "text",
  35. text: "Please edit the file.",
  36. },
  37. ],
  38. }
  39. const editPart = {
  40. id: editPartID,
  41. sessionID,
  42. messageID: assistantMessageID,
  43. type: "tool",
  44. callID: "call_edit_regression",
  45. tool: "edit",
  46. state: {
  47. status: "completed",
  48. input: { filePath: "src/regression.ts" },
  49. output: "Edited src/regression.ts",
  50. title: "src/regression.ts",
  51. metadata: {
  52. filediff: {
  53. file: "src/regression.ts",
  54. additions: 1,
  55. deletions: 1,
  56. before: "export const value = 'before'\n",
  57. after: "export const value = 'after'\n",
  58. },
  59. diff: "diff --git a/src/regression.ts b/src/regression.ts\n-export const value = 'before'\n+export const value = 'after'\n",
  60. },
  61. time: { start: 1700000001000, end: 1700000002000 },
  62. },
  63. }
  64. const streamedTextPart = {
  65. id: textPartID,
  66. sessionID,
  67. messageID: assistantMessageID,
  68. type: "text",
  69. text: "Streaming added a later assistant text part.",
  70. }
  71. const assistantMessage = {
  72. info: {
  73. id: assistantMessageID,
  74. sessionID,
  75. role: "assistant",
  76. time: { created: 1700000001000 },
  77. parentID: userMessageID,
  78. modelID: model.modelID,
  79. providerID: model.providerID,
  80. mode: "build",
  81. agent: "build",
  82. path: { cwd: directory, root: directory },
  83. cost: 0.01,
  84. tokens: { input: 100, output: 200, reasoning: 0, cache: { read: 0, write: 0 } },
  85. variant: "max",
  86. },
  87. parts: [editPart],
  88. }
  89. export async function setupTimelineBenchmark(page: Page, options: { historyTurns: number; eventBatch: number }) {
  90. const events: EventPayload[] = []
  91. let eventBatch = options.eventBatch
  92. await mockOpenCodeServer(page, {
  93. directory,
  94. project: project(),
  95. provider: provider(),
  96. sessions: [session()],
  97. pageMessages: () => ({
  98. items: [
  99. ...Array.from({ length: options.historyTurns }, (_, index) => performanceTurn(index)).flat(),
  100. userMessage,
  101. assistantMessage,
  102. ],
  103. }),
  104. events: () => events.splice(0, eventBatch),
  105. eventRetry: 16,
  106. })
  107. await page.addInitScript(() => {
  108. localStorage.setItem(
  109. "settings.v3",
  110. JSON.stringify({
  111. general: {
  112. editToolPartsExpanded: true,
  113. shellToolPartsExpanded: true,
  114. showReasoningSummaries: true,
  115. },
  116. }),
  117. )
  118. })
  119. await page.setViewportSize({ width: 1366, height: 768 })
  120. const scroller = page.locator(".scroll-view__viewport", { has: page.locator("[data-timeline-row]") })
  121. const text = page.locator(`[data-timeline-part-id="${textPartID}"]`).first()
  122. await page.goto(`/${base64Encode(directory)}/session/${sessionID}`)
  123. await expectSessionTitle(page, title)
  124. await expectAppVisible(scroller)
  125. return {
  126. scroller,
  127. text,
  128. transport: {
  129. enqueue(payload: EventPayload | EventPayload[]) {
  130. events.push(...(Array.isArray(payload) ? payload : [payload]))
  131. },
  132. pendingCount() {
  133. return events.length
  134. },
  135. releaseAll() {
  136. eventBatch = events.length
  137. },
  138. },
  139. async scrollToBottom() {
  140. await scroller.evaluate((element) => {
  141. element.scrollTop = element.scrollHeight
  142. })
  143. },
  144. async waitForStableGeometry() {
  145. await expect
  146. .poll(() => scroller.evaluate((element) => element.scrollHeight - element.clientHeight - element.scrollTop))
  147. .toBeLessThanOrEqual(1)
  148. await page.waitForFunction((partID) => {
  149. const root = [...document.querySelectorAll<HTMLElement>(".scroll-view__viewport")].find((element) =>
  150. element.querySelector(`[data-timeline-part-id="${partID}"]`),
  151. )
  152. if (!root) return false
  153. return new Promise<boolean>((resolve) => {
  154. const height = root.scrollHeight
  155. requestAnimationFrame(() =>
  156. requestAnimationFrame(() =>
  157. resolve(root.scrollHeight === height && root.scrollHeight - root.clientHeight - root.scrollTop <= 1),
  158. ),
  159. )
  160. })
  161. }, textPartID)
  162. },
  163. }
  164. }
  165. export function buildInitialStreamEvent(deltaCount: number): EventPayload {
  166. return {
  167. directory,
  168. payload: {
  169. type: "message.part.updated",
  170. properties: {
  171. part: {
  172. ...streamedTextPart,
  173. text: `Streaming${streamChunk(0, deltaCount + 1)}\n\n\`\`\`ts\nconst initial = true\n\`\`\``,
  174. },
  175. },
  176. },
  177. }
  178. }
  179. export function buildStreamDeltaEvents(deltaCount: number): EventPayload[] {
  180. return Array.from({ length: deltaCount }, (_, index) => ({
  181. directory,
  182. payload: {
  183. type: "message.part.delta",
  184. properties: {
  185. messageID: assistantMessageID,
  186. partID: textPartID,
  187. field: "text",
  188. delta: streamChunk(index + 1, deltaCount + 1),
  189. },
  190. },
  191. }))
  192. }
  193. function performanceTurn(index: number) {
  194. const suffix = String(index).padStart(4, "0")
  195. const userID = `msg_0000_${suffix}_a_user`
  196. const assistantID = `msg_0000_${suffix}_b_assistant`
  197. const before = historicalSource(index, false)
  198. const after = historicalSource(index, true)
  199. const parts = [
  200. ...(index % 5 === 0
  201. ? [
  202. {
  203. id: `prt_0000_${suffix}_reasoning`,
  204. sessionID,
  205. messageID: assistantID,
  206. type: "reasoning",
  207. text: `Reviewing the existing implementation. ${"constraint analysis ".repeat(20)}`,
  208. time: { start: 1690000001000 + index * 2_000, end: 1690000001200 + index * 2_000 },
  209. },
  210. ]
  211. : []),
  212. {
  213. id: `prt_0000_${suffix}_assistant`,
  214. sessionID,
  215. messageID: assistantID,
  216. type: "text",
  217. text: historicalMarkdown(index),
  218. },
  219. ...(index % 8 === 0
  220. ? [
  221. {
  222. id: `prt_0000_${suffix}_edit`,
  223. sessionID,
  224. messageID: assistantID,
  225. type: "tool",
  226. callID: `call_0000_${suffix}_edit`,
  227. tool: "edit",
  228. state: {
  229. status: "completed",
  230. input: { filePath: `src/history-${index}.ts` },
  231. output: `Edited src/history-${index}.ts`,
  232. title: `src/history-${index}.ts`,
  233. metadata: {
  234. filediff: { file: `src/history-${index}.ts`, additions: 48, deletions: 48, before, after },
  235. },
  236. time: { start: 1690000001200 + index * 2_000, end: 1690000001400 + index * 2_000 },
  237. },
  238. },
  239. ]
  240. : []),
  241. ...(index % 12 === 0
  242. ? [
  243. {
  244. id: `prt_0000_${suffix}_write`,
  245. sessionID,
  246. messageID: assistantID,
  247. type: "tool",
  248. callID: `call_0000_${suffix}_write`,
  249. tool: "write",
  250. state: {
  251. status: "completed",
  252. input: { filePath: `src/generated-${index}.tsx`, content: after },
  253. output: `Wrote src/generated-${index}.tsx`,
  254. title: `src/generated-${index}.tsx`,
  255. metadata: {
  256. filediff: { file: `src/generated-${index}.tsx`, additions: 32, deletions: 0, before: "", after },
  257. },
  258. time: { start: 1690000001400 + index * 2_000, end: 1690000001500 + index * 2_000 },
  259. },
  260. },
  261. ]
  262. : []),
  263. ...(index % 16 === 0
  264. ? [
  265. {
  266. id: `prt_0000_${suffix}_patch`,
  267. sessionID,
  268. messageID: assistantID,
  269. type: "tool",
  270. callID: `call_0000_${suffix}_patch`,
  271. tool: "apply_patch",
  272. state: {
  273. status: "completed",
  274. input: { patchText: realisticPatch(index) },
  275. output: "Success. Updated src/components/SessionCard.tsx",
  276. title: "src/components/SessionCard.tsx",
  277. metadata: {
  278. files: [
  279. {
  280. filePath: "src/components/SessionCard.tsx",
  281. relativePath: "src/components/SessionCard.tsx",
  282. type: "update",
  283. additions: 8,
  284. deletions: 3,
  285. patch: realisticPatch(index),
  286. before,
  287. after,
  288. },
  289. ],
  290. },
  291. time: { start: 1690000001500 + index * 2_000, end: 1690000001700 + index * 2_000 },
  292. },
  293. },
  294. ]
  295. : []),
  296. ]
  297. return [
  298. {
  299. info: {
  300. id: userID,
  301. sessionID,
  302. role: "user",
  303. time: { created: 1690000000000 + index * 2_000 },
  304. summary: { diffs: [] },
  305. agent: "build",
  306. model,
  307. },
  308. parts: [
  309. {
  310. id: `prt_0000_${suffix}_user`,
  311. sessionID,
  312. messageID: userID,
  313. type: "text",
  314. text: `Historical prompt ${index}`,
  315. },
  316. ],
  317. },
  318. {
  319. info: {
  320. id: assistantID,
  321. sessionID,
  322. role: "assistant",
  323. time: { created: 1690000001000 + index * 2_000, completed: 1690000001500 + index * 2_000 },
  324. parentID: userID,
  325. modelID: model.modelID,
  326. providerID: model.providerID,
  327. mode: "build",
  328. agent: "build",
  329. path: { cwd: directory, root: directory },
  330. cost: 0.01,
  331. tokens: { input: 100, output: 200, reasoning: 0, cache: { read: 0, write: 0 } },
  332. variant: "max",
  333. finish: "stop",
  334. },
  335. parts,
  336. },
  337. ]
  338. }
  339. function historicalMarkdown(index: number) {
  340. const code = `import { For, Show, createSignal } from "solid-js"
  341. type SessionRow = { id: string; title: string; active: boolean }
  342. export function SessionList(props: { rows: SessionRow[] }) {
  343. const [selected, setSelected] = createSignal<string>()
  344. return (
  345. <section aria-label="Sessions">
  346. <For each={props.rows}>{(row) => (
  347. <button classList={{ active: row.active }} onClick={() => setSelected(row.id)}>
  348. <Show when={selected() === row.id} fallback={row.title}>{row.title.toUpperCase()}</Show>
  349. </button>
  350. )}</For>
  351. </section>
  352. )
  353. }`
  354. return `## Session renderer review ${index}
  355. The active session keeps **semantic row identity** while reconciling measured content. See [Solid documentation](https://docs.solidjs.com/) and the inline \`measureElement(node)\` call.
  356. | Concern | Current behavior | Verification |
  357. | --- | --- | --- |
  358. | streaming | appends Markdown blocks | painted frames |
  359. | geometry | anchors visible rows | DOM coordinates |
  360. | tools | preserves expanded state | keyed remount probe |
  361. > Long sessions combine Markdown, syntax highlighting, tool output, and asynchronously rendered diffs.
  362. ${index % 4 === 0 ? `\`\`\`tsx\n${code}\n\`\`\`\n\n\`\`\`bash\nbun typecheck\nbun test --preload ./happydom.ts ./src/pages/session\ngit diff --check\n\`\`\`` : "- preserve the viewport anchor\n- avoid replacing stable Markdown nodes\n- process provider deltas without blocking input"}`
  363. }
  364. function historicalSource(index: number, updated: boolean) {
  365. const method = updated ? "toLocaleUpperCase(props.locale)" : "toUpperCase()"
  366. const limit = updated ? 24 : 20
  367. return `import { createMemo, For } from "solid-js"
  368. type Message = {
  369. id: string
  370. role: "user" | "assistant"
  371. text: string
  372. tokens: { input: number; output: number }
  373. }
  374. export function MessageSummary(props: { messages: Message[]; locale: string }) {
  375. const visible = createMemo(() => props.messages.filter((message) => message.text.trim()).slice(-${limit}))
  376. const total = createMemo(() => visible().reduce((sum, message) => sum + message.tokens.output, 0))
  377. return (
  378. <article data-session-index="${index}">
  379. <header>{total().toLocaleString(props.locale)} output tokens</header>
  380. <For each={visible()}>{(message) => <p data-role={message.role}>{message.text.${method}}</p>}</For>
  381. </article>
  382. )
  383. }
  384. `
  385. }
  386. function realisticPatch(index: number) {
  387. return `*** Begin Patch
  388. *** Update File: src/components/SessionCard.tsx
  389. @@
  390. -const title = props.session.title.toUpperCase()
  391. -const messages = props.messages.slice(-20)
  392. +const title = props.session.title.toLocaleUpperCase(props.locale)
  393. +const messages = props.messages.filter((message) => message.text.trim()).slice(-24)
  394. +const outputTokens = messages.reduce((sum, message) => sum + message.tokens.output, 0)
  395. @@
  396. - <h2>{title}</h2>
  397. + <h2 data-session-index="${index}">{title}</h2>
  398. + <span>{outputTokens.toLocaleString(props.locale)} output tokens</span>
  399. *** End Patch`
  400. }
  401. export function streamChunk(index: number, count: number) {
  402. if (index === 0) return `\n\n## Implementation plan\n\nStreaming **bold analysis`
  403. if (index === count - 1)
  404. return `\n\`\`\`\n\n## Verification\n\n- **Typecheck:** passed\n- **Timeline geometry:** stable\n- **Streaming output:** benchmark-complete <!-- stream-${index} -->`
  405. const section = Math.floor(index / 18) + 1
  406. const fragments = [
  407. ` continues across three`,
  408. ` or four word`,
  409. ` provider deltas and`,
  410. ` closes in this fragment**. <!-- stream-${index} -->\n\n`,
  411. `| Concern | State`,
  412. ` | Verification |\n|`,
  413. ` --- | ---`,
  414. ` | --- |\n|`,
  415. ` markdown | incremental |`,
  416. ` painted frames | <!-- stream-${index} -->\n\n`,
  417. `\`\`\`tsx\nconst row: SessionRow`,
  418. ` = rows[index] ??`,
  419. ` fallback\nconst title =`,
  420. ` row.title.toLocaleUpperCase(locale)\n`,
  421. `const selected = createMemo(()`,
  422. ` => row.id ===`,
  423. ` activeID()) // stream-${index}\n`,
  424. `// stream-${index}\n\`\`\`\n\n### Iteration ${section}\n\nStreaming **bold analysis`,
  425. ]
  426. return fragments[(index - 1) % fragments.length]!
  427. }
  428. function project() {
  429. return {
  430. id: projectID,
  431. worktree: directory,
  432. vcs: "git",
  433. name: "timeline-state-regression",
  434. time: { created: 1700000000000, updated: 1700000000000 },
  435. sandboxes: [],
  436. }
  437. }
  438. function session() {
  439. return {
  440. id: sessionID,
  441. slug: "timeline-state-regression",
  442. projectID,
  443. directory,
  444. title,
  445. version: "dev",
  446. time: { created: 1700000000000, updated: 1700000000000 },
  447. }
  448. }
  449. function provider() {
  450. return {
  451. all: [
  452. {
  453. id: "opencode",
  454. name: "OpenCode",
  455. models: { "claude-opus-4-6": { id: "claude-opus-4-6", name: "Claude Opus 4.6", limit: { context: 200_000 } } },
  456. },
  457. ],
  458. connected: ["opencode"],
  459. default: { providerID: "opencode", modelID: "claude-opus-4-6" },
  460. }
  461. }