Compare commits

..
201 Commits
Author SHA1 Message Date
Aarav Sareen 00e7472faa feat(tui): new dialog designs behind new designs experiment (#55810)
Lands the rest of the dialog redesign stack, all behind the new-designs experiment:

- put dialog search in the title row (#55800)
- hide dialog search on short lists (#55801)
- read the experiment through useNewDesigns (#55802)
- raise dialog footers (#55805)
- standardize dialog footer actions (#55806)
- style selected dialog list rows (#55807)
- show list overflow indicator (#55808)
- restyle dialog headers (#55809)
- use vivid agent colors (#55810)
2026-10-16 15:15:15 +05:30
Aarav Sareen 50d4280dbd refactor(tui): build DialogSelect on DialogLayout (#55799) 2026-10-16 14:52:35 +05:30
Aarav Sareen c5e513e98e feat(tui): add opencode2 theme and text.faint token (#55798) 2026-10-16 14:48:08 +05:30
Aarav Sareen 09ef07e11e feat(tui): add new designs experiment (#55818) 2026-10-16 14:36:10 +05:30
Jack 7b99646cf1 docs(go): remove retired Go models (#55761) 2026-10-16 16:38:49 +08:00
Jack 37e3912d8e docs(console): add GLM-5.3-Flash Free (#55975) 2026-10-16 14:34:24 +08:00
Aiden Cline f0c122f717 fix(update): cache rollout fallback reads (#55205) 2026-10-16 01:33:46 -05:00
opencode-agent[bot]anddc85 e3d10de997 docs(console): add LL Alpha Free (#55969)
Co-authored-by: dc85 <83497+dc85@users.noreply.github.com>
2026-10-15 23:31:33 -07:00
Aiden Cline 538f8b1da6 fix(core): respell variants when config changes a catalog model's package (#55962) 2026-10-16 01:26:53 -05:00
Aiden Cline f09eee5002 fix(core): treat unreadable config file references as empty (#55959) 2026-10-16 01:12:37 -05:00
Aiden Cline 4cce6aef4e fix(core): prioritize preferred free OpenCode models when signed out (#55972) 2026-10-16 01:09:50 -05:00
Aiden Cline ccc6a3fd59 fix(core): escape env config values that break parsing (#55915) 2026-10-16 00:33:51 -05:00
Aiden Cline 32b41bab13 test(cli): simplify service env test (#55952) 2026-10-16 00:14:35 -05:00
Lucas Kimandkimnamu e3d5a3bdd3 fix(core): hide newer Bedrock bare IDs that require inference profiles (#54486)
Co-authored-by: kimnamu <kimnamu@users.noreply.github.com>
2026-10-16 00:14:09 -05:00
JasonH 723a2f6892 fix(cli): load saved environment when starting managed services (#50907) 2026-10-16 00:05:51 -05:00
Aiden Cline b0a8e2501b fix(ai): honor Anthropic cache format on Bedrock Converse (#55942) 2026-10-15 23:53:14 -05:00
Jensen eeec76bb62 fix(tui): transparent background for embedded terminal panel (#55396) 2026-10-15 22:46:19 -04:00
Luke Parker e25b7abf89 fix(session-ui): slide the tool group count when it changes (#55617) 2026-10-16 11:10:33 +10:00
xin zhuangandAiden Cline 706a688994 fix(core): omit compaction replay context from sanitized exports (#55592)
Co-authored-by: Aiden Cline <aidenpcline@gmail.com>
2026-10-15 20:10:25 -05:00
Aiden Cline 20d172e462 docs: document external_directory allow default (#55885) 2026-10-15 20:09:02 -05:00
opencode-agent[bot] 7049e5af4d chore(core): refresh bundled models.dev snapshot 2026-10-16 00:40:26 +00:00
Luke Parker d7d44a7e03 fix(app): fade long file names at the edge of the file tree (#55889) 2026-10-15 23:46:27 +00:00
Luke Parker 867a77a38f fix(app): keep the review pane steady when the side terminal toggles (#55879) 2026-10-15 23:34:29 +00:00
2e7ac8c8ea fix(tui): roll the compact form over to M at the rounding boundary (#55871)
Co-authored-by: argszero <argszero@users.noreply.github.com>
Co-authored-by: Tarquinen <78942835+Tarquinen@users.noreply.github.com>
2026-10-15 19:34:22 -04:00
Luke Parker 13263f30ed chore(release): publish the desktop app from beta (#55878) 2026-10-16 09:01:10 +10:00
opencode-agent[bot] b3aa790aae chore: update nix node_modules hashes 2026-10-15 22:45:48 +00:00
Filip d0f3204619 fix(util): hide plugin Git console windows on Windows (#55475) 2026-10-16 00:45:40 +02:00
Filip 17229d24f5 chore(ci): speed up and stabilize the test workflow (#55866) 2026-10-16 00:35:49 +02:00
DanteandDaniel Smolsky 7a4a03212e fix(core): seed configured limits before model transforms (#55778)
Co-authored-by: Daniel Smolsky <dannysmo@gmail.com>
2026-10-15 18:26:21 -04:00
berce e89206d397 fix(tui): say why /editor did nothing when no editor is set (#55872) 2026-10-15 17:12:22 -05:00
8db638c53c fix(core): default to big-pickle when only free OpenCode models are available (#55852)
Co-authored-by: rekram1-node <rekram1-node@users.noreply.github.com>
Co-authored-by: Aiden Cline <aidenpcline@gmail.com>
2026-10-15 17:05:21 -05:00
Jackandopencode-agent[bot] fc2fc596e3 docs(go): launch Step 5 Preview in Go (#55749)
Co-authored-by: opencode-agent[bot] <opencode-agent[bot]@users.noreply.github.com>
2026-10-15 15:00:45 -07:00
Aiden Clineanddajiaohuang a448d5b987 fix(core): accept numeric MCP timeouts (#55851)
Co-authored-by: dajiaohuang <mikewushuwen@outlook.com>
2026-10-15 16:05:04 -05:00
DS 3485a7b366 fix(tui): stop repeated review from reopening the last diff file (#55845) 2026-10-15 21:05:00 +00:00
Aiden Cline 412b2b1d85 fix(core): load and spell reasoning for every native provider package (#55789) 2026-10-15 15:34:08 -05:00
Daniel Nunns fe87944b6a fix(app): dropzone blur adjustment to avoid idle backdrop cost (#55418) 2026-10-16 06:18:38 +10:00
opencode-agent[bot]andrekram1-node 78fa607a49 ci: refresh models.dev snapshot every 12 hours (#55841)
Co-authored-by: rekram1-node <rekram1-node@users.noreply.github.com>
2026-10-15 15:13:53 -05:00
opencode f40dc433cb sync release versions for v2.0.30 [skip ci] 2026-10-15 19:48:32 +00:00
Aiden Cline d0732eadf8 docs: document MCP CIMD client registration (#55796) 2026-10-15 13:54:15 -05:00
775d1d0d71 fix(core): honor OPENCODE_DISABLE_CLAUDE_CODE (#55774)
Co-authored-by: thdxr <826656+thdxr@users.noreply.github.com>
Co-authored-by: malarahfelipe <29868402+malarahfelipe@users.noreply.github.com>
2026-10-15 13:17:35 -05:00
Victor Navarro f0b8913064 fix(infra): hand share domain over from teams worker (#55784) 2026-10-15 18:09:20 +00:00
opencode-agent[bot] a20a614d6b chore(core): refresh bundled models.dev snapshot 2026-10-15 17:51:27 +00:00
Victor Navarro 9e68770074 chore: retire session sharing backend (#55716) 2026-10-15 19:42:49 +02:00
opencode-agent[bot]andrekram1-node 6488d3da31 ci: restore daily models.dev snapshot refresh on dev (#55783)
Co-authored-by: rekram1-node <rekram1-node@users.noreply.github.com>
2026-10-15 12:40:46 -05:00
James Long 22dea2453b fix(tui): mount each dialog once so /fork shows its pending view (#55751) 2026-10-15 13:37:59 -04:00
James Long a58d1dd924 fix(tui): keep fork pending view at the list inset (#55746) 2026-10-15 13:37:37 -04:00
James Long 18d1dd453a fix(tui): show remaining dialog hints label-first (#55745) 2026-10-15 13:37:32 -04:00
James Long 838d41a0a0 refactor(tui): build prompt and integration views on DialogLayout (#55742) 2026-10-15 13:36:22 -04:00
Victor Navarro 1ca34aeee6 fix(ai): use protocol-specific inference endpoints (#55680) 2026-10-15 19:31:03 +02:00
James Long 61bfcbdaff refactor(tui): build prompt-style dialogs on DialogPrompt (#55518) 2026-10-15 13:17:19 -04:00
James Long 6d570f1d92 refactor(tui): replace dialog inset flag with a cell count (#55582) 2026-10-15 13:14:27 -04:00
James Long 6c706f2021 chore(tui): format dialog files with prettier (#55531) 2026-10-15 13:12:22 -04:00
James Long 1d07373cae refactor(tui): move remaining dialogs onto DialogLayout (#55523) 2026-10-15 13:11:49 -04:00
James Long 09a075d90c feat(tui): open the diff side panel by default (#55780) 2026-10-15 13:06:34 -04:00
terry-an-investorandDaniel Smolsky 86755e1cea fix(core): initialize MCP session for TinyFish web search (#54730)
Co-authored-by: Daniel Smolsky <dannysmo@gmail.com>
2026-10-15 17:06:05 +00:00
James Long 68510d9d6e refactor(tui): inline select row gutter and derive detail width (#55740) 2026-10-15 13:00:36 -04:00
James Long 611bc3662c refactor(tui): add shared dialog layout with one vertical rhythm (#55519) 2026-10-15 12:59:56 -04:00
James Long 0478ba6459 feat(tui): responsive diff viewer layouts (#55574) 2026-10-15 12:55:44 -04:00
James Long 06e3837eb1 refactor(tui): split DialogSelect row rendering into components (#55517) 2026-10-15 12:54:49 -04:00
Victor Navarro 41cb349c9b fix(console): link Zen and Go docs to V2 console pages (#55773) 2026-10-15 18:46:16 +02:00
James Long 78359c6744 refactor(tui): add shared DialogFooter with label-first actions (#55513) 2026-10-15 12:45:20 -04:00
James Long 3c61484f58 refactor(tui): use one side padding for all dialogs (#55505) 2026-10-15 12:30:23 -04:00
James Long af6ec83979 refactor(tui): add shared DialogHeader (#55501) 2026-10-15 11:39:21 -04:00
James Long 4f31eb987d refactor(tui): add dialog inset constants (#55498) 2026-10-15 11:38:21 -04:00
opencode-agent[bot] 654b79b27e docs(console): add Nemotron 3.5 Super VL Free (#55747)
Co-authored-by: opencode-agent[bot] <219766164+opencode-agent[bot]@users.noreply.github.com>
2026-10-15 07:48:29 -07:00
Filip 81200db2a3 fix(desktop): open PowerShell in the project directory on Windows (#55710) 2026-10-15 14:46:53 +02:00
Jack 4397ee44d0 docs(console): add DeepSeek V4.1 Flash Free (#55636) 2026-10-15 15:23:29 +08:00
Aiden Clineandkksingh000 b47c6802da fix(ai): accept null Responses function call namespace (#55631)
Co-authored-by: kksingh000 <kkandsingh000@gmail.com>
2026-10-15 02:13:14 -05:00
Aiden Cline ae8d59f8b5 fix(core): fit compaction output limit to the request actually sent (#55613) 2026-10-15 01:57:46 -05:00
opencode-agent[bot] 7ced591c3c chore: update nix node_modules hashes 2026-10-15 06:51:13 +00:00
Aiden Cline b55f220a17 fix(core): treat *.localhost as loopback for MCP OAuth token endpoints (#55627) 2026-10-15 01:39:46 -05:00
fbf5f164d9 fix(core): skip MCP list calls for unadvertised capabilities (#55474)
Co-authored-by: tsehla42 <tsehla42@users.noreply.github.com>
Co-authored-by: Aiden Cline <aidenpcline@gmail.com>
2026-10-15 01:26:12 -05:00
Don BowmanandAiden Cline 3aa26f1676 fix(core): advertise the spec-shaped MCP elicitation capability (#53196)
Co-authored-by: Aiden Cline <aidenpcline@gmail.com>
2026-10-15 01:19:35 -05:00
Aiden Cline a8fc567c5c chore(core): redact params in database query errors (#55621) 2026-10-15 01:04:07 -05:00
Aiden Cline 7b5f1bd9e1 fix(core): skip codemode query for MCP servers that reject it (#55618) 2026-10-15 00:50:11 -05:00
opencode-agent[bot] bdf4793286 feat(app): show voice delegations from the iOS app as Voice messages (#54426) 2026-10-15 13:23:12 +08:00
Luke Parker 37df62f4a1 fix(session-ui): show webfetch URL while the fetch runs (#55590) 2026-10-15 12:24:18 +10:00
Aiden Cline d099d2cb2a fix(cli): poll install download progress instead of tracing bytes (#55586) 2026-10-14 20:57:03 -05:00
Aiden Cline 97c201931c fix(www): serve install script from dev branch (#55587) 2026-10-14 20:37:54 -05:00
328f74c213 fix(mcp): pass tool input as permission metadata (#51062)
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Aiden Cline <aidenpcline@gmail.com>
2026-10-14 18:52:52 -05:00
Aiden Cline 32b1a1bf85 test(core): run MCP lifecycle tests against an in-process server (#55568) 2026-10-14 18:50:26 -05:00
Luke Parker 2ae7ec8a16 fix(app): keep project settings open when the project folder is missing (#55553) 2026-10-15 09:40:43 +10:00
Aiden Cline ccd3aa787a fix(schema): publish config schema that accepts V1 and V2 shapes (#55524) 2026-10-14 18:09:31 -05:00
Aiden Cline e05cc4a18d docs(plugin): document permission assert and fix session rules example (#55526) 2026-10-14 18:08:45 -05:00
Luke Parker 3943b84ef0 fix(cli): default the Windows service to port 45278 (#55547) 2026-10-15 08:41:49 +10:00
Filipandvegerot 1e63a3bb73 fix(core): load configured instructions (#55539)
Co-authored-by: vegerot <5297725+vegerot@users.noreply.github.com>
2026-10-15 00:34:17 +02:00
vprdev 7291f3e07a fix(console): keep API route handlers out of route modules (#55541) 2026-10-14 14:41:00 -07:00
opencode-agent[bot]andTarquinen 13afea6a1a docs(console): correct Cat Jam Free privacy on Go page (#55499)
Co-authored-by: Tarquinen <78942835+Tarquinen@users.noreply.github.com>
2026-10-14 14:00:46 -05:00
James Long 8ffbcc2c81 fix(tui): tidy docked diff panel spacing (#55467) 2026-10-14 13:12:43 -04:00
opencode-agent[bot]andrekram1-node 35bb8e44ef fix(core): treat empty configured provider and model names as omitted (#55465)
Co-authored-by: rekram1-node <rekram1-node@users.noreply.github.com>
2026-10-14 11:29:44 -05:00
opencode-agent[bot]anddc85 0ccfe69ff3 docs(console): list Cat Jam Free unavailable regions (#55466)
Co-authored-by: dc85 <83497+dc85@users.noreply.github.com>
2026-10-14 09:28:55 -07:00
Stefan Avram 07c0ff5914 feat(console): enrich Salesforce leads with Console account status (#54387) 2026-10-14 12:28:23 -04:00
James Long fe1717b309 fix(tui): put the diff side panel behind an experiment (#55456) 2026-10-14 12:16:18 -04:00
Aiden Cline 943dc005f7 fix(vscode): use the sst/opencode repository URL for Marketplace publishing (#55463) 2026-10-14 11:04:25 -05:00
Aiden Cline cddf1dd3e9 docs: document top-level policies in Console API response (#55461) 2026-10-14 10:55:52 -05:00
James Long b474b84259 fix(tui): use the action disabled token for inactive key hints (#55452) 2026-10-14 11:28:46 -04:00
James Long c0d41d2b26 feat(tui): render diffs in plugin panel slots (#47152) 2026-10-14 11:26:36 -04:00
Filip c458ad72d3 fix(core): substitute empty for missing config file references (#55388) 2026-10-14 16:35:25 +02:00
opencode-agent[bot]andneriousy f44c40b4d3 docs: add mise install method (#55415)
Co-authored-by: neriousy <34747899+neriousy@users.noreply.github.com>
2026-10-14 15:43:06 +02:00
opencode-agent[bot]andBrendonovich 5fa0a42386 feat(app): restore option arrow session tab navigation (#54277)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-10-14 21:35:52 +08:00
Jack d3e1de326b docs(www): remove Ling free models from Console models (#55410) 2026-10-14 21:29:21 +08:00
opencode-agent[bot]andBrendonovich 81d57087a4 feat(session-ui): summarize each turn's changed files (#55064)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-10-14 21:13:31 +08:00
opencode 34d8ded0c5 sync release versions for v2.0.29 [skip ci] 2026-10-14 09:03:25 +00:00
Jack 3a69bae845 docs(go): remove DeepSeek V4 Flash and V4 Flash Vision Exp (#55332) 2026-10-14 15:12:10 +08:00
黑墨水鱼 a7ad408dfe fix(stats): normalize deepseek v4.1 flash codename (#55330) 2026-10-14 15:01:34 +08:00
opencode-agent[bot] 6cc58b9094 docs(go): add Gemini 4 Argon Contributor (#55314)
Co-authored-by: opencode-agent[bot] <219766164+opencode-agent[bot]@users.noreply.github.com>
2026-10-14 00:00:53 -07:00
Luke Parker 165cd2e832 feat(desktop): pair devices through remote access (#55306) 2026-10-14 15:56:17 +10:00
Aiden Cline 5aabb619c0 fix(plugin): support Figma Git installs and dev releases (#55304) 2026-10-13 23:31:48 -05:00
Aiden Cline def5d948ef chore(tui): revert OpenTUI 0.6 upgrade (#55300) 2026-10-13 23:27:27 -05:00
Aiden Cline f1632d052d fix(plugin): use public Figma endpoint and OAuth defaults (#55252) 2026-10-13 23:18:49 -05:00
Aiden Cline f576da508d feat(core): stabilize top-level policies config (#55297) 2026-10-13 22:47:44 -05:00
Luke Parker 1c28c2fec5 fix(app): show a steer as pending from its first frame (#55251) 2026-10-14 13:07:36 +10:00
Luke Parker 52ba7d630f test(app): stop partial settings mocks leaking across browser tests (#55276) 2026-10-14 12:58:50 +10:00
Aiden Cline 6dc4d4e758 fix(core): give managed configuration highest precedence (#55267) 2026-10-13 21:28:47 -05:00
Aiden Cline 6a7cedcbf1 feat(plugin): let plugins assert permissions (#54930) 2026-10-13 20:28:24 -05:00
Luke Parker 89e043b681 fix(plugin): resolve the figma plugin's peer from the workspace (#55269) 2026-10-14 11:15:01 +10:00
Aiden Clineand1052326311 73517183b3 fix(plugin): keep each Promise hook rejection on its own tool call (#55263)
Co-authored-by: 1052326311 <65798732+1052326311@users.noreply.github.com>
2026-10-13 19:31:51 -05:00
usrnk1andLukeParkerDev 9de9b746e3 feat(desktop): refine diff view colors (#52551)
Co-authored-by: LukeParkerDev <10430890+Hona@users.noreply.github.com>
2026-10-14 10:12:13 +10:00
opencode-agent[bot]andSlickstef11 d2cedffd71 docs: correct Cat Jam Free data policy (#55224)
Co-authored-by: Slickstef11 <98915060+Slickstef11@users.noreply.github.com>
2026-10-14 00:11:09 +00:00
usrnk1andLukeParkerDev de417edf24 feat(desktop): manage provider accounts and restore Console connect intro (#54101)
Co-authored-by: LukeParkerDev <10430890+Hona@users.noreply.github.com>
2026-10-13 23:49:06 +00:00
usrnk1andLukeParkerDev 293a5bab9a feat(desktop): move session unread dots into tab container (#53570)
Co-authored-by: LukeParkerDev <10430890+Hona@users.noreply.github.com>
2026-10-13 23:40:15 +00:00
opencode-agent[bot]andrekram1-node 41f656730e docs: use supported policy action names (#55259)
Co-authored-by: rekram1-node <rekram1-node@users.noreply.github.com>
2026-10-13 18:39:07 -05:00
Kit Langton 4ea42c47df fix(session-ui): render user message attachments above text and admit inline files (#54650) 2026-10-13 16:28:42 -07:00
opencode-agent[bot]andrekram1-node 43bb7ba3a2 fix(core): let v1 npm config target built-in provider routes (#55254)
Co-authored-by: rekram1-node <63023139+rekram1-node@users.noreply.github.com>
2026-10-13 18:23:51 -05:00
usrnk1andLukeParkerDev 7b33bcea4e feat(desktop): show session tokens and cost on the session view (#53785)
Co-authored-by: LukeParkerDev <10430890+Hona@users.noreply.github.com>
2026-10-13 23:14:04 +00:00
Kit Langton 46e4695b96 fix(app): retain raw media bytes up to 256 MiB for artifact previews (#55018) 2026-10-13 15:52:31 -07:00
usrnk1andLukeParkerDev 3ec856b6c2 feat(desktop): refresh question composer (#54822)
Co-authored-by: LukeParkerDev <10430890+Hona@users.noreply.github.com>
2026-10-14 08:02:38 +10:00
Kit Langton 2a593c0d1b fix(app): suppress missing-file toast on restored and open file tabs (#55022) 2026-10-13 14:24:55 -07:00
Aiden Cline a3f7f42ac9 feat(core): continue responses after output token limits (#53876) 2026-10-13 16:24:45 -05:00
Kit Langton 7497b89b6d feat(file): add trackpad zoom and pan to image previews (#54590) 2026-10-13 14:19:45 -07:00
opencode-agent[bot] 80d43eb707 chore: update nix node_modules hashes 2026-10-13 20:53:16 +00:00
Dax d0a2ce32de feat(tui): report pending session status to the terminal (#55172) 2026-10-13 16:48:09 -04:00
Kit Langton 8396de1759 fix(app): retain session model choices across catalog refreshes (#54481) 2026-10-13 13:46:52 -07:00
Kit Langton 1163e6cd91 fix(app): fill vertical tab hover gaps (#54866) 2026-10-13 13:15:45 -07:00
Kit Langton 573fd296d0 feat(app): cycle side-panel tabs when side panel is focused (#54899) 2026-10-13 13:13:34 -07:00
Kit Langton 84e095526c fix(app): close browser tabs from the address field (#54501) 2026-10-13 13:13:28 -07:00
opencode-agent[bot]andopencode-agent[bot] e9def88a77 docs(console): remove Cat Jam Free from models privacy exceptions (#55209)
Co-authored-by: opencode-agent[bot] <opencode-agent[bot]@users.noreply.github.com>
2026-10-13 11:16:10 -07:00
opencode-agent[bot] 0af756b30f docs(console): show Gemini 4 Argon discount with strikethrough pricing (#55206)
Co-authored-by: opencode-agent[bot] <219766164+opencode-agent[bot]@users.noreply.github.com>
2026-10-13 10:56:06 -07:00
Aiden Cline 55c863daf3 feat(update): index artifact rollout lookups (#55202) 2026-10-13 12:36:48 -05:00
James Long d8e31d846a fix(server): align connect route checks (#55177) 2026-10-13 13:33:55 -04:00
opencode-agent[bot] a00475a4dd docs(console): add Gemini 4 Argon to Console models (#55196)
Co-authored-by: opencode-agent[bot] <219766164+opencode-agent[bot]@users.noreply.github.com>
2026-10-13 10:32:09 -07:00
Jack 7410b1c13c docs(console): add Cat Jam Free to Go (#55188) 2026-10-14 00:48:52 +08:00
23e3493ab2 fix(update): cache D1 reads and use partial indexes for lookups (#55109)
Co-authored-by: neriousy <34747899+neriousy@users.noreply.github.com>
Co-authored-by: Aiden Cline <aidenpcline@gmail.com>
2026-10-13 10:07:40 -05:00
Victor Navarro 82833dac90 refactor(console): stop stripping legacy Zen headers in proxy (#55120) 2026-10-13 16:43:43 +02:00
opencode-agent[bot] 1015cb67d0 chore: update nix node_modules hashes 2026-10-13 13:07:44 +00:00
Simon Klee 65f8907708 chore(tui): upgrade OpenTUI to 0.6.2 (#55083) 2026-10-13 14:59:21 +02:00
Victor Navarro c1615b1db9 refactor(console): call inference through a service binding (#55103) 2026-10-13 12:12:52 +02:00
Victor Navarro 4ffede4941 chore(console): remove unused translation strings (#55093) 2026-10-13 11:38:57 +02:00
Luke Parker be674e3158 fix(app): stop project store eviction loop on launch (#55078) 2026-10-13 19:22:40 +10:00
usrnk1andLukeParkerDev 5b22e915d8 feat(desktop): clarify variant-only timeline notices (#54880)
Co-authored-by: LukeParkerDev <10430890+Hona@users.noreply.github.com>
2026-10-13 09:03:44 +00:00
opencode c5aabae288 sync release versions for v2.0.28 [skip ci] 2026-10-13 08:17:45 +00:00
Aiden Cline 044d8b7d2e feat(ai): continue split Gemini responses (Gemini transport) (#55056) 2026-10-13 02:39:11 -05:00
opencode-agent[bot]andBrendonovich c7bddc38b3 fix(session-ui): drop stale todowrite tool label (#53966)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-10-13 07:35:36 +00:00
Aiden Cline 5a4dd5b430 feat(plugin): bundle complete Figma skills (#55061) 2026-10-13 02:10:45 -05:00
Luke Parker 7e858f474d fix(ui): return dialog focus from the stack, not from each caller (#55038) 2026-10-13 07:05:31 +00:00
opencode-agent[bot]andBrendonovich 417f120ee3 refactor(app): derive unread state from server viewed watermarks (#54780)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-10-13 14:58:13 +08:00
opencode-agent[bot]andBrendonovich bf8c48de73 fix(app): include subagent sessions in desktop session cost (#55052)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-10-13 06:55:33 +00:00
vprdev de65b9f9cc fix(console): keep Go limits chart headers from overflowing in long locales (#55054) 2026-10-12 23:49:47 -07:00
Aiden Cline 836c0e5e65 feat(plugin): add figma plugin (#55049) 2026-10-13 01:37:19 -05:00
Luke Parker 9693c31233 test(app): end the Working geometry fixture at an idle marker (#55045) 2026-10-13 16:28:40 +10:00
Luke Parker 4836431048 fix(storybook): declare @tanstack/solid-query for the pairing mock (#55047) 2026-10-13 16:25:02 +10:00
opencode-agent[bot]andBrendonovich b8f925e51c feat(app): per-project auto-accept permissions overriding a default (#54839)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-10-13 14:16:45 +08:00
opencode-agent[bot]andBrendonovich e65080dd08 refactor(app): drop per-message model and agent from mobile session timeline (#54775)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-10-13 06:10:24 +00:00
Aiden Cline d8129ca1e0 fix(ai): raise default chunk timeout to fifteen minutes (#55032) 2026-10-13 00:03:44 -05:00
opencode-agent[bot]anddc85 b4f19bfe74 docs(www): add Cat Jam Free to Console models (#55029)
Co-authored-by: dc85 <83497+dc85@users.noreply.github.com>
2026-10-12 21:57:28 -07:00
Tommy D. RossiandAiden Cline d78267503d feat(plugin): expose credential.activate to server plugins (#52797)
Co-authored-by: Aiden Cline <aidenpcline@gmail.com>
2026-10-12 23:29:22 -05:00
Luke Parker 06425d2bd7 fix(app): show Working above undelivered steers (#55023) 2026-10-13 14:24:30 +10:00
Aiden Cline 460c626acd fix(core): disable Bun's fetch idle timeout for provider requests (#55007) 2026-10-12 23:12:44 -05:00
Luke Parker 738f77e470 fix(app): load images and audio in the review panel (#55015) 2026-10-13 04:10:50 +00:00
Aiden ClineandRenato Duarte ba82b370c1 fix(core): discover system configuration directory at lowest precedence (#54921)
Co-authored-by: Renato Duarte <renato.duarte@datacamp.com>
2026-10-12 23:02:06 -05:00
Frank b4a57f6849 fix(console): redirect old zen and go docs from docs proxy 2026-10-12 23:02:39 -04:00
Frank d7cfdaa3c7 docs: redirect zen docs to console models 2026-10-12 22:46:50 -04:00
opencode-agent[bot]andrekram1-node 15b24ae12d fix(console): renew DeepSeek ZDR date on Go landing page through October 2026 (#54987)
Co-authored-by: rekram1-node <rekram1-node@users.noreply.github.com>
2026-10-12 20:31:07 -05:00
Aiden Cline 69a71426ce feat(core): configure Anthropic cache breakpoints with compatibility.cacheFormat (#54945) 2026-10-12 20:23:14 -05:00
Luke Parker 6a12383d3e fix(desktop): update emulated x64 installs to native ARM64 (#54983) 2026-10-13 01:11:18 +00:00
Luke Parker bd23808adf fix(tui): report x64 emulation on Windows ARM64 (#54984) 2026-10-13 01:01:49 +00:00
Luke Parker 3731aace4a fix(ci): fail releases that bundle native code for the wrong CPU (#54982) 2026-10-13 10:46:28 +10:00
Luke Parker 126b7b633b fix(core): extract ripgrep on Windows without PowerShell (#54981) 2026-10-13 10:45:55 +10:00
Luke Parker f7ac58f267 fix(desktop): stage the bundled CLI per architecture (#54979) 2026-10-13 10:39:52 +10:00
opencode-agent[bot]andrekram1-node 67f5c2197a fix(update): return 503 instead of 1101 when D1 is overloaded (#54920)
Co-authored-by: rekram1-node <63023139+rekram1-node@users.noreply.github.com>
2026-10-12 19:27:14 -05:00
Luke Parker df63a72da4 feat(console): offer the Windows ARM64 desktop download (#54971) 2026-10-12 23:31:34 +00:00
Dax 2bf145b931 feat(tui): show release highlights after updating (#54969) 2026-10-12 23:20:11 +00:00
Aiden ClineandEmre Şafak 5673bfa4a8 feat(core): add request body encoding setting (#54932)
Co-authored-by: Emre Şafak <3928300+esafak@users.noreply.github.com>
2026-10-12 18:17:39 -05:00
Filip d46588fe90 feat(cli): publish and upgrade official WinGet packages (#54808) 2026-10-13 01:03:35 +02:00
Luke Parker 039eb85ba1 fix(cli): install the native binary on Windows ARM64 (#54955) 2026-10-13 08:43:52 +10:00
Aiden Cline a22754f761 fix(core): support provider-level compatibility and migrate setCacheKey (#54911) 2026-10-12 15:54:05 -05:00
Aiden Cline 1438073271 fix(plugin): return Promise tool throws as tool failures (#54913) 2026-10-12 15:37:34 -05:00
80fb31ebb7 fix(vscode): launch the V2 CLI without --port (#49084)
Co-authored-by: uyencss <uyencss@users.noreply.github.com>
Co-authored-by: Aiden Cline <aidenpcline@gmail.com>
2026-10-12 13:58:37 -05:00
Dax 22326d4bc3 feat(changelog): serve /changelog from a standalone worker (#54906) 2026-10-12 18:56:09 +00:00
Dax c57c448d31 feat(console): render CHANGELOG.md on /changelog (#54902) 2026-10-12 14:41:18 -04:00
OpeOginni 1c74b9f020 fix(tui): restrict command autocomplete to prompt start (#54857) 2026-10-12 17:39:16 +00:00
Filip 7bac892c73 fix(core): stop listing Azure resources at startup (#54870) 2026-10-12 17:03:58 +00:00
Aiden Cline 5683367e27 fix(core): send unknown v1 openai-compatible model options in the request body (#54694) 2026-10-12 10:57:36 -05:00
opencode-agent[bot]andrekram1-node 5b7bad23b9 docs: point READMEs at @opencode/cli npm package (#54855)
Co-authored-by: rekram1-node <rekram1-node@users.noreply.github.com>
2026-10-12 10:44:32 -05:00
Victor Navarro e41e7e9064 refactor(ai): rename OpenCodeZen provider to OpenCode (#54767) 2026-10-12 16:35:49 +02:00
Filip 0cb434775c fix(core): preserve mixed line endings in edit tool (#53166) 2026-10-12 16:22:58 +02:00
Victor Navarro bcf23b6775 docs(www): point Go endpoints to inference base (#54777) 2026-10-12 11:47:39 +02:00
Victor Navarro 25053bbdc7 docs: replace old Zen and Go pages with V2 console docs (#54761) 2026-10-12 11:30:55 +02:00
Victor Navarro a34961825b chore(infra): remove legacy Console Stripe products, prices and coupons (#54740) 2026-10-12 10:39:13 +02:00
Jack 60a212c076 docs(go): raise DeepSeek V4.1 Flash allowances in V2 (#54753) 2026-10-12 16:27:35 +08:00
Jack 337e933d4a docs(go): raise DeepSeek V4.1 Flash allowances (#54752) 2026-10-12 16:26:26 +08:00
1092 changed files with 56659 additions and 46763 deletions

No files matched your search

+5 -10
View File
@@ -49,8 +49,11 @@ runs:
echo "dir=$(bun pm cache)" >> "$GITHUB_OUTPUT"
echo "version=$(bun --version)" >> "$GITHUB_OUTPUT"
# On Windows, extracting the cache archive takes longer than Bun downloading and
# extracting the same packages itself, so Windows installs skip the cache.
- name: Restore Bun dependencies
id: bun-cache
if: runner.os != 'Windows'
uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: ${{ steps.cache.outputs.dir }}
@@ -61,19 +64,11 @@ runs:
shell: bash
- name: Install dependencies
run: |
# Workaround for patched peer variants
# e.g. ./patches/ for standard-openapi
# https://github.com/oven-sh/bun/issues/28147
if [ "$RUNNER_OS" = "Windows" ]; then
bun install --frozen-lockfile --linker hoisted ${{ inputs.install-flags }}
else
bun install --frozen-lockfile ${{ inputs.install-flags }}
fi
run: bun install --frozen-lockfile ${{ inputs.install-flags }}
shell: bash
- name: Save Bun dependencies
if: steps.bun-cache.outputs.cache-hit != 'true' && github.event_name != 'pull_request' && github.event_name != 'pull_request_target'
if: runner.os != 'Windows' && steps.bun-cache.outputs.cache-hit != 'true' && github.event_name != 'pull_request' && github.event_name != 'pull_request_target'
uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: ${{ steps.cache.outputs.dir }}
+40
View File
@@ -0,0 +1,40 @@
name: deploy-changelog
on:
push:
branches:
- dev
paths:
- services/changelog/**
- .github/workflows/deploy-changelog.yml
workflow_dispatch:
concurrency:
group: deploy-changelog
cancel-in-progress: false
permissions:
contents: read
jobs:
deploy:
if: github.repository == 'anomalyco/opencode' && github.ref_name == 'dev'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
- uses: ./.github/actions/setup-bun
- name: Typecheck
working-directory: services/changelog
run: bun typecheck
- name: Test
working-directory: services/changelog
run: bun test
- name: Deploy
working-directory: services/changelog
run: bun run deploy
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+62
View File
@@ -0,0 +1,62 @@
name: models-snapshot
permissions:
contents: write
on:
workflow_dispatch:
schedule:
- cron: "0 0,12 * * *"
concurrency:
group: ${{ github.workflow }}
cancel-in-progress: false
jobs:
refresh:
if: github.repository == 'anomalyco/opencode'
runs-on: blacksmith-4vcpu-ubuntu-2404
steps:
- name: Checkout repository
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
persist-credentials: false
ref: dev
# The refresh script only needs `fetch`; skip the monorepo install.
- name: Setup Bun
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version-file: package.json
- name: Setup git committer
uses: ./.github/actions/setup-git-committer
with:
opencode-app-id: ${{ vars.OPENCODE_APP_ID }}
opencode-app-secret: ${{ secrets.OPENCODE_APP_SECRET }}
- name: Refresh snapshot
run: bun packages/core/script/update-models-snapshot.ts
- name: Commit changes
run: |
set -euo pipefail
FILE="packages/core/src/models-dev/snapshot.txt"
if [ -z "$(git status --short -- "$FILE")" ]; then
echo "No changes to commit"
echo "### models.dev snapshot" >> "$GITHUB_STEP_SUMMARY"
echo "Status: no changes" >> "$GITHUB_STEP_SUMMARY"
exit 0
fi
git add "$FILE"
git commit -m "chore(core): refresh bundled models.dev snapshot"
git pull --rebase --autostash origin dev
git push origin HEAD:dev --no-verify
echo "### models.dev snapshot" >> "$GITHUB_STEP_SUMMARY"
echo "Status: committed $(git rev-parse --short HEAD)" >> "$GITHUB_STEP_SUMMARY"
+1 -1
View File
@@ -6,7 +6,7 @@ permissions:
on:
workflow_dispatch:
push:
branches: [dev, beta]
branches: [dev]
paths:
- "bun.lock"
- "package.json"
+9 -4
View File
@@ -112,6 +112,7 @@ jobs:
BUN_COMPILE_RELEASE: bun-v1.4.2
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
OPENCODE_RELEASE: ${{ needs.version.outputs.release }}
OPENCODE_RELEASE_NOTES: ${{ (github.ref_name == 'dev' && inputs.release_notes) || '' }}
GH_REPO: ${{ needs.version.outputs.repo }}
GH_TOKEN: ${{ steps.committer.outputs.token }}
@@ -140,7 +141,8 @@ jobs:
sign-cli-macos:
needs: build-cli
runs-on: macos-26
if: github.repository == 'anomalyco/opencode'
# Beta publishes only the desktop app, which signs the CLI it bundles.
if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta'
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
@@ -195,7 +197,7 @@ jobs:
needs: version
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 30
if: github.repository == 'anomalyco/opencode' && !(github.ref_name == 'dev' && (inputs.bump || inputs.version))
if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta' && !(github.ref_name == 'dev' && (inputs.bump || inputs.version))
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
@@ -217,7 +219,7 @@ jobs:
needs:
- version
- build-node-app-archive
if: github.repository == 'anomalyco/opencode' && !(github.ref_name == 'dev' && (inputs.bump || inputs.version))
if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta' && !(github.ref_name == 'dev' && (inputs.bump || inputs.version))
strategy:
fail-fast: false
matrix:
@@ -258,6 +260,7 @@ jobs:
env:
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
OPENCODE_RELEASE: ${{ needs.version.outputs.release }}
OPENCODE_RELEASE_NOTES: ${{ (github.ref_name == 'dev' && inputs.release_notes) || '' }}
- name: Verify service lifecycle
if: matrix.settings.target != 'windows-arm64'
@@ -274,7 +277,7 @@ jobs:
needs:
- sign-cli-macos
runs-on: blacksmith-4vcpu-windows-2025
if: github.repository == 'anomalyco/opencode' && (github.ref_name == 'dev' || github.ref_name == 'beta')
if: github.repository == 'anomalyco/opencode' && github.ref_name == 'dev'
env:
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
@@ -589,6 +592,7 @@ jobs:
path: packages/opencode/dist
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
if: github.ref_name != 'beta'
with:
name: opencode-preview-cli
path: packages/cli/dist
@@ -652,6 +656,7 @@ jobs:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
OPENCODE_DESKTOP_DIST: /tmp/desktop
WINGET_GITHUB_TOKEN: ${{ secrets.WINGET_GITHUB_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: 15d29c8639fd3733b1b5486a2acfd968
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+119 -58
View File
@@ -25,13 +25,14 @@ jobs:
name: affected packages
runs-on: blacksmith-4vcpu-ubuntu-2404
outputs:
app: ${{ steps.packages.outputs.app }}
e2e: ${{ steps.packages.outputs.app == 'true' && github.ref_name != 'dev' && github.head_ref != 'dev' }}
steps:
- name: Checkout repository
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
# Pull requests diff against the merge's first parent; pushes diff against the previous dev head.
fetch-depth: ${{ github.event_name == 'pull_request' && 2 || 0 }}
- name: Setup Bun
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
@@ -48,7 +49,8 @@ jobs:
echo "app=true" >> "$GITHUB_OUTPUT"
exit 0
fi
bun x turbo@2.10.2 ls --affected --filter=@opencode/app --output=json > affected.json
# Storybook hosts the component tests, but no app package depends on it.
bun x turbo@2.10.2 ls --affected --filter=@opencode/app --filter=@opencode/storybook --output=json > affected.json
bun -e 'const result = await Bun.file("affected.json").json(); console.log(`app=${result.packages.count > 0}`)' >> "$GITHUB_OUTPUT"
unit:
@@ -70,7 +72,8 @@ jobs:
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
# Pull requests diff against the merge's first parent; pushes diff against the previous dev head.
fetch-depth: ${{ github.event_name == 'pull_request' && 2 || 0 }}
- name: Setup Node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
@@ -93,15 +96,6 @@ jobs:
git config --global user.email "bot@opencode.ai"
git config --global user.name "opencode"
- name: Cache Turbo
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: node_modules/.cache/turbo
key: turbo-${{ runner.os }}-${{ hashFiles('turbo.json', '**/package.json') }}-${{ github.sha }}
restore-keys: |
turbo-${{ runner.os }}-${{ hashFiles('turbo.json', '**/package.json') }}-
turbo-${{ runner.os }}-
- name: Run unit tests
timeout-minutes: 20
run: |
@@ -134,32 +128,6 @@ jobs:
TURBO_SCM_BASE: ${{ github.event_name == 'pull_request' && format('{0}^1', github.sha) || github.event.before }}
TURBO_SCM_HEAD: ${{ github.sha }}
- name: Verify compiled service lifecycle
if: always()
timeout-minutes: 10
working-directory: packages/cli
env:
NODE_OPTIONS: ${{ runner.os == 'Windows' && '--max-old-space-size=4096' || '' }}
run: |
bun run script/build.ts --single --skip-install
bun run script/service-smoke.ts
- name: Setup Node build runtime
if: always()
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "26.4.0"
- name: Verify Node build
if: always()
timeout-minutes: 15
working-directory: packages/cli
env:
NODE_OPTIONS: ${{ runner.os == 'Windows' && '--max-old-space-size=4096' || '' }}
run: |
bun run script/build-node.ts --single --skip-install --outdir=dist/node
bun run script/service-smoke.ts --node
- name: Check generated client
if: runner.os == 'Linux'
working-directory: packages/client
@@ -170,9 +138,8 @@ jobs:
working-directory: services/www
run: bun run check:generated
e2e:
name: e2e (${{ matrix.settings.name }})
needs: affected
build:
name: build (${{ matrix.settings.name }})
strategy:
fail-fast: false
matrix:
@@ -182,39 +149,112 @@ jobs:
- name: windows
host: blacksmith-4vcpu-windows-2025
runs-on: ${{ matrix.settings.host }}
defaults:
run:
shell: bash
steps:
- name: Checkout repository
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
# Pull requests diff against the merge's first parent; pushes diff against the previous dev head.
fetch-depth: ${{ github.event_name == 'pull_request' && 2 || 0 }}
- name: Setup Bun
uses: ./.github/actions/setup-bun
- name: Verify compiled service lifecycle
timeout-minutes: 10
working-directory: packages/cli
env:
NODE_OPTIONS: ${{ runner.os == 'Windows' && '--max-old-space-size=4096' || '' }}
run: |
bun run script/build.ts --single --skip-install
bun run script/service-smoke.ts
# Unit tests import workspace sources and never build the libraries they use, so this checks those builds. The
# CLI and app closures hold every library a tested package depends on. The builds are tsc and Bun.build with no
# platform-specific steps, and the libraries publish from Linux, so Windows skips them.
- name: Build workspace libraries
if: ${{ !cancelled() && runner.os == 'Linux' }}
timeout-minutes: 10
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
bun turbo build --concurrency=3 --filter='@opencode/cli^...' --filter='@opencode/app^...'
exit 0
fi
bun turbo build --affected --concurrency=3 --filter='@opencode/cli^...' --filter='@opencode/app^...'
env:
TURBO_SCM_BASE: ${{ github.event_name == 'pull_request' && format('{0}^1', github.sha) || github.event.before }}
TURBO_SCM_HEAD: ${{ github.sha }}
- name: Setup Node build runtime
if: ${{ !cancelled() }}
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "26.4.0"
- name: Verify Node build
if: ${{ !cancelled() }}
timeout-minutes: 15
working-directory: packages/cli
env:
NODE_OPTIONS: ${{ runner.os == 'Windows' && '--max-old-space-size=4096' || '' }}
run: |
bun run script/build-node.ts --single --skip-install --outdir=dist/node
bun run script/service-smoke.ts --node
e2e-suite:
name: e2e (${{ matrix.settings.name }}, ${{ matrix.suite.id }})
needs: affected
if: needs.affected.outputs.e2e == 'true'
strategy:
fail-fast: false
matrix:
settings:
- name: linux
host: blacksmith-4vcpu-ubuntu-2404
- name: windows
host: blacksmith-4vcpu-windows-2025
# Playwright splits whole spec files across shards by test count, not duration. Every app-N
# entry must use the same total, and the entries must cover 1..total. The service worker suite
# reuses shard 2's production build. Each component suite runs once per OS in its own leg, so the
# two suites' Storybook servers and test time are not added up on one runner.
suite:
- id: app-1
shard: 1/2
- id: app-2
shard: 2/2
- id: session-ui-components
- id: app-components
runs-on: ${{ matrix.settings.host }}
env:
E2E_ENABLED: ${{ needs.affected.outputs.app == 'true' && github.ref_name != 'dev' && github.head_ref != 'dev' }}
PLAYWRIGHT_BROWSERS_PATH: ${{ github.workspace }}/.playwright-browsers
defaults:
run:
shell: bash
steps:
- name: Checkout repository
if: env.E2E_ENABLED == 'true'
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup Node
if: env.E2E_ENABLED == 'true'
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
# Playwright 1.59 hangs while extracting Chromium with Node 24.16.
node-version: "24.15"
- name: Setup Bun
if: env.E2E_ENABLED == 'true'
uses: ./.github/actions/setup-bun
- name: Read Playwright version
if: env.E2E_ENABLED == 'true'
id: playwright-version
run: |
version=$(node -e 'console.log(require("./package.json").workspaces.catalog["@playwright/test"])')
echo "version=$version" >> "$GITHUB_OUTPUT"
- name: Cache Playwright browsers
if: env.E2E_ENABLED == 'true'
id: playwright-cache
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
@@ -222,47 +262,47 @@ jobs:
key: ${{ runner.os }}-${{ runner.arch }}-playwright-${{ steps.playwright-version.outputs.version }}-chromium
- name: Install Playwright system dependencies
if: env.E2E_ENABLED == 'true' && runner.os == 'Linux'
if: runner.os == 'Linux'
working-directory: packages/app
run: bunx playwright install-deps chromium
- name: Install Playwright browsers
if: env.E2E_ENABLED == 'true' && steps.playwright-cache.outputs.cache-hit != 'true'
if: steps.playwright-cache.outputs.cache-hit != 'true'
working-directory: packages/app
run: bunx playwright install chromium
- name: Run app e2e tests against production build
if: env.E2E_ENABLED == 'true'
run: bun --cwd packages/app test:e2e:built
if: matrix.suite.shard
run: bun --cwd packages/app test:e2e:built --shard=${{ matrix.suite.shard }}
env:
CI: true
timeout-minutes: 30
timeout-minutes: 15
- name: Verify service worker precaching and upgrades
if: env.E2E_ENABLED == 'true'
if: matrix.suite.shard == '2/2'
working-directory: packages/app
run: bunx playwright test --config e2e/service-worker/playwright.config.ts
timeout-minutes: 5
- name: Run session UI component tests
if: ${{ !cancelled() && env.E2E_ENABLED == 'true' }}
if: matrix.suite.id == 'session-ui-components'
run: bun --cwd packages/session-ui test:components
env:
CI: true
timeout-minutes: 15
- name: Run app component tests
if: ${{ !cancelled() && env.E2E_ENABLED == 'true' }}
if: matrix.suite.id == 'app-components'
run: bun --cwd packages/app test:components
env:
CI: true
timeout-minutes: 15
- name: Upload Playwright artifacts
if: always() && env.E2E_ENABLED == 'true'
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: playwright-${{ matrix.settings.name }}-${{ github.run_attempt }}
name: playwright-${{ matrix.settings.name }}-${{ matrix.suite.id }}-${{ github.run_attempt }}
if-no-files-found: ignore
retention-days: 7
path: |
@@ -272,3 +312,24 @@ jobs:
packages/session-ui/component-tests/playwright-report
packages/app/component-tests/test-results
packages/app/component-tests/playwright-report
# Branch rules require one e2e check per OS. These keep those names and pass only when every
# leg above passed, or when no leg was needed; a failing leg on either OS fails both checks.
e2e:
name: e2e (${{ matrix.os }})
needs: [affected, e2e-suite]
if: ${{ !cancelled() }}
strategy:
fail-fast: false
matrix:
os: [linux, windows]
runs-on: blacksmith-4vcpu-ubuntu-2404
steps:
- name: Check browser test results
env:
AFFECTED: ${{ needs.affected.result }}
SUITES: ${{ needs.e2e-suite.result }}
EXPECTED: ${{ needs.affected.outputs.e2e == 'true' && 'success' || 'skipped' }}
run: |
echo "affected packages: $AFFECTED, browser test legs: $SUITES (expected $EXPECTED)"
test "$AFFECTED" = success && test "$SUITES" = "$EXPECTED"
+138
View File
@@ -0,0 +1,138 @@
---
name: app-e2e-tests
description: Use when writing, changing, reviewing, or debugging Playwright e2e tests in packages/app/e2e (regression keepers and user stories). Covers the mocked opencode server harness and the Bun static server, per-test isolation, page-load and route cost, the suite-wide service-worker block, races with first mount, hover, measurement, clock, dialogs and shortcuts, projects, shards and worker scheduling, rehearsing Windows timing locally, and diagnosing a CI flake from its artifacts. Not for Storybook component tests or e2e/performance benchmarks.
---
# App e2e tests
Read `packages/app/e2e/AGENTS.md` and the Tests section of `packages/app/AGENTS.md` first. They define what to test, which locators to use, and how to assert. `packages/app/README.md` (E2E Testing) documents run modes and env vars. This skill covers what makes these tests slow or flaky in CI, which runs the suite as two shards per OS on 4-vCPU runners (`.github/workflows/test.yml:207-229`). Most races below were found on Windows.
All paths below are relative to `packages/app` unless they start with `packages/`, `services/` or `.github/`.
## What a test runs against
- **No opencode backend.** Each shard leg runs `bun --cwd packages/app test:e2e:built --shard=<n>/2` (`test.yml:274-279`). It builds once and starts one Bun static server, `e2e/utils/serve.ts`, on `127.0.0.1:${PLAYWRIGHT_PORT ?? 3000}`. All 5 workers share it (`playwright.config.ts:23-27`).
- `serve.ts` keeps vite preview's SPA fallback rules. Do not move built e2e back to vite preview. On case-insensitive file systems it synchronously reads the whole `dist/_assets` directory (about 3,100 files) for every asset request, so every worker's page loads wait in line. The `e2e/performance` configs still use it to keep their baselines comparable.
- **The API is an in-memory mock per page,** running in the test worker. `mockOpenCodeServer` (`e2e/utils/mock-server.ts:202`):
- answers `page.route("**/api/**")` with an Effect HttpApi handler;
- fakes `/api/event` SSE with an init-script `fetch` override;
- serves PTY sockets through `routeWebSocket`.
- **Unmocked routes fail the test** with a 501 and `Unmocked API request` (`mock-server.ts:403-411`). Add the route to `mock-server.ts` once instead of routing around it in a spec.
- **Build pages with the helpers:**
- `mockWorkspace`, `openSession`, `openDraft`, `openWorktreeDraft`, `mockRemoteServer`, `openSettings` (`e2e/utils/workspace.ts`);
- `setupTimeline` (`e2e/utils/timeline.ts:209`) for streamed timelines, `mockServers` (`mock-server.ts:495`) for several origins;
- `seed` (`e2e/utils/app.ts:61`) for storage, `holdRoute` (`app.ts:207`) to hold requests until you release them.
- **Deliver events** with the mock's `push`, which buffers until the app connects, or with `installSseTransport` (`e2e/utils/sse-transport.ts:60`), whose `send` resolves on delivery. After `page.reload()`, await `transport.waitForConnection()` before sending (`e2e/regression/timeline-stream.spec.ts:1700-1702`).
- **Windows-only failures are races, not Windows code paths.** Mock directories are `C:/OpenCode/<name>` on every OS (`workspace.ts:33`), and nothing touches the disk. Lazy chunks, stylesheets and responses finish out of order more often on the Windows runners.
## Isolation
- **No shared state between tests.** Each test gets a fresh context, mock handler and init scripts. Outside `e2e/service-worker`, which runs under its own config and shares builds through a worker fixture (`e2e/service-worker/cache.spec.ts:21`, `:74`), app e2e has no `beforeAll`, serial mode, `test.extend` or worker fixtures. Keep it that way so `-g` and `PLAYWRIGHT_FULLY_PARALLEL=1` keep working.
- **Handlers mutate the objects you pass.** Creating a session pushes into `sessions` (`mock-server.ts:839`). Renaming writes `session.title` (`:1340`), and VCS init writes `project.vcs` (`:1019`).
- Call `session()`/`project()` inside the test.
- `mockWorkspace` and `openSession` copy what you pass (`workspace.ts:36-48`).
- `mockOpenCodeServer` and `mockServers` use your objects as they are. Module-level fixtures like `multi-server.spec.ts:10-19` are therefore shared by every test in the file.
- **Timeline builders keep state per test attempt** (`timeline.ts:165-198`). Call stateful builders such as `assistantMessage` or `partUpdated` inside the test. Only pure ones such as `toolPart` belong at module scope.
- **Seed before the first `goto`.** `seed` writes storage once per tab behind a `sessionStorage` marker, so reloads keep what the app stored (`app.ts:59-90`). It cannot reset state mid-test.
## Keep it fast
- **Navigate once.** Every `goto` or `reload` is a cold load of the production bundle: about 150 requests per session open, about 125 of them static files. Each test has a new context, and any `page.route` disables the HTTP cache. Reach later states through the UI or through pushed events. Reload only when surviving a reload is the contract.
- **Service workers are already blocked suite-wide** (`serviceWorkers: "block"`, `playwright.config.ts:66-67`). Do not add a per-file block; the 11 in `e2e/regression` are redundant.
- Production registers `/sw.js` on load (`src/entry.tsx:54-55`) and precaches about 1,600 files (`globPatterns: ["**/*"]`, `vite.pwa.ts:34`). `e2e/service-worker/` covers it under its own config. The main config ignores that directory (`playwright.config.ts:33-36`), and CI runs it after shard 2 (`test.yml:281-285`).
- Opt back in with `test.use({ serviceWorkers: "allow" })` only when the worker is the contract. It never controls the first load (`clientsClaim: false`, `vite.pwa.ts:26-28`). After a reload it can control the page, and page routes may then miss its requests.
- Every built-mode page load logs Playwright's block warning. Console collectors must ignore it, as `captureConsoleWarnings` does (`e2e/utils/command-palette.ts:15-26`).
- **Match new routes with a RegExp or a query-aware glob, not a function.**
- A single function matcher makes Playwright intercept `**/*` for the page. Every static asset then round-trips to the test worker (250 continued requests in one Windows test).
- Existing `holdRoute` calls such as `review.spec.ts:51` and `mockMissingLocation` (`mock-server.ts:480`) still use functions and pay this. Converting one route gains nothing while another function route is registered on the page.
- Globs match the whole URL, so `**/api/vcs/init` misses `/api/vcs/init?location...`. Write `/\/api\/vcs\/init\?/` or `"**/api/session?*"` (`command-palette.spec.ts:10`, `:28`).
- **Use the stress fixture only when scale is the contract.** `fixture`, `mockStressTimeline` and `installStressSessionTabs` (`e2e/utils/session-fixture.ts:336`, `:436`, `:448`) serve a long timeline with 300-line diffs.
- Its cold mount reveals rows only after worker-rendered markdown arrives. Mounting one of its diffs blocked the renderer for 4-11 s on CI.
- The 14 regression files that use it held about half of the e2e flakes CI found.
- Prefer `openSession` or `setupTimeline` with the few messages the test needs.
- **Assert inside loops only when each step is the contract.** A web-first assertion that fails its first check retries after 100, 250, 500, then 1,000 ms. The 10-step loop at `mobile-timeline-scroll.spec.ts:688-693` takes about 8 s, mostly backoff.
- **Real-time waits cost their full length on every run and retry** (`settings-wsl.spec.ts:268-276` waits out a 10 s health check). Prefer `page.clock`:
- install it before the `goto` or `reload` whose timers you need (`timeline-stream.spec.ts:1700`);
- keep fast-forwards under the client's 45 s event-stream idle timeout (`packages/client/src/solid/connection.ts:35`).
- **Leave benchmark pacing out of regression tests.** The `sendAll` delays and `messageDelay` exist for benchmarks (`timeline.ts:306`, `mock-server.ts:82`). Hold message pages with `beforeMessagesResponse` instead.
## Wait for state, not time: races CI found
Most of these rarely reproduce on an idle local machine.
- **First mount happens in stages.** `openSession` and `expectSessionTitle` return once the composer is editable and a title is visible. Later the loading header's `<h1>` is replaced, and a cold timeline keeps its rows hidden while it scrolls itself to the bottom. Before you measure or hover in the session view, wait for something that only the final mount renders, such as the last `[data-timeline-row="UserMessage"]` or the row you click next.
- **Hovering during a scroll loses the tooltip.** A tooltip closes when its trigger scrolls, and Playwright's mouse never moves again. `session-summary.spec.ts:21-26` waits for the last row before it hovers; without that wait it needed a retry in 6 of 36 Windows runs.
- **One-shot measurements can hit a detached node.** `locator.evaluate` resolves the element, then evaluates in a second round trip. If the node is replaced in between, `getBoundingClientRect` returns an all-zero rect and `boundingBox` returns `null`. The subagent title-anchor test failed with "Expected: 0" in 11 runs until it waited for a timeline-only button (`subagent-child-navigation.spec.ts:60-64`). Take reference measurements once the final structure is in place. Polled reads re-resolve and are safe.
- **`goto` returns late, so a modal may already be open.**
- `goto` waits for `load`, which can fire after the app is already interactive.
- An open dialog sets `aria-hidden` on the app root, which hides everything behind it from role locators.
- What's New opens 500 ms after the changelog response, and it raced the Settings check in 11 of 36 Windows runs. Hold the request that opens a modal until readiness is asserted, as `startUpgraded` does (`whats-new.spec.ts:227-234`).
- **`pauseAt(new Date())` right after `install()` can throw** "Cannot fast-forward to the past", because the installed clock starts slightly ahead of the runner's clock. Install at an explicit time and pause at an offset from it (`tabs.spec.ts:443-445`).
- **A shortcut that does nothing is usually a product guard, not timing.** The global handler ignores keys while `dialog.active` (`src/shell/commands/command.tsx:489`). `active` is the top dialog that has not started closing (`packages/ui/src/context/dialog.tsx:52`, `:310-311`). A dialog that has started closing does not block keys during its 100 ms exit (`dialog.tsx:87`), but any open dialog does, including one you did not expect. Check that guard before you add a wait.
- **Shortcut tests fail on local macOS; that is not a regression.**
- The Desktop Chrome profile reports a Windows UA and `navigator.platform = "Win32"`, so the app (`IS_MAC`, `command.tsx:14`) expects Ctrl. On macOS, `ControlOrMeta` sends Meta.
- Every test that opens the palette through `openCommandPalette` (`e2e/utils/command-palette.ts:50`) fails locally and passes in CI, as do `tabs.spec.ts:835` and `timeline-cache.spec.ts:163`. Verify on Linux or in CI, or press `Control` in a throwaway copy. Do not edit tests for macOS.
- A new test can pick the modifier from the page, as `session-summary.spec.ts:29-30` does.
- **Font probes mislead.** `document.fonts.check()` can stay false after the font has loaded: when a lazy `@layer` stylesheet activates late, Chromium rebuilds font faces as unloaded. The code-font test failed outright in 9 of 36 Windows runs that way. Polling a probe that lays out text can make itself true. Await `document.fonts.ready`, lay out new text, and then check once (`timeline-cache.spec.ts:281-293`).
- **Use the harness's signals.** `holdRoute(...).arrived` resolves when the request reaches the route, and `transport.send` resolves after delivery. `setupTimeline(...).waitForPart` resolves once a part renders (`timeline.ts:328`).
- **Decide which side is wrong.** Three of eight investigated e2e flakes were product bugs, each since fixed in the product:
- a stale scroll offset restored when a scroll settles (`src/session/timeline/observe-element-offset.ts`);
- a video double-click that also entered native fullscreen (`packages/gui-extensions/src/file/artifact-view.tsx:617`);
- shortcuts dropped while a dialog closed.
If a user could hit the interleaving, fix the product and keep the assertion.
## Scheduling
- **Two projects split the suite** (`playwright.config.ts:69-86`). `chromium-touch-scroll` runs only `mobile-timeline-scroll.spec.ts`, which the `touchScroll` regex (`:29`) matches, with `fullyParallel: true`.
- Projects queue in declaration order, so its 37 tests start after every `chromium` file and spread across all workers. As one serial group, the file took 3-5 minutes in CI.
- A rename that the regex misses quietly puts the file back in `chromium` as that serial group.
- `--project chromium`, UI mode and the VS Code extension's default project skip the file.
- **In `chromium`, files are the scheduling unit.** `fullyParallel` is off unless `PLAYWRIGHT_FULLY_PARALLEL=1` (`:42`), so a file's tests run in order on one worker. A long file sets a floor and leaves an idle tail. New regressions go into the area's keeper file (`e2e/AGENTS.md`), so keep each case cheap.
- **Shards split whole files by test count, not duration** (`test.yml:219-222`). The touch project queues last, so its tests always fall in shard 2. To reproduce a leg's schedule, pass the same `--shard`.
- **Worker-scoped options fork a worker.** `launchOptions`, `channel`, `headless`, `video`, `trace`, `screenshot` and `defaultBrowserType` give a file its own worker hash.
- Playwright groups a project's files by worker hash in order of first appearance, so such a file runs after every default file in its project.
- Use test-scoped options instead: `viewport`, `deviceScaleFactor`, `hasTouch`, `isMobile`, `userAgent`, `colorScheme`, `serviceWorkers`, `locale`.
- Use `launchOptions` only when a Chromium flag is the contract, with a comment (`patch-border.spec.ts:5-9`).
- **Never spread `devices[...]` into `test.use`.** iPhone entries set `defaultBrowserType: "webkit"`, which forks a worker and needs a browser that CI never installs (`test.yml:269-272`). Copy the fields you need, as `mobile-timeline-scroll.spec.ts:23-28` does.
- **Retries are not free.** CI retries twice (`playwright.config.ts:44`). Each failure restarts the worker's browser and costs 10-30 s of cleanup on Windows. The first retry then reruns with a trace and a video (`:62-65`).
- **Timeouts are not a fix.** The limits are 60 s per test and 10 s per assertion (`playwright.config.ts:38-41`). `APP_READY_TIMEOUT` (30 s, `e2e/utils/waits.ts:4`) covers only first readiness.
- When one wait is genuinely long, scope the timeout to that assertion and say what takes the time. `settings-wsl.spec.ts:268-276` does this with `{ timeout: 20_000 }` for a 10 s health check.
- `test.setTimeout` does not lengthen assertions. `timeline-history.spec.ts:73` sets 240 s without a comment and still fails at the 10 s poll at `:127`.
## Before you push
Run from `packages/app`:
- [ ] Run in built mode, as CI does: `bun run test:e2e:built -- e2e/regression/<file>.spec.ts`. Dev mode serves unbundled modules, with the API on another origin (`playwright.config.ts:19-21`).
- [ ] Use a free port when another worktree or agent may hold 3000: `PLAYWRIGHT_PORT=4310 bun run test:e2e:built -- ...`. Built runs never reuse a server, and `serve.ts` fails on a busy port. Stay below 49152 on Windows: it reserves ports from there up and hands them out for outgoing connections (`services/www/src/docs/content/cli/web.mdx:43`, `packages/client/test/fixture/service-fixture.ts:108-109`).
- [ ] To repeat without rebuilding:
- build once with `VITE_OPENCODE_TEST_FIXTURES=1 bun run build`;
- keep `bun e2e/utils/serve.ts --host 127.0.0.1 --port 4310` running;
- run `PLAYWRIGHT_BUILD=1 PLAYWRIGHT_BASE_URL=http://127.0.0.1:4310 bun run test:e2e -- ...`.
- [ ] Repeat new or changed tests at CI concurrency without retries: `--repeat-each=10 --workers=5 --retries=0 -g "<title>"`. Run the file once with `PLAYWRIGHT_FULLY_PARALLEL=1` to prove that order does not matter.
- [ ] Rehearse Windows timing by delaying assets, not only the CPU. CPU throttling at 4x and 6x did not reproduce the tooltip or title-anchor races, but delayed responses did.
- In a throwaway copy, hold the suspect lazy chunk, stylesheet or API response with `holdRoute`, and release it 0.6-1.5 s after `arrived`.
- Route worker scripts with `page.context().route`.
- A race fix must fail before the fix and pass after it (`packages/app/AGENTS.md`, Tests).
- [ ] Check the cost on a noisy machine. Other agents add load, and local A/Bs at a load average of 20-35 were inconclusive.
- Compare the medians of interleaved before/after runs at `--workers=5`, or the step durations in the report (`bun run test:e2e:report`).
- Count every `goto` and `reload` you added.
- [ ] `bun run typecheck:e2e` reports 4 existing errors: `timeline-stream.spec.ts:1822`, `:1825`, and two `e2e/performance` probes. Add none. If you changed `playwright.config.ts`, update `test-browser/playwright-config.test.ts`.
## When CI flakes
- **Find it.** e2e runs on pull requests that affect `@opencode/app` or `@opencode/storybook`, including their workspace dependencies, and on every manual dispatch (`.github/workflows/test.yml:42-54`). It never runs on dev (`:28`).
- Each OS has the legs `app-1` and `app-2` (the shards), `session-ui-components` and `app-components`.
- The required `e2e (linux)` and `e2e (windows)` checks only aggregate those legs (`:316-335`).
- A pass on retry leaves a leg green. Check each Windows shard report's Flaky list, and make sure your new tests are not on it.
- **Download:** `gh run download <run-id> -n playwright-windows-app-2-1 -D <dir>`. Artifacts are named `playwright-<os>-<leg>-<run attempt>` (`test.yml:301-314`). App e2e results are in `<dir>/app/e2e/`.
- **In CI, the failing first attempt has no trace and no video** (`playwright.config.ts:62-65`).
- `test-results/<test>-<project>/` holds `error-context.md` (the aria snapshot at the failure) and `test-failed-1.png`.
- `<test>-<project>-retry1/` holds `trace.zip` and `video.webm` whether the retry passed or failed, plus failure files only if it failed. A second retry records neither.
- **Read `error-context.md` first.** An open dialog or an element with no accessible name explains most "element(s) not found" errors.
- **Get timings from the retry trace:** `bunx playwright show-trace <dir>/app/e2e/test-results/<test>-<project>-retry1/trace.zip`. To see which side won, compare when a screencast frame changed with when the response landed.
- **Get the transient state from a failing video,** sampled frame by frame (`ffmpeg -i video.webm -vf fps=4 frame-%03d.png`). That is how the tooltip race showed the tooltip closing in the same frame the timeline rows appeared.
- In CI, retry1's video shows the failure only if the retry failed too.
- Locally, a failing test keeps its video (`retain-on-failure`), so you can record the race with `--repeat-each` and delayed assets.
- **Open the report:** `bunx playwright show-report <dir>/app/e2e/playwright-report`. It shows step durations for every attempt, including passing ones.
+117
View File
@@ -0,0 +1,117 @@
---
name: component-tests
description: Use when writing, changing, debugging, or reviewing Storybook-based Playwright component tests. That covers specs in packages/app/component-tests or packages/session-ui/component-tests, `*.fixture.tsx` files there or beside source (such as packages/gui-extensions/src/browser/panel.fixture.tsx), the stories they mount, and the shared harness in packages/storybook (playwright/config.ts, playwright/story.ts, .storybook/main.ts, preview.tsx, mocks). Also use when a component test is flaky, passed on retry, or fails with "Execution context was destroyed", "Failed to fetch dynamically imported module", or `#storybook-root` hidden. Covers mount args, source modules imported by URL, Vite dependency pre-bundling and reloads, cold vs warm Storybook, mobile drawers, geometry, and checks before pushing.
---
# Component tests
Each package suite starts one Storybook/Vite dev server, and every worker shares it (`packages/storybook/playwright/config.ts:17-24`; CI uses 2 workers, `config.ts:15`). With `fullyParallel` (`config.ts:12`), the tests of one file run on several workers in any order. There is no backend: server, SDK and sync modules are in-page mocks. Every test gets a fresh context, and `mount` is a full iframe navigation (`packages/storybook/playwright/story.ts:37`). Slow or flaky component tests in CI have come from five sources: the shared server's dependency optimizer, module resolution that depended on the install layout, a cold first story, a product race (the mobile drawer), or an action that ran before the UI reached the state it needed.
Read these first rather than repeating them:
- `packages/storybook/playwright/README.md` covers layout, run commands and "Adding a test".
- `packages/app/AGENTS.md` "Tests" decides whether a test should exist, when theme or direction cases are allowed, and that a regression test must fail before the fix.
- `packages/app/e2e/AGENTS.md` "Test Hygiene" applies here unchanged.
## Stories and `mount`
- **Location.** Put the story next to the production component under `src/` of `ui`, `session-ui`, `app` or `gui-extensions`. Storybook indexes only the `stories` globs in `packages/storybook/.storybook/main.ts:44-49`.
- **Story ID.** It is the meta `id` if one is set (`packages/session-ui/src/components/session-review.stories.tsx:25`). Otherwise it is the kebab-cased `title`, then `--`, then the kebab-cased export. Check it at `http://127.0.0.1:6006/?path=/story/<id>`. A wrong ID never renders, so `mount` waits out its full 30 s root wait (`story.ts:39`) and then fails.
- **URL args can be dropped.** `mount(id, { args, globals })` writes them into the URL (`story.ts:20-36`). Storybook drops an arg when the story declares no `args`/`argTypes` entry for its key. It also drops one whose value is not `[A-Za-z0-9 _-]*`, a number, a hex color or `rgb()`/`hsl()`, which rules out paths, URLs and file names with dots. The only trace is the browser console warning "Omitted potentially unsafe URL args.", and the test then passes on the default scenario.
- Give every arg a typed default. With `args: { split: false }` (`session-review.stories.tsx:129`), `split:false` arrives as a boolean.
- Pick punctuated values inside the story, from a `scenario`-style arg.
- **Globals** are `theme`, `direction` and `locale` (`packages/storybook/.storybook/preview.tsx:106-122`). `mount` also sets `a11y.manual` (`story.ts:29-36`); caller globals override it.
- **Portaled UI.** `mount` returns `#storybook-root`. Dialogs, menus and drawers render outside it, so locate them from `page` (`packages/app/component-tests/composer.spec.ts:101-107`).
- **Server state** comes from the `resolve.alias` list in `viteFinal` (`main.ts:72-94`), which points app server, SDK and sync modules at `packages/storybook/.storybook/mocks/app/**`. Extend a mock rather than adding a server. Restore mock state in `onCleanup` (`mockProviderAuth`, `packages/app/src/providers/connect/dialog.stories.tsx:23`) so that switching stories in the Storybook UI does not inherit it. Tests reset it on every mount.
- **Requests the mocks do not answer.** Route them with `page.route`. That includes server endpoints such as `/api/fs/read` (`packages/session-ui/component-tests/read-image.spec.ts:20`) and external URLs such as favicons (`packages/session-ui/component-tests/markdown.spec.ts:217`).
## Fixtures imported by URL
Use these when the contract is not visible in a story, such as construction counts, unmount races or cache state.
- **Fixture file.** Put a `*.fixture.tsx` file in `component-tests/` or beside the source it drives (`packages/gui-extensions/src/browser/panel.fixture.tsx`). It exports a `mountX()` that renders into a host with a `data-testid` (`packages/session-ui/component-tests/basic-tool.fixture.tsx:7-46`). Never end the name in `.spec` or `.test`.
- **Mount it in three steps.**
1. Mount a light story first, so that the app styles load.
2. Import the fixture and call it inside `page.evaluate`.
3. Locate it with `page.getByTestId` (`packages/session-ui/component-tests/basic-tool.spec.ts:30-36`).
It renders outside the preview decorators, so it must supply its own providers (`packages/app/component-tests/browser-pane-restore.spec.ts:69-83`).
- **Module URLs.** Build each one with `sourceURL(new URL("<relative path with extension>", import.meta.url))` (`story.ts:10`), written as a string literal in the spec (`browser-pane-restore.spec.ts:6-24`). Any other spelling either fails to load or loads a second module instance whose contexts the page never provides; a hand-written `/@fs//...` is the documented second-instance case (`story.ts:6-9`). The literal also matters for pre-bundling (next section).
- **Aliases.** A module imported by URL is the real file. App code that reaches the same module through a `main.ts` alias gets the mock (`browser-pane-restore.spec.ts:95-96`). Decide which of the two the contract needs.
- **Spec imports.** Import source modules into the spec with `import type` only (`browser-pane-restore.spec.ts:2-4`). A value import runs browser code in the Node runner.
- **Async order.** Let the test decide the order through deferreds the fixture exposes (`mountExtensionHost`, `packages/app/component-tests/extension-host.fixture.tsx:135`). Await the outcome they lead to (`extension-host.spec.ts:46-77`), or poll in-page state with `until` (`extension-host.fixture.tsx:124-132`). Do not copy the fixed in-page `setTimeout` waits that other cases in `extension-host.spec.ts` (`:38`, `:88-90`, `:108-119`) use to prove a negative.
## Vite pre-bundling and reloads
`viteFinal` drops `storybook:optimize-deps-plugin` (`main.ts:105-108`) and sets `optimizeDeps` itself (`main.ts:56-67`). Its `entries` are every `*.stories.tsx` and `*.worker.ts` under the four `src/` trees, every module a component spec names by a `./` or `../` string literal ending in `.ts`/`.tsx` (collected at `main.ts:15-29`), and `preview.tsx`; `include` adds the Storybook preview runtime. Vite pre-bundles their bare imports before the first page loads. A dependency the scan misses is found on first import instead. If that changes chunks already served, Vite logs `✨ optimized dependencies changed. reloading` and sends `full-reload` with path `*` to every page in every worker, and requests with a stale `?v=` hash get a 504 "Outdated Optimize Dep".
- **The bar is zero reloads.** A cold run of either suite prints neither `new dependencies optimized` nor `optimized dependencies changed`; neither did the Linux and Windows CI legs. Dropping `preview.tsx` and `include` from `main.ts` brings one reload back, so these lines are the signal to watch.
- **Keep new code reachable by the scan.** A module path built at runtime, in a template literal, or without its extension is not collected, and neither is a spec named other than `*.spec.ts`. Name stories `*.stories.tsx`: Storybook indexes other extensions, but the scan reads only that one. Name workers `*.worker.ts`, since the scan does not follow `new Worker(new URL(…))`. Add an `optimizeDeps.include` entry only for a dependency the scan cannot reach. Vite names it in `✨ new dependencies optimized: …`, and `DEBUG=vite:deps` replaces that line with scan and discovery detail.
- **Symptoms.** "page.evaluate: Execution context was destroyed", "Failed to fetch dynamically imported module …/@fs/…", or fixture state that is gone right after `mount` ("Registrations: 1" not found, an empty tab strip).
- **Only `mount()` survives a reload,** because it navigates back to the same URL. A reload loses everything set up after it: `page.evaluate` imports, mounted fixtures, state from earlier clicks, and the elements your locators pointed at. Another worker's discovery can trigger it at any moment.
- **Fix reloads in the scan, never with retries, timeouts or import order.** The import-everything-before-mount `Promise.all` in `browser-pane-restore.spec.ts:43-58` (comment at `:56`) only narrowed the window. Before the entries existed, that file's `:123` and `:150` were retried in 31 CI jobs each, and failed attempts cost about 39-47 s (Linux) and 34 s (Windows) of worker time per run.
- **Clear the cache whenever entries matter.** Vite's `getConfigHash` covers `optimizeDeps.include`, `resolve` and plugin names, but not `entries`, and a valid `_metadata.json` skips the scan. A warm cache therefore never scans a new story or fixture, so it shows neither the reloads nor the absence of reloads that CI's cold scan would. Delete `packages/storybook/node_modules/.cache` before judging.
- **Resolve through package resolution, not paths into `node_modules`.** `main.ts:69-71` dedupes `@tanstack/solid-query` instead of aliasing it into `app/node_modules`, a path that exists only under bun's isolated linker. While Windows CI installed hoisted, that alias made every app story fail there, and 23 of 30 runs hit the step's 15-minute cap. CI now runs the same `bun install --frozen-lockfile` on every OS (`.github/actions/setup-bun/action.yml:66-68`), so such an alias would pass CI and still break a hoisted local install.
## Cold vs warm, and what a mount costs
- **CI is always cold.** Each suite runs in its own leg on a fresh runner (`test.yml:228-229`), so every leg starts Storybook with no cache and runs the full scan.
- **Do not count the first test.** In one CI run of this harness, the first test per worker took 5.7-7.0 s on Linux and 14-15 s on Windows. Warm tests had a median of 1.5 s (app) and 2.0 s (session-ui) on Linux and 2.4-2.6 s on Windows. A warm `mount` (navigation plus root wait) had a median of 1.0 s (app) and 1.5 s (session-ui) on Linux and 1.7-1.9 s on Windows, which is most of a typical test. Judge cost by warm attempts.
- **Local reuse.** Playwright reuses whatever answers on the port (`config.ts:20`; default 6006, `config.ts:3`). That hides cold cost and reloads, and with several worktrees another checkout's Storybook can serve your tests its own code. Set `PLAYWRIGHT_STORYBOOK_PORT` or `PLAYWRIGHT_STORYBOOK_URL` (`config.ts:3-4`). On Windows pick a port below 49152: the dynamic range starts there, and Hyper-V and WSL reserve blocks inside it (`netsh int ipv4 show excludedportrange protocol=tcp`). Two Storybooks in one checkout share, and race on, `packages/storybook/node_modules/.cache/storybook/<version>/<hash>/sb-vite`, so a separate port is not enough: use a separate worktree.
- **Keep mounts few.** Put one scenario in each test, and resize in place with `page.setViewportSize` (`composer.spec.ts:28-29`) instead of mounting again.
- `a11y.manual` makes addon-a11y skip its axe run after each render, so changing `a11y.test` in `preview.tsx:133-135` is not enforced by these tests. Assert accessibility in the spec when it is the contract.
- CI records video only on the first retry, next to the trace; local runs keep `retain-on-failure` (`config.ts:27-30`).
## Mobile, touch and drawers
- **Touch.** Use `story.use({ hasTouch: true, isMobile: true, viewport: { width: 390, height: 844 } })` inside a `story.describe` (`packages/session-ui/component-tests/session-timeline-mobile.spec.ts:3-4`). These options are test-scoped, so the shared workers stay. Prove that emulation took effect with `matchMedia("(hover: none)")` (`composer.spec.ts:244`), and interact with `tap()` or `page.touchscreen.tap` (`session-timeline-mobile.spec.ts:41-42`).
- **No `launchOptions`.** They are worker-scoped, so the file gets its own worker hash and its own workers. App e2e had to move `packages/app/e2e/regression/mobile-timeline-scroll.spec.ts:18` into its own `fullyParallel` project (`packages/app/playwright.config.ts:69-86`) because it otherwise formed one long serial group running alone on a single worker.
- **Drawers.** Below 768 px, pickers open in a bottom drawer (`composer.spec.ts:100-107`).
- @corvu/drawer 0.2.4 lost a close requested in the first frames after opening: focus stayed trapped in an off-screen sheet and `body` kept `pointer-events: none`. Before the fix, this caused most first-attempt failures of `composer.spec.ts:5`, in 17 of 31 Linux runs.
- `patches/@corvu%2Fdrawer@0.2.4.patch` (root `package.json` `patchedDependencies`) fixes it, so tests need no wait before pressing Escape or tapping outside.
- `composer.spec.ts:375-429` guards the patch. It dismisses in-page, before and as `data-opening` appears, because Playwright input cannot target those frames. Upgrading @corvu/drawer drops the patch, so rerun those tests.
- Before measuring or screenshotting a drawer, wait until it is fully in the viewport and has no `data-transitioning` (`packages/app/e2e/regression/mobile-model-pickers.spec.ts:25-26`).
- A stuck overlay is a product bug. Fix the product and guard it in-page, as the patch did, rather than waiting it out.
## Geometry, platforms, known failures
- **Fonts.** Inter's `@font-face` has no `font-display` (`packages/app/src/index.css:13-18`), so a story can lay out with fallback metrics and then shift. Windows CI saw 6.5 px in the composer overflow measurement (`composer.spec.ts:93-95`), which now waits first (`:25-26`). Before measuring, run `await page.evaluate(() => document.fonts.ready.then(() => undefined))` (`markdown.spec.ts:247`). The `.then` keeps the `FontFaceSet` from being returned to Node.
- **Page scroll.** Outside fullscreen, the preview frame is `calc(100vh - 2rem)` to fit Storybook's 1rem padding (`preview.tsx:82-84`). With `100vh`, every such story scrolled by 32 px, and any scroll-into-view shifted boxes (`composer.spec.ts:116` saw y go from 300 to 268). Do not give a story root `100vh`. A story taller than the viewport still scrolls, so measure relative to a container captured at the same moment, or use `parameters: { layout: "fullscreen" }`.
- **Shortcuts.** Write them as `ControlOrMeta+…` (`browser-pane-restore.spec.ts:134`). Derive expected labels from `navigator.platform` (`packages/app/component-tests/session-question-dock.spec.ts:121`).
- **Known local failure.** On macOS, `browser-pane-restore.spec.ts:123` fails after `ControlOrMeta+w` (Meta+W, `:134-135`), while CI (Control+W) passes. It is not your regression.
- **`story.fail`.** It waits out the full 10 s expect timeout on every run: `packages/session-ui/component-tests/file-tool.spec.ts:49-50` took 12.6 s on Linux CI and 14.8 s on Windows CI. Fix the product instead, or make the expected failure an immediate check once the state has settled.
## Before you push
From the owning package (`packages/session-ui` or `packages/app`):
1. **Repeat** at CI's worker count. Locally retries are already 0 (`config.ts:14`). Every attempt must pass: `bun run test:components -- component-tests/<file>.spec.ts --workers=2 --repeat-each=10`.
2. **Read durations** in `bunx playwright show-report component-tests/playwright-report`. Compare warm tests with the CI medians above. Anything much slower needs a reason in the work the test does.
3. **Rehearse load.** Late font swaps and focus restored after a menu closes (`composer.spec.ts:114-115`) race the test under load. In a throwaway copy of the spec, throttle before `mount` with `const cdp = await page.context().newCDPSession(page)` and then `await cdp.send("Emulation.setCPUThrottlingRate", { rate: 4 })`. Alternatively, repeat while the other suite runs.
4. **Run each suite cold** whenever you add a story, fixture, dependency, worker or lazy import, or change `packages/storybook`. From the repo root, once per suite, as CI runs each in its own leg. Playwright pipes Storybook's output into its own (`config.ts:22-23`), and a free port makes it start a fresh server:
```sh
rm -rf packages/storybook/node_modules/.cache
PLAYWRIGHT_STORYBOOK_PORT=6216 bun run --cwd packages/app test:components -- --workers=2 2>&1 | tee /tmp/app-components.log
grep -E "new dependencies optimized|optimized dependencies changed" /tmp/app-components.log
```
The `grep` must print nothing. Count optimizer events, not durations: under load, the same config ran anywhere from 127 to 189 s.
5. **Windows.** Check platform keys and labels and font-dependent geometry. The Windows component legs are the authoritative check.
- Do not skip on Windows, and do not raise `config.ts` timeouts, retries or the `mount` wait.
- If one test does genuinely expensive work, call `story.setTimeout(...)` in that test, with a comment that names the work.
6. **Confirm CI ran the component legs.** E2E never runs on pushes to dev (`test.yml:28`), so no post-merge run catches a regression.
- The `affected` gate filters on `@opencode/app` and `@opencode/storybook` (`test.yml:52-53`). `ui`, `session-ui` and `gui-extensions` count through app's dependencies. `workflow_dispatch` forces the legs on (`test.yml:48-51`).
- `test.yml` is listed in `globalDependencies` (`turbo.json:8`), so editing it marks every package affected.
- The required `e2e (linux)` and `e2e (windows)` checks also pass when no leg was needed (`test.yml:316-335`). Look for `e2e (<os>, session-ui-components)` and `e2e (<os>, app-components)`.
- If CI skipped them, report your local cold run in the PR.
## When CI flakes
- **Download the artifact.** Run `gh run download <run-id> -n playwright-<linux|windows>-<session-ui|app>-components-<attempt> -D <dir>` (`test.yml:301-314`). Results are in `<dir>/session-ui/component-tests/` or `<dir>/app/component-tests/`. Only the first retry has a trace and, in CI, a video: `test-results/<test>-components-retry1/`.
- **Find reloads.** Storybook's output reaches the job log with a `[WebServer]` prefix, so grep the log for `optimized dependencies changed`. In the retry trace, a reload shows up as any of:
- a second `iframe.html` load and a second `[vite] connecting...`;
- the deps `?v=` hash changing between requests;
- 504 "Outdated Optimize Dep" on `deps/*.js`.
+82
View File
@@ -0,0 +1,82 @@
---
name: tui-tests
description: Use when writing, fixing, or reviewing tests that render OpenTUI (testRender, createTestRenderer, createAppFixture) in packages/tui or packages/cli. Covers frame waits (waitForFrame, waitFor, waitForVisualIdle, flush), started vs non-started renderers, injected clocks, mock keyboard and mouse input, terminal sizes, cleanup and shared paths, and the 30s budget. Also use when a TUI test fails with "Timed out waiting for frame predicate after N passes", or when a tui test file is slow. For cli subprocess and service tests, use the unit-tests skill.
---
# TUI tests
packages/tui runs about 170 test files in one `bun test` process. CI runs it next to up to two other suites on 4-vCPU runners (`bun turbo test --affected --concurrency=3` in `.github/workflows/test.yml`), where it has taken 136-146s on Linux and 147-171s on Windows, most of it idle on frame pacing, production timers and sleeps. Most flakes come from waiting on the wrong signal and then running out of frames on a busy runner.
Read the root `AGENTS.md` Testing section (no `globalThis` mocks, run from the package directory) and its TUI Stories section. To drive the real TUI, use the `opencode-dev` skill. For CLI subprocesses, service deadlines, Effect `TestClock` and turbo test tasks, use the `unit-tests` skill.
## Frame budgets are not time
- `waitForFrame`, `waitFor` and `flush` give up after `maxPasses` (default 20). `waitForVisualIdle` gives up after `maxFrames` (default 20). One pass is one rendered frame (`DEFAULT_MAX_PASSES` in `@opentui/core/testing`). "Timed out waiting for frame predicate after 20 passes" comes from this budget, not from bun's timeout.
- **Started renderer** (`setup.renderer.start()`, as `createAppFixture` does at `packages/tui/test/fixture/app.ts:28`): frames tick at OpenTUI's default 30 fps, so 20 passes are about 0.66s. Production renders at `targetFps: 60` (`packages/tui/src/app.tsx:241`), so test frames are twice as slow as the real app.
- **Not started** (the default for `testRender` and `createTestRenderer`): `waitFor` and `waitForFrame` fail within milliseconds when no render is scheduled, and the error shows `isRunning: false`. In the same state `flush()` and `waitForVisualIdle()` return immediately without error; they do not wait for fetches or timers. Await the signal, then `renderOnce()`.
- Wait on frames only for something a frame produces. For anything else, wait on the signal itself:
- **Focus set on a timer.** `DialogSelect` focuses its filter with `setTimeout(..., 1)` (`packages/tui/src/ui/dialog-select.tsx:702`), which takes about 15ms on Windows. `typeText` sends keys to whatever is focused, so early keys are dropped and Enter then picks the default option. Put the focus in the predicate, as both dialog waits in `packages/tui/test/command-selection.test.tsx` do (`:68-70` for the model, `:75-80` for the variant): `setup.renderer.currentFocusedRenderable instanceof InputRenderable`. Before the variant wait had it, the test flaked in 5 CI runs in 20 hours, including a dev push, and a bigger budget did not help: it still failed with `maxPasses: 150`, because the keys were lost, not late. If a wait fails with the focus in the predicate, look for a state race, not the budget.
- **Markdown and code text.** `<markdown>` (`packages/tui/src/routes/session/message-parts.tsx:182`) draws no text until the shared tree-sitter worker replies, while frames keep ticking, so a plain `waitForFrame` can spend all 20 passes on a loaded runner with the text still pending. Use `waitForHighlightedFrame(setup, predicate, options?)` from `packages/tui/test/fixture/frame.ts`. When the predicate fails, it awaits every in-flight `CodeRenderable.highlightingDone` inside the frame predicate, and awaiting there does not use up passes. It accepts any setup with `renderer` and `waitForFrame`; app-lifecycle, session-group-navigation and session-home wait on transcript text this way. If the code under test accepts a client, inject `new MockTreeSitterClient({ autoResolveTimeout: 0 })` instead (`packages/tui/test/mini/scrollback.surface.test.ts:87`).
- **Requests and other state.** Await the deferred response your fetch handler returns. With no signal to await, poll with a wall-clock deadline instead of raising `maxPasses`: the file-local `waitForFrame(setup, matches)` at `command-selection.test.tsx:117` checks `captureCharFrame()` every 10ms for up to 2s. `wait` in `packages/tui/test/cli/tui/data.test.tsx:37` and `waitForModel` in `packages/tui/test/fixture/local.tsx:109` do the same for state.
- `waitForVisualIdle` returns on the first frame with `cellsUpdated === 0` by default. A frame waiting on a highlight is also quiet, so wait for the text before you measure layout or assert on it: `session-home.test.tsx:227` waits for "History message 0001" with `waitForHighlightedFrame` after `waitForVisualIdle()` instead of reading the frame directly.
- Settle steps cost frames. Each `waitForVisualIdle({ quietFrames: 3 })` takes at least 3 frames, about 100ms at 30 fps. `session-group-navigation.test.tsx` has 14 of them. When you know what you are waiting for, wait for that frame instead.
- Do not use `maxPasses` as a clock. Several waits do, and each assumes 33ms frames:
- `app-lifecycle.test.tsx:792`: 120 passes to cover the 1s reconnect delay after `setup.events.disconnect()` at `:784`;
- `app-lifecycle.test.tsx:1721-1723`: 200 passes per retry-countdown second;
- `component/dialog-shell-output.test.tsx:144`: 100 passes for a 1s poll, plus `Bun.sleep(1100)` at `:163` and `:182`;
- `session-panel.test.tsx:590`: 120 passes in `ready()` for the initial load.
With test frame rates scaled 4x, dialog-shell-output (3 tests) and session-activity-anchor (2 tests) failed. The same budgets are why tests cannot yet run at production fps. A larger budget is fine only for a long run of frame-driven work, such as scrolling 50 rows.
## Pick the renderer mode and clock
- **Component logic:** `testRender(() => <X />, { width, height })` without `start()`. Change state, `await app.renderOnce()`, then assert on `captureCharFrame()`. One frame, deterministic.
- **Time-driven renderables:** pass `clock: new ManualClock()`, call `renderer.pause()`, then advance the clock and `renderOnce()` (`fixture()` in `packages/tui/test/component/retry-provider.test.tsx:8`). `pause()` also stops `requestLive()` (spinners, animations) from starting the frame loop.
- **Clock order:** inject a clock first (OpenTUI `ManualClock`; Effect `TestClock` for Effect code, see `unit-tests`). Use `jest.useFakeTimers()` only when nothing is injectable: it patches the global timers of a process that runs every tui file, so restore them with `jest.useRealTimers()` in `finally` (`packages/tui/test/util/delayed-presence.test.ts:24-26`).
- **Whole app:** `createAppFixture` (`packages/tui/test/fixture/app.ts`) gives a started renderer, an in-process `Bun.serve` and `kittyKeyboard: true`. Call `await setup.ready` before the first wait. Passing `config` replaces the default `{ animations: false }`, so include `animations: false` yourself. The first use in a process pays `await import("../../src/app")`: about 1s idle, 12-25s under heavy load. Use it only when the behavior spans routes or data.
- **Server behavior:** use the existing `createFetch` and `createEventStream` fixture (`packages/tui/test/fixture/tui-client.ts:15`, `:69`) rather than spawning a server. The persistent PTY, for example, is faked as `/api/experimental/persistent-pty/...` routes plus a `Bun.serve` websocket (`packages/tui/test/session-wheel-focus.test.tsx:52`); real PTY behavior is tested in `packages/server/test/persistent-pty.test.ts`. Every fixture server listens on `port: 0` (`fixture/app.ts:32`) and is reached through `server.url`; never hard-code a port. Windows hands out ephemeral ports from 49152 up, so a fixed port in that range can already be taken by another connection.
## Keyboard and mouse
- Use `setup.mockInput`: `pressKey`, `typeText`, `pressEnter`, `pressEscape`, `pressArrow`, `pasteBracketedText`.
- Create renderers with `kittyKeyboard: true`. Without it, `mockInput` silently sends something else (OpenTUI 0.5.17):
| Input | Without kitty mode | With kitty mode |
| -------------------------------------------- | ----------------------------------------- | --------------- |
| `pressKey("u", { ctrl: true, shift: true })` | `ctrl+u` | `ctrl+shift+u` |
| `pressKey("2", { ctrl: true })` | `2` | `ctrl+2` |
| `pressEnter({ shift: true })` | `return` | `shift+return` |
| `pressEscape()` then `pressKey("a")` | `meta+a` (a lone Escape is held for 20ms) | `escape`, `a` |
- A second click on the same renderable within 500ms (renderer clock) and within 1 cell becomes a word or line selection. Do not sleep past that window: `Bun.sleep(550)` at `packages/tui/test/session-activity-anchor.test.tsx:120` costs 4.4s per file. Call `setup.renderer.clearSelection()` first, which resets the click history, or click at least 2 cells away. In a `ManualClock` renderer driven by `renderOnce()`, `clock.advance(501)` also works.
## Terminal sizes
- Always pass `width` and `height`. Otherwise the renderer uses `process.stdout.columns`: your terminal locally, 80 in CI.
- Cover layout at a narrow and a wide width, for example `test.each([100, 44])` (`packages/tui/test/app-lifecycle.test.tsx:13`). After `setup.resize(w, h)`, `await setup.renderOnce()` or `flush()` before asserting. Run any real-time sequence at one width only.
- Measure work by counting, not timing: mounted rows (`packages/tui/test/session-mount-budget.test.tsx`), rendered diff lines (`packages/tui/test/cli/tui/diff-viewer.test.tsx:2198`). `performance.now()` thresholds fail on slow Windows runners.
## Timers, cleanup and shared state
- A TUI test that takes over a second is usually waiting on a production constant; make it injectable instead of waiting it out. Two such constants: the shell output poll `setTimeout(poll, more ? 0 : 1_000)` (`packages/tui/src/component/dialog-shell-output.tsx:73`; 6 tests, 18.8s, 95% idle) and `reconnectDelay = 1_000` (`packages/client/src/solid/connection.ts:33`; about 1s per reconnect test). connection.ts already takes `idleTimeout` and `flushInterval` options, so add a sibling.
- Clean up with `await using` or `finally`: destroy the renderer and stop the fixture server. Cancel timers first, or they throw "TextBuffer is destroyed" into the next test.
- Remove the tmpdir last. Destroy the renderer and await the app task first, as `createAppFixture`'s `[Symbol.asyncDispose]` does (`fixture/app.ts:63`). Removing it under a pending write logs "Failed to persist" and flock "lock is compromised".
- `TestTuiContexts` (`packages/tui/test/fixture/tui-environment.tsx:32-35`) defaults `home` and `state` to fixed `/tmp/opencode/...` paths. When the tree mounts a provider that writes under `paths.state` (`StorageProvider` in `src/context/storage.tsx:145`, `LocalProvider`, or the prompt history, frecency and stash providers), pass `paths={{ state, home }}` built from `tmpdir()` (`test/fixture/fixture.ts:8`). Process-shared paths are what keep tui from parallel workers: `--parallel=2 --no-isolate` halved local wall time (162.9s to 80.7s). Isolated mode re-imports `src/app` in each of the 18 test files that load it, at 6x the CPU.
- Bun does not cancel a timed-out test body. It keeps running and can fail the next test or rerun as "Unhandled error between tests". Triage the first failure in a file; the ones after it may be leftovers.
- Import another package's test helpers by relative path only from a package in tui's workspace dependency closure. `@opencode/tui#test` depends on `transit` in `turbo.json`, which folds tui's whole workspace dependency closure into the test hash, so `data.test.tsx:7` reaching `../../../../core/test` is covered because tui depends on `@opencode/core`. A package outside that closure is not hashed, and a change there can replay a stale pass (see `unit-tests`, Turbo test tasks).
## Timeouts and failures
- The tui and cli test scripts run `bun test --timeout 30000`; Bun's default is 5s. In tui, that budget exists for the cold `src/app` import, not for slow waits.
- A frame-budget failure is not a timeout problem. Raising the test timeout does nothing for it, and raising `maxPasses` only hides the wrong wait.
- A per-test timeout below 30s, like the 15000 at `session-group-navigation.test.tsx:249`, must still cover the cold import when the file runs alone. New per-test timeouts name their work in a comment (see `unit-tests`, Know the budget).
- A frame-budget failure that reproduces on every run of one branch is a regression in that change, not a flake. dialog-shell-output failed "after 100 passes" in 21 of 29 tui runs on one PR stack and in 0 of about 102 elsewhere. Do not answer it with a bigger budget.
- Do not add `skipIf(process.platform === "win32")` to hide a timing flake; fix the wait. Windows timers have about 15ms resolution, so a 1ms `setTimeout` race that never shows on macOS fails there.
## Before you push
- From `packages/tui`: `bun test --timeout 30000 test/<file>`. This matches CI's budget and prints per-test milliseconds, which the package script's `--only-failures` hides.
- `bun test --timeout 30000 test/<file> --rerun-each 10`: all 10 must pass. The first iteration pays the cold import, so a timeout on iteration 1 under heavy load is that import, not your wait. Repeat while one other suite runs (for example `bun run test` in `packages/core`), not on an overloaded machine. Before its focus wait, the command-selection race failed 5 of 8 local runs under load.
- Force the race you suspect: temporarily slow the timer or reply (for example the focus `setTimeout` to 150ms). The test must still pass. Revert afterwards.
- Negative control: make the predicate impossible. The test must fail fast with a frame dump, not hang until the timeout.
- Windows-sensitive behavior to check for: timers under 16ms, renaming a file another process holds, process kill, and paths shown in frames. On pushes and pull requests the unit job runs `--affected`, so `@opencode/tui:test` is scheduled only when tui, a workspace package it depends on, or a `globalDependencies` file in `turbo.json` changed. In the `unit (windows)` log, confirm the lines prefixed `@opencode/tui:test:` are there with `cache miss, executing` and a pass, and compare its `Ran N tests across M files. [Xs]` line with a recent run that included tui. Per-file timing is only available locally.
+140
View File
@@ -0,0 +1,140 @@
---
name: unit-tests
description: Use when writing, reviewing, speeding up, or fixing a flaky `bun test` unit test in any package (core, cli, server, ai, codemode, util, client, sdk, plugin, http-recorder, merman, app src and test-browser, desktop, gui-extensions, ui, session-ui, latex, ...), except OpenTUI renderer tests (see tui-tests). Also use when a test "timed out after 5000ms" on Windows CI, fails only on Windows, when the unit job is slow, when adding cli subprocess or service tests, or when adding a package's test task to turbo.json. Covers controlling time instead of sleeping, per-test timeouts, process and git spawn cost on Windows, Windows-only failures, temp dirs and process state, leaks between files, and reading CI timeouts.
---
# Fast, Reliable Unit Tests
CI runs `bun turbo test --affected --concurrency=3` on 4-vCPU Linux and Windows runners (unit job in `.github/workflows/test.yml`), so each suite shares the CPU with two others, and Windows is the slower leg. Most slow or flaky unit tests here wait on real time, spawn too many processes, or assert wall-clock speed.
Read these first; this skill does not repeat them:
- Root `AGENTS.md`: the Testing and Style Guide sections.
- `packages/app/AGENTS.md` Tests (`packages/desktop` and `packages/gui-extensions` follow it): one owner per contract, and no production seams for tests.
- `packages/ai/AGENTS.md`: cassettes. The `effect` skill: `it.effect` and `it.live`.
Sibling skills: `tui-tests` (OpenTUI renderer tests in tui and cli), `app-e2e-tests` (Playwright in `packages/app/e2e`), `component-tests` (Storybook Playwright). This skill owns cli subprocess and service tests.
## Know the budget
- Bun's default per-test timeout is 5000ms. Check the package's `test` script:
- 30s: ai, cli, desktop, http-recorder, latex, merman, simulation, theme and tui pass `--timeout 30000`; core's `script/test.ts` passes `--timeout=30000`.
- 5s: client, httpapi-codegen and sdk pass `--timeout 5000`; app, codemode, function, gui-extensions, plugin, plugin-browser, script, server, session-ui, ui and util use the default.
- Size Windows risk by counting spawns, not by local wall time.
- npm.test.ts "installs a Git package from an npm ::path: subdirectory at a branch" takes 0.4s locally and hit 5000ms on Windows CI. Each Npm.add Git case makes about 75 git process events: 3 `clone --recurse-submodules`, which run the git-submodule shell script.
- Assume roughly 40ms per Git-for-Windows spawn (estimated from an earlier git.test run on Windows CI: ~24s for 564 spawns). Some core file groups run 5-9x slower on Windows than locally.
- Those `test.each` cases (`npm.test.ts:223`, `:251`) hit 5000ms in 13 of 45 Windows core runs; that is why core's runner now defaults to 30s (comment at `packages/core/script/test.ts:38`).
- A timeout loosens the budget only when it exceeds the package default.
- In a 5s package, work that legitimately needs longer gets a per-test timeout and a comment naming the work: `packages/server/test/fetch.test.ts:406-407` ("Real retries wait 18 \* 200 ms ...", `{ timeout: 10_000 }`). `test.each(table)(name, fn, 30_000)` takes it as the third argument. Use file-wide `setDefaultTimeout` only when every test in the file does such work.
- In core, the four file-level `setDefaultTimeout(30_000)` calls only restate the runner default, and a per-test `{ timeout: 15_000 }` (still in `tool-shell.test.ts`, `session-generate.test.ts` and others) is stricter than it. Do not add values at or below 30s there.
- Never absorb a sleep, poll or production interval with a larger timeout, `--retry`, or `skipIf(win32)`; remove the wait. Skip on Windows only when the platform lacks the capability, with a comment (`npm.test.ts:313`, symlinks).
## Control time; do not wait for it
- **Effect code.** `it.effect` from `packages/core/test/lib/effect.ts` runs on `TestClock`; `testEffect(layer)` adds your layer. server and cli import it from `../../core/test/lib/effect`; ai has `packages/ai/test/lib/effect.ts`.
- **Fork, then adjust.** Fork with `Effect.forkChild({ startImmediately: true })` (`packages/ai/test/http-timeout.test.ts:58`), or await a Deferred the code completes and then `Effect.yieldNow` (`:80-81`). Otherwise `TestClock.adjust` can run before the sleep is registered, and the join hangs until Bun's timeout.
- **Debounced streams and watchers.** `advance(condition)` and `drain` in `packages/core/test/lib/clock.ts` alternate one real 1ms macrotask with 500ms adjusts, because debounces register sleeps across fiber hops. Use `drain` (4 such steps) before a "nothing happened" assertion instead of `Bun.sleep(25)`. `advance`'s 100-step bound is right under TestClock, but a condition waiting on slow real work (a child, a large write) can run out of steps under load.
- **Real I/O between virtual steps.** `TestClock.withLive(Effect.sleep("10 millis"))`. `registered()` at `packages/cli/test/service.test.ts:740` tests the 5s registration watch with real file I/O under `it.effect`. This departs from the effect skill's "filesystem → `it.live`" on purpose: the timer is the contract.
- **Real events need `it.live`.** Under `it.effect` the clock moves only when the test adjusts it, so an Effect timeout on a path driven by real processes, sockets or file events never fires and a missing event hangs instead of failing. The AppProcess tests (`packages/core/test/process/process.test.ts:13-14`) use `it.live` because the spawner's 1-second post-exit capture deadline (`packages/util/src/cross-spawn-spawner.ts:322`) never fired under TestClock.
- **Give a racing component its own clock.** When a real-time deadline races slow setup, provide that component a `Clock` that only the test moves past the deadline. `packages/core/test/browser-idle.test.ts:24-38` wraps the live clock for `LocationActivity` (`:49-51`) and adds the TTL at `:84`, once the browser state is attached. Before, it waited out a real 2s TTL and failed on Windows CI with "RPC is unavailable: experimental.browser" when plugin activation was slow. Shortening a real TTL makes that race flakier.
- **Product Effect code must stay on the caller's clock**, which is what makes both patterns above possible. Read time through `Clock`, wait with `Effect.sleep` or `Schedule`, and run nested effects with the caller's context.
- A bare `Effect.runPromise` runs on the default real clock. McpStdio does this (`packages/core/src/mcp/stdio.ts:66`, `:82`, `:109`), so `packages/core/test/mcp.test.ts:832` waits the real 2s `CLOSE_GRACE` on every OS.
- Capture `yield* Effect.context()` and use `Effect.runPromiseWith(context)`, as `packages/cli/src/acp/agent.ts:27` does.
- **Code outside Effect** (app, desktop, ui, session-ui): `jest.useFakeTimers()` and `setSystemTime` from `bun:test`, restored in `afterEach` (`packages/desktop/src/main/extension/lifecycle.test.ts:27-32`, `packages/desktop/src/main/storage/drafts.test.ts:15-17`).
- **Advance fake timers to the next timer** (`jest.advanceTimersToNextTimer()`, `jest.runOnlyPendingTimers()`), not in small fixed steps. The 10ms-step `advance` at `lifecycle.test.ts:37` turns the 1,000-seed fuzz test (`:607`) into about 430k event-loop turns: 2.8-3.8s on Windows, 0.56s on Linux.
## Real-time waits: deadlines, not attempt counts
- Bound a real-time poll in milliseconds, generously, and return as soon as it holds: `until` at `packages/cli/test/service-lifecycle.test.ts:267` (30s), `eventually` at `packages/core/test/integration.test.ts:37` (10s).
- Attempt-count loops hide a small budget that shrinks under load. Do not copy `waitUntil` at `packages/core/test/config/reload.test.ts:371` (100 × 10ms; the skills test at `:57` timed out after 1.2s on a Linux dev push) or `packages/core/test/plugin/provider-azure.test.ts:219` (3000 × 1ms).
- Poll for every state you assert afterwards: the reload poll at `reload.test.ts:301-317` includes the skills that `:319-320` assert.
- Let the test, not a timer, release a child's next step. The login command in `integration.test.ts:230-254` prints its secret only after the test, having seen the pending status, writes a release file; it used to print after a fixed `Bun.sleep(50)`.
- Small timer gaps race too: `packages/core/test/process/process.test.ts:59-67` ordered stdout and stderr with 10ms and 20ms child timers and failed on Windows CI (`out 2` read before `err 1`); it now uses 100ms and 200ms.
## When the wait happens in another process
TestClock cannot reach a spawned server or worker. These production waits already cost real time:
- cli (about 60s of its roughly 2-minute suite): the 15s bind-retry deadline (`Date.now() + 15_000` in `packages/cli/src/server-process.ts`), the 5s registration watch (`packages/cli/src/services/service-registration.ts:63`), and fixed sleeps (`Bun.sleep(8_000)` at `service.test.ts:620`, `Bun.sleep(5_500)` at `service-lifecycle.test.ts:237`).
- core (about 8s locally): McpStdio `CLOSE_GRACE` 2s + `FORCE_KILL_AFTER` 2s (`stdio.ts:10-13`), Shell `forceKillAfter` 3s (`packages/core/src/shell.ts:306`, `:401`), and the 1s capture deadline in cross-spawn-spawner.
To avoid adding more:
- Test the timing logic in-process under TestClock (the `registered()` tests at `service.test.ts:270-299`). Keep real processes for exit codes, signals, stdio and port binding, with one test per escalation path. Do not add tests that wait out these constants.
- Shorten a production duration through an option, not by waiting it out. Precedent: real product options (`Flock.Options` in `packages/util/src/flock.ts:41-47`, `idleTimeout`/`flushInterval` in `packages/client/src/solid/connection.ts`) and client's hidden seam `withEnsureTiming` (`packages/client/src/service-timing.ts:31`, used by `packages/client/test/fixture/service-timing.ts`).
- For a spawned process the value must reach the child, as `timeoutMs` does through the worker payload at `packages/core/test/util/flock.test.ts:50-58`.
- server-process.ts has no override today, so its 15s tests cannot be shortened from the test side.
- app, desktop and gui-extensions forbid such seams (their AGENTS.md Tests sections); core, cli, util, client and tui have no such ban.
- Retry timing belongs in core under TestClock. `packages/server/test/fetch.test.ts:363-408` spends about 5.8s of server's 16s in real 200ms bind retries (`packages/core/src/plugin/provider/openai.ts:21`). The fixed ports 1455/1457 are the contract there; new server tests cover routing and error mapping only. Elsewhere bind port 0 (`packages/app/src/runtime/server/global-sync/bootstrap.test.ts:81`).
## Do not assert wall-clock speed
- `expect(performance.now() - startedAt).toBeLessThan(500)` failed on Windows at 510ms (`packages/ui/src/context/marked-parser.test.ts:84`); `packages/core/test/shell-scan/adversarial.test.ts:77` has the same shape. merman's layout audit no longer asserts its elapsed time.
- Count operations, or pick an input where a regression is catastrophic and assert only the result, so it trips the test timeout: `packages/codemode/test/openapi.test.ts:638` (depth 30 is 2^30 work without memoization). A ratio of two timings still fails on a load spike; if you keep one, use a generous factor and say it is timing-sensitive.
## Spawn less
- **Process start-up.** Each `bun run src/index.ts` CLI boot costs about 1.3s of CPU (the entry loads TUI `.tsx` through the preload in `packages/cli/bunfig.toml`). Test parsing and validation in-process; keep one or two real subprocess tests per file. Each cold bun child that imports the MCP SDK cost 1-3s; the MCP lifecycle tests, which spawned several, hit 5000ms on Windows until they moved to the in-process `resourceServer()` (`packages/core/test/mcp.test.ts:90`).
- **Spawned CLIs** use `isolatedEnv(root)` from `packages/cli/test/fixture/environment.ts`: isolated HOME, XDG and database, shared transpiler cache. `packages/cli/test/upgrade.test.ts:98` and `debug-paths.test.ts:24` set a private `XDG_CACHE_HOME` without `BUN_RUNTIME_TRANSPILER_CACHE_PATH`, so every spawn transpiles again; do not copy them.
- **Git.** Before the shared fixture below, a PATH shim counted about 2,850 git spawns per core run, and git.test took about 24s on Windows CI and 7s locally.
- Create repos with `packages/core/test/fixture/git.ts`. `initGit(directory, ...initArgs)` (`:24-27`) runs one `git init` and appends the fsmonitor, gpgsign and identity settings to `.git/config` in one write; `initRepo` (`:64-67`) adds an empty root commit (2 spawns; with one `git config` per key it took 6), and `gitRemote` builds on `initGit`.
- Do not write per-file `git init` plus `git config` copies. server still has two (`packages/server/test/vcs.test.ts:215-218`, `packages/server/test/worktree.test.ts:131-133`); server already imports core fixtures such as `tmpdir`.
- Use `-c user.name=… -c user.email=…` only for commits the test makes itself (`npm.test.ts:53`). Repos where production code commits later (snapshot, worktree, vcs) need repo-local identity.
- Keep identity repo-local. The unit job's "Configure git identity" step sets a global identity, but core's `script/test.ts` and cli's `isolatedEnv` replace HOME, so it is invisible there and visible to server and tui. That HOME isolation keeps core's missing-identity coverage: do not depend on CI's identity, and do not add a global gitconfig in core.
- **Independent children** start together (`Promise.all`, `packages/ai/test/exports.test.ts:63`). `packages/app/test-browser/playwright-config.test.ts` runs sequential `Bun.spawnSync` (3.5s on Windows, 1.4s on Linux); `packages/desktop/scripts/windows-installer.test.ts` makes 6 sequential cold `pwsh` starts for ACL reads, which one `pwsh` call could batch.
- **Size contention and thresholds to the claim.** `flock.test.ts:46` starts 16 bun workers; use only as many as still exceed the 4 CI vCPUs. A hard-coded threshold forces huge fixtures: `packages/core/test/git.test.ts:354` writes 2,100 files to cross `looseObjectLimit = 2048` (`packages/core/src/git.ts:50`), 2.7s locally and slower on Windows. Make the threshold an option with the production default, cross a small value in the test, and assert the default once.
## Windows-only failures
- Renaming onto a file another process holds open fails. cli `service.test.ts:462` failed on a dev push with `FileSystem.rename (...service-local.json.<uuid>.tmp)` from the temp-then-rename at `service-registration.ts:39`. Close handles the test holds; when two product processes race, fix the product, not the test.
- SIGTERM cannot be caught: `process.kill` ends the target at once with exit code 1, so a shutdown handler runs only on POSIX. Assert per platform with `catchesSigterm`, `stopSignal` and `stoppedExitCode` (`packages/client/test/fixture/service-fixture.ts:7-11`).
- Do not prove a stopped server released its port by binding it again. Windows hands out ephemeral ports from 49152 up, and any process, including suites running alongside, may take the port for an outgoing connection; a re-bind failed there with "Failed to start server. Is port 65518 in use?". Assert that nothing accepts connections (`expectNotListening`, `service-fixture.ts:108-117`).
- `os.tmpdir()` reads `TEMP` on Windows and `TMPDIR` on POSIX; set both for a child (`packages/util/test/global.test.ts:22-24`). Compare canonical paths with `fs.realpathSync.native`, which expands 8.3 short names such as `RUNNER~1` (`:84-86`).
- Reset a test socket once the request has arrived (`data`), not on `open`. Resetting on accept races the client's write, and on Windows the lost race is a write or connect error instead of a reset: `packages/util/src/retry.test.ts:25-30` recorded 2 of its 3 expected failures there. `packages/app/src/runtime/server/global-sync/bootstrap.test.ts:83-88` still resets on `open` and failed 3 of about 19 loaded local runs with `write EPIPE`, which `transientMessages` in `packages/util/src/retry.ts` does not list.
## Temp dirs, files, process state
- core's `script/test.ts` points HOME, XDG\_\* and TMPDIR (plus USERPROFILE, TMP and TEMP on Windows) at a fresh directory per run. Per-test dirs: `tmpdir()` (`await using`), `tmpdirScoped` or `withTempDir` from `packages/core/test/fixture/tmpdir.ts`.
- Close watchers, databases and children before the dir is removed. On Windows an open handle fails removal with `EBUSY`; `remove` in `tmpdir.ts` then forces a GC and retries every 100ms, up to 30 times.
- Restore process state: env with `withEnv` (`packages/core/test/fixture/env.ts`) in Effect tests and in `afterEach` elsewhere, real timers, and `setSystemTime()`.
- `CI=true` in the unit job, and Turbo passes it through. Code that reads `CI` takes another path there, so a test of the non-CI path unsets it itself: `packages/http-recorder/test/websocket.test.ts:132` wraps its record-mode case in `withEnvironment("CI", undefined, ...)`, because in CI that case replayed and waited forever for "open".
## Keep files independent without `--isolate`
- Except app, each suite runs all its files in one process with one module registry (core: 262 files), so state leaks between files.
- Do not use `mock.module`; it leaks across files.
- It is why app's scripts pass `--isolate`: app unit went from 2.4s to 9.9s locally, and unit plus browser from 5.3s to 12-20s on CI.
- `packages/cli/test/mini-config.test.ts:25` and `packages/core/test/plugin/provider-gitlab.test.ts:74` already leak in non-isolated suites; do not copy them.
- In Effect packages, provide the dependency through a test layer. In app, desktop and gui-extensions, drive the real module and entry point, and inject only through a parameter the product already has.
- Never add `--isolate` or bare `--parallel` (which implies `--isolate`) to a test script: ai went from 7.6s to 26.3s with `--parallel=2`.
- `--parallel=N --no-isolate` keeps the shared registry and measured 0.47-0.68x serial wall time at about the same CPU in core. It also exposed load-sensitive tests (browser-idle and integration's `eventually`, both since fixed).
- Adopting it is a runner decision for maintainers once CI passes on both OSes, not a fix for one slow test.
- Runtime imports run in every file that loads the module. `packages/desktop/src/main/storage/store.ts:3` imports `electron` only for `getStore`, so `src/main/extension/storage.test.ts` and `src/main/storage/store.test.ts` download the ~100MB Electron binary on a fresh install. On a first local run, storage.test.ts took 5.3s of file time for 0.1s of test bodies. Use `import type` for types (`packages/desktop/src/main/ipc-transport.test.ts:4`).
## Turbo test tasks
- `bun turbo test` runs only packages with an `@opencode/<pkg>#test` entry in `turbo.json`; all 24 packages with a `test` script have one. A new suite copies its neighbors (`"dependsOn": ["transit"], "outputs": []`); check with `bun turbo test --dry=json`. Suites without an entry rotted: client, util, sdk, http-recorder and merman needed fixes before CI could run them.
- `transit` runs nothing and depends on `^transit`, so a test hash covers the package's whole workspace closure. The global dependencies add root `package.json` (whose `packageManager` pins Bun), `bunfig.toml`, `patches/**`, `.npmrc`, `.github/actions/setup-bun/**` and `test.yml`.
- Tests do not wait for builds: workspace packages export their sources (`"./*": "./src/*.ts"` in `packages/core/package.json`), so a test must not read a dependency's `dist`. The build job's "Build workspace libraries" step checks the library builds on Linux.
- A package that compiles `src` with tsc keeps colocated tests out of the build (`"exclude": ["src/**/*.test.ts"]` in `packages/util/tsconfig.build.json`). Otherwise `bun test` also runs the compiled copies, as Windows CI did with `packages/util/dist/retry.test.js`.
## When CI flakes
- Most suites print only failures (`--only-failures`): `(fail) <name> [5000ms]` and `^ this test timed out after 5000ms`.
- When `killed 1 dangling process` and `# Unhandled error between tests` follow (for example `NpmInstallFailedError` with `SIGTERM` from a `git clone`), the test was still doing real work, not hanging.
- The unhandled error is the abandoned Effect failing after Bun killed its child, not a second bug. Count the work (see Before you push) before choosing a fix.
- Check whether the test also fails on dev pushes: `gh run list --workflow test.yml --branch dev --event push --status failure`. In one census before core's 30s default, 4 of 25 dev pushes went red, all on Windows unit tests (3 of them Npm.add 5s timeouts).
- Read whole job logs with `gh run view --log --job <id>`; `--log-failed` omits green jobs, whose `Ran N tests across M files. [Xs]` lines you need for comparison.
- Assert a child's stderr before its exit codes. `packages/core/test/util/effect-flock.test.ts:327-328` checks codes first, so its one CI failure never showed the cause.
## Before you push
Run from the package directory with the flags from its `test` script (app needs `--conditions` and `--preload`). In core use `bun run script/test.ts <file> …`, which forwards flags, isolates HOME and applies the 30s timeout.
- [ ] `bun test <file> --rerun-each 10` passes every time. Add `--randomize` for order dependence; reproduce a failure with `--seed=<n>`.
- [ ] Per-test durations: `--reporter=junit --reporter-outfile=<abs path>` (works through `script/test.ts`). Any test over about 1s does real work you can name.
- [ ] Windows: count spawns. `GIT_TRACE=<abs file>` logs roughly one `trace: built-in:` or `trace: exec:` line per git process; a logging `git` shim first on PATH also works. At about 40ms per spawn, compare with the package timeout.
- [ ] Rerun the file while the full package suite runs in another terminal; CI runs three suites on four vCPUs.
- [ ] Grep the diff for `Bun.sleep(`, `setTimeout(`, `Date.now() +`, `performance.now()`, `Effect.runPromise(` in product code, `mock.module`, `git config`, and literal port numbers.
- [ ] After CI: with `--only-failures`, the `unit (windows)` log hides passing durations. Compare your package's `Ran N tests across M files. [Xs]` line with a recent dev run's.
- [ ] New package suite: `bun turbo test --dry=json` lists `@opencode/<pkg>#test`.
+1
View File
@@ -151,6 +151,7 @@
"**/.sst",
"**/*.d.ts",
"**/sdk.gen.ts",
"packages/plugins/figma/skills/**",
".agent/**",
".agents/**",
".claude/**",
+1
View File
@@ -2,3 +2,4 @@ sst-env.d.ts
packages/desktop/src/bindings.ts
packages/client/src/generated/
packages/client/src/generated-effect/
packages/plugins/figma/skills/
+1
View File
@@ -166,6 +166,7 @@ const table = sqliteTable("session", {
- Avoid mocks as much as possible, you shouldn't be using globalThis.\* at all unless it's the only option.
- Test actual implementation, do not duplicate logic into tests
- Tests cannot run from repo root (guard: `do-not-run-tests-from-root`); run from package directories such as `packages/core`.
- Before writing or changing tests, read the matching skill in `.opencode/skills`: `unit-tests` (bun test), `tui-tests` (OpenTUI renderer tests), `app-e2e-tests` (Playwright in `packages/app/e2e`) or `component-tests` (Storybook Playwright). They cover what has made tests slow or flaky in CI.
## Checks
+202
View File
@@ -2,6 +2,208 @@
Release notes for OpenCode V2, newest first.
## v2.0.30 — 2026-10-15
### Highlights
- **Changed Files by Turn**: Enable **Settings → Preferences → Timeline → Changed files** to see each completed turn’s changed files, line counts, and expandable diffs. ([#55064](https://github.com/anomalyco/opencode/pull/55064))
- **Docked TUI Diffs**: Run `/diff` inside a session to open the diff viewer beside your work. Press `f` to switch between the side panel and full screen; the layout adapts automatically to narrower terminals. ([#47152](https://github.com/anomalyco/opencode/pull/47152), [#55574](https://github.com/anomalyco/opencode/pull/55574), [#55780](https://github.com/anomalyco/opencode/pull/55780))
- **Keyboard Tab Navigation**: Use **Option+↑/↓** to move between session tabs, or add **Shift** to jump between unread tabs. ([#54277](https://github.com/anomalyco/opencode/pull/54277))
### Core
#### Improvements
- Load local glob patterns and remote URLs configured through `instructions`, and refresh them when configuration changes. ([#55539](https://github.com/anomalyco/opencode/pull/55539))
- Honor `OPENCODE_DISABLE_CLAUDE_CODE` and `OPENCODE_DISABLE_CLAUDE_CODE_SKILLS` when discovering `.claude` skills. ([#55774](https://github.com/anomalyco/opencode/pull/55774))
- Publish a configuration schema that accepts both V1 and V2 configuration shapes during migration. ([#55524](https://github.com/anomalyco/opencode/pull/55524))
- Remove the retired session-sharing backend and unavailable `/share` command. ([#55716](https://github.com/anomalyco/opencode/pull/55716))
#### Bug fixes
- Use protocol-specific inference endpoints for OpenCode providers and accept `null` namespaces in Responses API function calls. ([#55680](https://github.com/anomalyco/opencode/pull/55680), [#55631](https://github.com/anomalyco/opencode/pull/55631))
- Fit compaction output limits to the request actually sent. ([#55613](https://github.com/anomalyco/opencode/pull/55613))
- Restore authenticated TinyFish web search by initializing its MCP session. Thanks [@terry-an-investor](https://github.com/terry-an-investor). ([#54730](https://github.com/anomalyco/opencode/pull/54730))
- Improve MCP compatibility by skipping unsupported catalog and codemode calls, advertising spec-compliant elicitation capabilities, and accepting `*.localhost` OAuth token endpoints. Thanks [@tsehla42](https://github.com/tsehla42) and [@donbowman](https://github.com/donbowman). ([#55474](https://github.com/anomalyco/opencode/pull/55474), [#55618](https://github.com/anomalyco/opencode/pull/55618), [#53196](https://github.com/anomalyco/opencode/pull/53196), [#55627](https://github.com/anomalyco/opencode/pull/55627))
- Treat empty provider and model names as omitted, and substitute an empty value for missing configuration-file references. ([#55465](https://github.com/anomalyco/opencode/pull/55465), [#55388](https://github.com/anomalyco/opencode/pull/55388))
- Default the Windows background service to port `45278`. ([#55547](https://github.com/anomalyco/opencode/pull/55547))
### TUI
#### Improvements
- Open `/diff` beside the current session by default, retain state when toggling full screen with `f`, and adapt the file tree and patch layout to terminal width. ([#47152](https://github.com/anomalyco/opencode/pull/47152), [#55574](https://github.com/anomalyco/opencode/pull/55574), [#55780](https://github.com/anomalyco/opencode/pull/55780))
#### Bug fixes
- Show `/fork`’s pending view reliably and keep it aligned with the file list. ([#55746](https://github.com/anomalyco/opencode/pull/55746), [#55751](https://github.com/anomalyco/opencode/pull/55751))
- Correct spacing and inactive key-hint styling in the docked diff panel. ([#55452](https://github.com/anomalyco/opencode/pull/55452), [#55467](https://github.com/anomalyco/opencode/pull/55467))
### Desktop
#### Improvements
- Show each completed turn’s changed files, line counts, and expandable diffs when **Settings → Preferences → Timeline → Changed files** is enabled. ([#55064](https://github.com/anomalyco/opencode/pull/55064))
- Navigate session tabs with **Option+↑/↓**, or add **Shift** to jump to the previous or next unread tab. ([#54277](https://github.com/anomalyco/opencode/pull/54277))
- Display delegations from the iOS app as **Voice** messages. ([#54426](https://github.com/anomalyco/opencode/pull/54426))
#### Bug fixes
- Open PowerShell in the selected project directory on Windows. ([#55710](https://github.com/anomalyco/opencode/pull/55710))
- Keep project settings accessible when the project folder is missing. ([#55553](https://github.com/anomalyco/opencode/pull/55553))
- Show the requested URL while `webfetch` is running. ([#55590](https://github.com/anomalyco/opencode/pull/55590))
### Extensions
#### Bug fixes
- Include MCP tool input as `metadata.input` in permission requests, allowing permission hooks to inspect the proposed call. Thanks [@lu-zero](https://github.com/lu-zero). ([#51062](https://github.com/anomalyco/opencode/pull/51062))
## v2.0.29 — 2026-10-14
### Highlights
- **Remote Device Pairing**: In **Settings → Pairing**, select **Pair device** to enable OpenTunnel remote access and get a QR code or copyable link. ([#55306](https://github.com/anomalyco/opencode/pull/55306))
- **Provider Account Management**: Use the connect dialog or **Settings → Providers** to switch, rename, remove, or add provider accounts. ([#54101](https://github.com/anomalyco/opencode/pull/54101))
- **Automatic Response Continuation**: Responses that reach their output-token limit now continue automatically, preserving partial output instead of stopping abruptly. ([#53876](https://github.com/anomalyco/opencode/pull/53876))
- **Trackpad Image Navigation**: Pinch to zoom and use two-finger scrolling to pan image and SVG previews. Select **Fit** to reset the view. ([#54590](https://github.com/anomalyco/opencode/pull/54590))
### Core
#### Improvements
- Automatically continue responses after an output-token limit, with bounded retries and clearer recovery for truncated tool calls. ([#53876](https://github.com/anomalyco/opencode/pull/53876))
- Stabilize access policies under the top-level `policies` configuration key while retaining compatibility with `experimental.policies`. ([#55297](https://github.com/anomalyco/opencode/pull/55297))
#### Bug fixes
- Give centrally managed configuration precedence over local and user configuration. ([#55267](https://github.com/anomalyco/opencode/pull/55267))
- Allow migrated V1 npm provider configuration to target built-in provider routes. ([#55254](https://github.com/anomalyco/opencode/pull/55254))
### TUI
#### Improvements
- Report working sessions and sessions awaiting permission or input through terminal program-status notifications. ([#55172](https://github.com/anomalyco/opencode/pull/55172))
### Desktop
#### Improvements
- Pair devices from **Settings → Pairing** through OpenTunnel remote access, with a QR code and copyable link. ([#55306](https://github.com/anomalyco/opencode/pull/55306))
- Manage provider accounts from the connect dialog and **Settings → Providers**, including switching, renaming, removal, and adding another account. ([#54101](https://github.com/anomalyco/opencode/pull/54101))
- Show session context tokens and accumulated family cost in the session view. ([#53785](https://github.com/anomalyco/opencode/pull/53785))
- Pinch to zoom and use two-finger scrolling to pan image and SVG previews; select **Fit** to reset. ([#54590](https://github.com/anomalyco/opencode/pull/54590))
- Cycle side-panel tabs with the configured previous-tab and next-tab shortcuts while the side panel is focused. ([#54899](https://github.com/anomalyco/opencode/pull/54899))
- Refresh the question composer and clarify timeline notices that apply only to a model variant. ([#54822](https://github.com/anomalyco/opencode/pull/54822), [#54880](https://github.com/anomalyco/opencode/pull/54880))
- Refine diff colors and move unread indicators into session tabs. ([#52551](https://github.com/anomalyco/opencode/pull/52551), [#53570](https://github.com/anomalyco/opencode/pull/53570))
#### Bug fixes
- Show steered messages as pending immediately and render inline attachments before their server echo arrives. ([#55251](https://github.com/anomalyco/opencode/pull/55251), [#54650](https://github.com/anomalyco/opencode/pull/54650))
- Preserve raw media data up to 256 MiB so artifact previews remain available. ([#55018](https://github.com/anomalyco/opencode/pull/55018))
- Retain session model selections when the model catalog refreshes. ([#54481](https://github.com/anomalyco/opencode/pull/54481))
- Close browser tabs from the address field and suppress incorrect missing-file notices for restored or already-open tabs. ([#54501](https://github.com/anomalyco/opencode/pull/54501), [#55022](https://github.com/anomalyco/opencode/pull/55022))
- Prevent a project-store eviction loop during launch and remove hover gaps between vertical tabs. ([#55078](https://github.com/anomalyco/opencode/pull/55078), [#54866](https://github.com/anomalyco/opencode/pull/54866))
### SDK
#### Improvements
- Export `lastAssistantWithUsage` from the Solid client to consistently locate the assistant step that determines current context usage. ([#53785](https://github.com/anomalyco/opencode/pull/53785))
#### Bug fixes
- Include all paginated child sessions when loading a session family for usage totals. ([#53785](https://github.com/anomalyco/opencode/pull/53785))
- Admit inline data-URL files into optimistic pending messages so attachments render immediately. ([#54650](https://github.com/anomalyco/opencode/pull/54650))
### Extensions
#### Improvements
- Add `ctx.permission.assert` for Effect and Promise plugins, allowing plugins to use configured permission rules and the native approval prompt. ([#54930](https://github.com/anomalyco/opencode/pull/54930))
#### Bug fixes
- Use Figma's public endpoint and default OAuth configuration, and support Git installations and development releases. ([#55252](https://github.com/anomalyco/opencode/pull/55252), [#55304](https://github.com/anomalyco/opencode/pull/55304))
- Resolve the Figma plugin peer dependency from its workspace. ([#55269](https://github.com/anomalyco/opencode/pull/55269))
- Associate each rejected Promise hook with its own tool call. Thanks [@1052326311](https://github.com/1052326311). ([#55263](https://github.com/anomalyco/opencode/pull/55263))
## v2.0.28 — 2026-10-13
### Highlights
- **Per-Project Auto-Accept**: Set **Settings → Projects → Auto-accept permissions** to override the default for one project. You can also press `mod+shift+a` in a session. ([#54839](https://github.com/anomalyco/opencode/pull/54839))
- **Release Highlights in the TUI**: After updating, the home screen shows the release highlights once. Run `/highlights` to reopen them, or disable automatic display with `highlights: false` in `cli.json`. ([#54969](https://github.com/anomalyco/opencode/pull/54969))
- **Native Windows ARM64 Support**: Windows ARM64 downloads, CLI installs, and desktop updates now use native ARM64 builds instead of x64 emulation. ([#54689](https://github.com/anomalyco/opencode/pull/54689), [#54971](https://github.com/anomalyco/opencode/pull/54971))
- **Continuous Gemini Responses**: Long Gemini and Vertex Gemini responses split by the provider now continue automatically as one response, including recovery from a dropped stream after a continuation checkpoint. ([#55056](https://github.com/anomalyco/opencode/pull/55056))
- **Official WinGet Packages**: Install V2 with `winget install --id Anomaly.OpenCode -e` or `winget install --id Anomaly.OpenCode.Desktop -e`. OpenCode upgrades WinGet installations through WinGet. ([#54808](https://github.com/anomalyco/opencode/pull/54808))
### Core
#### Improvements
- Continued split Gemini and Vertex Gemini responses automatically using provider continuation tokens. ([#55056](https://github.com/anomalyco/opencode/pull/55056))
- Added `settings.encoding` with `zstd`, `gzip`, and `none` values for provider, model, and variant HTTP request bodies. ChatGPT authentication defaults to Zstandard compression when no custom `baseURL` is set. Thanks [@esafak](https://github.com/esafak). ([#54932](https://github.com/anomalyco/opencode/pull/54932))
- Added provider-level compatibility defaults and `compatibility.cacheFormat` for Anthropic- and Alibaba-style prompt-cache markers. ([#54911](https://github.com/anomalyco/opencode/pull/54911), [#54945](https://github.com/anomalyco/opencode/pull/54945))
- Added official WinGet packages and WinGet-aware upgrade and uninstall support. ([#54808](https://github.com/anomalyco/opencode/pull/54808))
- Raised the default streamed-chunk timeout from 5 to 15 minutes for models that pause while reasoning. ([#55032](https://github.com/anomalyco/opencode/pull/55032))
#### Bug fixes
- Disabled Bun’s fetch idle timeout for provider requests, preventing long-running streams from ending early. ([#55007](https://github.com/anomalyco/opencode/pull/55007))
- Preserved mixed CRLF and LF line endings when the edit tool changes files. ([#53166](https://github.com/anomalyco/opencode/pull/53166))
- Preserved unknown V1 OpenAI-compatible model options in migrated request bodies. ([#54694](https://github.com/anomalyco/opencode/pull/54694))
- Stopped querying Azure resources during startup; Azure connections now ask for the resource name directly. ([#54870](https://github.com/anomalyco/opencode/pull/54870))
- Loaded the system configuration directory at the lowest precedence. Thanks [@rntdrts](https://github.com/rntdrts). ([#54921](https://github.com/anomalyco/opencode/pull/54921))
- Installed the native CLI and extracted ripgrep without PowerShell on Windows ARM64. ([#54955](https://github.com/anomalyco/opencode/pull/54955), [#54981](https://github.com/anomalyco/opencode/pull/54981))
### TUI
#### Improvements
- Added the post-update highlights dialog, `/highlights`, and the `highlights` alert setting. ([#54969](https://github.com/anomalyco/opencode/pull/54969))
#### Bug fixes
- Restricted slash-command autocomplete to the start of the prompt. Thanks [@OpeOginni](https://github.com/OpeOginni). ([#54857](https://github.com/anomalyco/opencode/pull/54857))
- Reported x64 emulation correctly when the TUI runs on Windows ARM64. ([#54984](https://github.com/anomalyco/opencode/pull/54984))
- Removed the stale `todowrite` label from tool output. ([#53966](https://github.com/anomalyco/opencode/pull/53966))
### Desktop
#### Improvements
- Added per-project auto-accept permission overrides under **Settings → Projects**, with `mod+shift+a` controlling the current project. ([#54839](https://github.com/anomalyco/opencode/pull/54839))
- Added a native **Windows (ARM64)** option to the download page. ([#54971](https://github.com/anomalyco/opencode/pull/54971))
#### Bug fixes
- Bundled native ARM64 terminal and CLI binaries in Windows ARM64 desktop builds, and moved emulated x64 installations to native ARM64 updates. Thanks [@mweinbach](https://github.com/mweinbach). ([#54689](https://github.com/anomalyco/opencode/pull/54689), [#54983](https://github.com/anomalyco/opencode/pull/54983))
- Included subagent sessions in displayed session costs. ([#55052](https://github.com/anomalyco/opencode/pull/55052))
- Loaded image and audio attachments in the review panel and opened video previews in an in-window theatre view. ([#55015](https://github.com/anomalyco/opencode/pull/55015), [#54696](https://github.com/anomalyco/opencode/pull/54696))
- Showed submitted prompts immediately and kept the **Working** marker above undelivered steers. ([#54047](https://github.com/anomalyco/opencode/pull/54047), [#55023](https://github.com/anomalyco/opencode/pull/55023))
- Fixed tab closing when collapsed side-panel tabs exist and restored focus correctly after stacked dialogs close. ([#54695](https://github.com/anomalyco/opencode/pull/54695), [#55038](https://github.com/anomalyco/opencode/pull/55038))
### SDK
#### Improvements
- Added request-body encoding and model/provider cache-format fields to generated client types. ([#54932](https://github.com/anomalyco/opencode/pull/54932), [#54945](https://github.com/anomalyco/opencode/pull/54945))
- Exported `CredentialApi` from the Promise client API. ([#52797](https://github.com/anomalyco/opencode/pull/52797))
### Extensions
#### Improvements
- Added an optional official Figma plugin with its MCP connection and six bundled Figma skills. ([#55049](https://github.com/anomalyco/opencode/pull/55049), [#55061](https://github.com/anomalyco/opencode/pull/55061))
- Exposed `credential.activate` to Effect and Promise server plugins. Thanks [@remorses](https://github.com/remorses). ([#52797](https://github.com/anomalyco/opencode/pull/52797))
#### Bug fixes
- Converted rejected Promise-based plugin tools into normal tool failures instead of crashing their execution path. ([#54913](https://github.com/anomalyco/opencode/pull/54913))
- Fixed the VS Code extension launching the V2 CLI with the removed `--port` argument. Thanks [@uyencss](https://github.com/uyencss). ([#49084](https://github.com/anomalyco/opencode/pull/49084))
## v2.0.27 — 2026-10-12
### Highlights
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">وكيل برمجة بالذكاء الاصطناعي مفتوح المصدر.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# مديري الحزم
npm i -g opencode-ai@latest # او bun/pnpm/yarn
npm i -g @opencode/cli@latest # او bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS و Linux (موصى به، دائما محدث)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">ওপেন সোর্স এআই কোডিং এজেন্ট।</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Package managers
npm i -g opencode-ai@latest # or bun/pnpm/yarn
npm i -g @opencode/cli@latest # or bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS and Linux (recommended, always up to date)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">O agente de programação com IA de código aberto.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Gerenciadores de pacotes
npm i -g opencode-ai@latest # ou bun/pnpm/yarn
npm i -g @opencode/cli@latest # ou bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS e Linux (recomendado, sempre atualizado)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">OpenCode je open source AI agent za programiranje.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Package manageri
npm i -g opencode-ai@latest # ili bun/pnpm/yarn
npm i -g @opencode/cli@latest # ili bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS i Linux (preporučeno, uvijek ažurno)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">Den open source AI-kodeagent.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Pakkehåndteringer
npm i -g opencode-ai@latest # eller bun/pnpm/yarn
npm i -g @opencode/cli@latest # eller bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS og Linux (anbefalet, altid up to date)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">Der Open-Source KI-Coding-Agent.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Paketmanager
npm i -g opencode-ai@latest # oder bun/pnpm/yarn
npm i -g @opencode/cli@latest # oder bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS und Linux (empfohlen, immer aktuell)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">El agente de programación con IA de código abierto.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Gestores de paquetes
npm i -g opencode-ai@latest # o bun/pnpm/yarn
npm i -g @opencode/cli@latest # o bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS y Linux (recomendado, siempre al día)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">L'agent de codage IA open source.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Gestionnaires de paquets
npm i -g opencode-ai@latest # ou bun/pnpm/yarn
npm i -g @opencode/cli@latest # ou bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS et Linux (recommandé, toujours à jour)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">Ο πράκτορας τεχνητής νοημοσύνης ανοικτού κώδικα για προγραμματισμό.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Διαχειριστές πακέτων
npm i -g opencode-ai@latest # ή bun/pnpm/yarn
npm i -g @opencode/cli@latest # ή bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS και Linux (προτείνεται, πάντα ενημερωμένο)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">L’agente di coding AI open source.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Package manager
npm i -g opencode-ai@latest # oppure bun/pnpm/yarn
npm i -g @opencode/cli@latest # oppure bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS e Linux (consigliato, sempre aggiornato)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">オープンソースのAIコーディングエージェント。</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# パッケージマネージャー
npm i -g opencode-ai@latest # bun/pnpm/yarn でもOK
npm i -g @opencode/cli@latest # bun/pnpm/yarn でもOK
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS と Linux(推奨。常に最新)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">오픈 소스 AI 코딩 에이전트.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# 패키지 매니저
npm i -g opencode-ai@latest # bun/pnpm/yarn 도 가능
npm i -g @opencode/cli@latest # bun/pnpm/yarn 도 가능
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS 및 Linux (권장, 항상 최신)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">The open source AI coding agent.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Package managers
npm i -g opencode-ai@latest # or bun/pnpm/yarn
npm i -g @opencode/cli@latest # or bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS and Linux (recommended, always up to date)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">AI-kodeagent med åpen kildekode.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Pakkehåndterere
npm i -g opencode-ai@latest # eller bun/pnpm/yarn
npm i -g @opencode/cli@latest # eller bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS og Linux (anbefalt, alltid oppdatert)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">Otwartoźródłowy agent kodujący AI.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Menedżery pakietów
npm i -g opencode-ai@latest # albo bun/pnpm/yarn
npm i -g @opencode/cli@latest # albo bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS i Linux (polecane, zawsze aktualne)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">Открытый AI-агент для программирования.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Менеджеры пакетов
npm i -g opencode-ai@latest # или bun/pnpm/yarn
npm i -g @opencode/cli@latest # или bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS и Linux (рекомендуем, всегда актуально)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">เอเจนต์การเขียนโค้ดด้วย AI แบบโอเพนซอร์ส</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="สถานะการสร้าง" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# ตัวจัดการแพ็กเกจ
npm i -g opencode-ai@latest # หรือ bun/pnpm/yarn
npm i -g @opencode/cli@latest # หรือ bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS และ Linux (แนะนำ อัปเดตเสมอ)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">Açık kaynaklı yapay zeka kodlama asistanı.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Paket yöneticileri
npm i -g opencode-ai@latest # veya bun/pnpm/yarn
npm i -g @opencode/cli@latest # veya bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS ve Linux (önerilir, her zaman güncel)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">AI-агент для програмування з відкритим кодом.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Менеджери пакетів
npm i -g opencode-ai@latest # або bun/pnpm/yarn
npm i -g @opencode/cli@latest # або bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS і Linux (рекомендовано, завжди актуально)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">Trợ lý lập trình AI mã nguồn mở.</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# Các trình quản lý gói (Package managers)
npm i -g opencode-ai@latest # hoặc bun/pnpm/yarn
npm i -g @opencode/cli@latest # hoặc bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS và Linux (khuyên dùng, luôn cập nhật)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">开源的 AI Coding Agent。</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# 软件包管理器
npm i -g opencode-ai@latest # 也可使用 bun/pnpm/yarn
npm i -g @opencode/cli@latest # 也可使用 bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS 和 Linux(推荐,始终保持最新)
+2 -2
View File
@@ -10,7 +10,7 @@
<p align="center">開源的 AI Coding Agent。</p>
<p align="center">
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://www.npmjs.com/package/@opencode/cli"><img alt="npm" src="https://img.shields.io/npm/v/@opencode/cli?style=flat-square" /></a>
<a href="https://github.com/anomalyco/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/anomalyco/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
@@ -50,7 +50,7 @@
curl -fsSL https://opencode.ai/install | bash
# 套件管理員
npm i -g opencode-ai@latest # 也可使用 bun/pnpm/yarn
npm i -g @opencode/cli@latest # 也可使用 bun/pnpm/yarn
scoop install opencode # Windows
choco install opencode # Windows
brew install anomalyco/tap/opencode # macOS 與 Linux(推薦,始終保持最新)
+349 -931
View File
File diff suppressed because it is too large. Load diff
+12 -87
View File
@@ -2,92 +2,6 @@ import { domain } from "./stage"
import { EMAILOCTOPUS_API_KEY } from "./app"
import { SECRET } from "./secret"
////////////////
// GATEWAY
////////////////
const zenLiteProduct = new stripe.Product("ZenLite", {
name: "OpenCode Go",
})
const zenLiteCouponFirstMonth50 = new stripe.Coupon("ZenLiteCouponFirstMonth50", {
name: "First month 50% off",
percentOff: 50,
appliesToProducts: [zenLiteProduct.id],
duration: "once",
})
const zenLiteCouponFirstMonth100 = new stripe.Coupon("ZenLiteCouponFirstMonth100", {
name: "First month 100% off",
percentOff: 100,
appliesToProducts: [zenLiteProduct.id],
duration: "once",
})
const zenLiteCouponThreeMonths100 = new stripe.Coupon("ZenLiteCoupon3Months100", {
name: "3 months 100% off",
percentOff: 100,
appliesToProducts: [zenLiteProduct.id],
duration: "repeating",
durationInMonths: 3,
})
const zenLiteCouponSixMonths100 = new stripe.Coupon("ZenLiteCoupon6Months100", {
name: "6 months 100% off",
percentOff: 100,
appliesToProducts: [zenLiteProduct.id],
duration: "repeating",
durationInMonths: 6,
})
const zenLiteCouponTwelveMonths100 = new stripe.Coupon("ZenLiteCoupon12Months100", {
name: "12 months 100% off",
percentOff: 100,
appliesToProducts: [zenLiteProduct.id],
duration: "repeating",
durationInMonths: 12,
})
const zenLitePrice = new stripe.Price("ZenLitePrice", {
product: zenLiteProduct.id,
currency: "usd",
recurring: {
interval: "month",
intervalCount: 1,
},
unitAmount: 1000,
})
const ZEN_LITE_PRICE = new sst.Linkable("ZEN_LITE_PRICE", {
properties: {
// Use existing Go resources in dev's checkout Stripe account.
product: $app.stage === "dev" ? "prod_U1tUscpmwtV2bG" : zenLiteProduct.id,
price: $app.stage === "dev" ? "price_1T3phhE7fOCwHSD4zS6w2NPy" : zenLitePrice.id,
priceInr: 92900,
firstMonth50Coupon: zenLiteCouponFirstMonth50.id,
firstMonth100Coupon: zenLiteCouponFirstMonth100.id,
threeMonths100Coupon: zenLiteCouponThreeMonths100.id,
sixMonths100Coupon: zenLiteCouponSixMonths100.id,
twelveMonths100Coupon: zenLiteCouponTwelveMonths100.id,
},
})
const zenBlackProduct = new stripe.Product("ZenBlack", {
name: "OpenCode Black",
})
const zenBlackPriceProps = {
product: zenBlackProduct.id,
currency: "usd",
recurring: {
interval: "month",
intervalCount: 1,
},
}
const zenBlackPrice200 = new stripe.Price("ZenBlackPrice", { ...zenBlackPriceProps, unitAmount: 20000 })
const zenBlackPrice100 = new stripe.Price("ZenBlack100Price", { ...zenBlackPriceProps, unitAmount: 10000 })
const zenBlackPrice20 = new stripe.Price("ZenBlack20Price", { ...zenBlackPriceProps, unitAmount: 2000 })
const ZEN_BLACK_PRICE = new sst.Linkable("ZEN_BLACK_PRICE", {
properties: {
product: zenBlackProduct.id,
plan200: zenBlackPrice200.id,
plan100: zenBlackPrice100.id,
plan20: zenBlackPrice20.id,
},
})
// Preview stages have no new Console or inference deployment to forward to.
const migrationDomain =
$app.stage === "production" ? "opencode.ai" : $app.stage === "dev" ? "dev.opencode.ai" : undefined
@@ -114,6 +28,10 @@ const ENTERPRISE_SALES_INBOX_EMAIL = new sst.Secret("ENTERPRISE_SALES_INBOX_EMAI
const SALESFORCE_CLIENT_ID = new sst.Secret("SALESFORCE_CLIENT_ID")
const SALESFORCE_CLIENT_SECRET = new sst.Secret("SALESFORCE_CLIENT_SECRET")
const SALESFORCE_INSTANCE_URL = new sst.Secret("SALESFORCE_INSTANCE_URL")
const CONSOLE_CRM_TOKEN = new sst.Secret("CONSOLE_CRM_TOKEN")
const CONSOLE_CRM_LOOKUP_URL = new sst.Linkable("CONSOLE_CRM_LOOKUP_URL", {
properties: { value: `https://${domain}/console/api/internal/console-account` },
})
const logProcessor = new sst.cloudflare.Worker("LogProcessor", {
handler: "packages/console/function/src/log-processor.ts",
@@ -134,7 +52,8 @@ new sst.cloudflare.x.SolidStart("Console", {
SALESFORCE_CLIENT_ID,
SALESFORCE_CLIENT_SECRET,
SALESFORCE_INSTANCE_URL,
new sst.Secret("CLOUDFLARE_ACCESS_CLIENT_ID"),
CONSOLE_CRM_TOKEN,
CONSOLE_CRM_LOOKUP_URL,
],
environment: {
//VITE_DOCS_URL: web.url.apply((url) => url!),
@@ -150,6 +69,12 @@ new sst.cloudflare.x.SolidStart("Console", {
...(flags ?? []),
"global_fetch_strictly_public",
])
// Same-zone fetch to inference re-enters as a public request and loses the client IP.
if (migrationDomain)
args.bindings = $resolve(args.bindings).apply((bindings) => [
...(bindings ?? []),
{ type: "service", name: "INFERENCE", service: `opencode-inference-${$app.stage}` },
])
args.tailConsumers = [{ service: logProcessor.nodes.worker.scriptName }]
},
},
-18
View File
@@ -1,18 +0,0 @@
import { SECRET } from "./secret"
import { shortDomain } from "./stage"
const storage = new sst.cloudflare.Bucket("EnterpriseStorage")
new sst.cloudflare.x.SolidStart("Teams", {
domain: shortDomain,
path: "packages/enterprise",
buildCommand: "bun run build:cloudflare",
link: [SECRET.SupportApiKey],
environment: {
OPENCODE_STORAGE_ADAPTER: "r2",
OPENCODE_STORAGE_ACCOUNT_ID: sst.cloudflare.DEFAULT_ACCOUNT_ID,
OPENCODE_STORAGE_ACCESS_KEY_ID: SECRET.R2AccessKey.value,
OPENCODE_STORAGE_SECRET_ACCESS_KEY: SECRET.R2SecretKey.value,
OPENCODE_STORAGE_BUCKET: storage.name,
},
})
-3
View File
@@ -5,9 +5,6 @@ sst.Linkable.wrap(random.RandomPassword, (resource) => ({
}))
export const SECRET = {
R2AccessKey: new sst.Secret("R2AccessKey", "unknown"),
R2SecretKey: new sst.Secret("R2SecretKey", "unknown"),
HoneycombApiKey: new sst.Secret("HONEYCOMB_API_KEY"),
HoneycombWebhookSecret: new random.RandomPassword("HoneycombWebhookSecret", { length: 24 }),
SupportApiKey: new sst.Secret("SUPPORT_API_KEY"),
}
+20
View File
@@ -0,0 +1,20 @@
import { shortDomain } from "./stage"
// Retains existing share data until it is deleted separately.
new sst.cloudflare.Bucket("EnterpriseStorage")
// The Share worker takes over the hostname of the retired Teams worker. Cloudflare rejects a second custom domain for
// the same hostname, so adopt the Teams domain and replace it, deleting the old one first.
$transform(cloudflare.WorkersCustomDomain, (_args, opts, name) => {
if (name !== "ShareDomain") return
opts.aliases = [
`urn:pulumi:${$app.stage}::${$app.name}::sst:cloudflare:SolidStart$sst:cloudflare:Worker$cloudflare:index/workersCustomDomain:WorkersCustomDomain::TeamsWorkerDomain`,
]
opts.deleteBeforeReplace = true
opts.replaceOnChanges = ["*"]
})
new sst.cloudflare.Worker("Share", {
domain: shortDomain,
handler: "packages/function/src/share.ts",
})
+29 -50
View File
@@ -100,9 +100,17 @@ else
fi
fi
# Git Bash and MSYS2 run as emulated x64 on Windows ARM64, so `uname -m` reports x86_64.
# The host CPU still shows in the `uname -s` suffix and in PROCESSOR_IDENTIFIER.
if [ "$os" = "windows" ] && [ "$arch" = "x64" ]; then
if [[ "$raw_os" == *-ARM64 || "${PROCESSOR_IDENTIFIER:-}" == ARM* ]]; then
arch="arm64"
fi
fi
combo="$os-$arch"
case "$combo" in
linux-x64|linux-arm64|darwin-x64|darwin-arm64|windows-x64)
linux-x64|linux-arm64|darwin-x64|darwin-arm64|windows-x64|windows-arm64)
;;
*)
echo -e "${RED}Unsupported OS/Arch: $os/$arch${NC}"
@@ -235,17 +243,6 @@ check_version() {
fi
}
unbuffered_sed() {
if echo | sed -u -e "" >/dev/null 2>&1; then
sed -nu "$@"
elif echo | sed -l -e "" >/dev/null 2>&1; then
sed -nl "$@"
else
local pad="$(printf "\n%512s" "")"
sed -ne "s/$/\\${pad}/" "$@"
fi
}
print_progress() {
local bytes="$1"
local length="$2"
@@ -275,52 +272,34 @@ download_with_progress() {
exec 4>/dev/null
fi
local tmp_dir=${TMPDIR:-/tmp}
local basename="${tmp_dir}/opencode_install_$$"
local tracefile="${basename}.trace"
rm -f "$tracefile"
mkfifo "$tracefile"
local headers="${output}.headers"
# Hide cursor
printf "\033[?25l" >&4
trap "trap - RETURN; rm -f \"$tracefile\"; printf '\033[?25h' >&4; exec 4>&-" RETURN
trap "trap - RETURN; rm -f \"$headers\"; printf '\033[?25h' >&4; exec 4>&-" RETURN
(
curl --trace-ascii "$tracefile" -fsL -o "$output" "$url"
) &
# Poll the file size on a timer so rendering cost stays fixed no matter how many bytes arrive.
# Read the size with ls because busybox wc -c reads the whole file.
curl -fsL -D "$headers" -o "$output" "$url" &
local curl_pid=$!
unbuffered_sed \
-e 'y/ACDEGHLNORTV/acdeghlnortv/' \
-e '/^0000: content-length:/p' \
-e '/^<= recv data/p' \
"$tracefile" | \
{
local length=0
local bytes=0
local length bytes
while kill -0 "$curl_pid" 2>/dev/null; do
if [ -f "$output" ]; then
length=$(grep -i '^content-length:' "$headers" 2>/dev/null | tail -n 1 | tr -dc '0-9' || true)
bytes=$(ls -ln "$output" | awk '{print $5}')
print_progress "$bytes" "${length:-0}"
fi
sleep 0.1 2>/dev/null || sleep 1
done
while IFS=" " read -r -a line; do
[ "${#line[@]}" -lt 2 ] && continue
local tag="${line[0]} ${line[1]}"
if [ "$tag" = "0000: content-length:" ]; then
length="${line[2]}"
length=$(echo "$length" | tr -d '\r')
bytes=0
elif [ "$tag" = "<= recv" ]; then
local size="${line[3]}"
bytes=$(( bytes + size ))
if [ "$length" -gt 0 ]; then
print_progress "$bytes" "$length"
fi
fi
done
}
wait $curl_pid
local ret=$?
local ret=0
wait "$curl_pid" || ret=$?
if [ "$ret" -eq 0 ]; then
bytes=$(ls -ln "$output" | awk '{print $5}')
print_progress "$bytes" "$bytes"
fi
echo "" >&4
return $ret
}
+3 -3
View File
@@ -1,7 +1,7 @@
{
"nodeModules": {
"x86_64-linux": "sha256-Nrl3q4qV3YKGnSoKDjs0HvFyviVhtNfKEmMUIoREITc=",
"aarch64-linux": "sha256-AfaHJIwoLA/9icnohKM2DL2dcmgSANfVT3oefOYBylE=",
"aarch64-darwin": "sha256-nat5x4P4yGHqqBbw64CT0B66dmR3oSV3Qic1vMGnE4Q="
"x86_64-linux": "sha256-foIqeQoc/G6w/9bd7OqC6mIxyQlCgbkPQWl3aHtb1l8=",
"aarch64-linux": "sha256-wiiiSjLyLhn0OFnh1Ug2CdAfwtpkncaUPLUI0TIucdA=",
"aarch64-darwin": "sha256-zQ26uuI0p+2tf7KYzcKLnPF+ERTumGz4uqezO9pObNg="
}
}
+4 -2
View File
@@ -2,7 +2,7 @@
"$schema": "https://json.schemastore.org/package.json",
"name": "opencode",
"description": "AI-powered development tool",
"version": "2.0.27",
"version": "2.0.30",
"private": true,
"type": "module",
"packageManager": "bun@1.4.2",
@@ -38,6 +38,7 @@
"workspaces": {
"packages": [
"packages/*",
"packages/plugins/*",
"services/*",
"packages/console/*",
"packages/stats/*"
@@ -183,6 +184,7 @@
"@ff-labs/fff-bun@0.10.5": "patches/@ff-labs%2Ffff-bun@0.10.5.patch",
"ghostty-web@github:anomalyco/ghostty-web#83c0a07": "patches/ghostty-web@0.3.0.patch",
"vite@8.2.2": "patches/vite@8.2.2.patch",
"@modelcontextprotocol/client@2.0.0": "patches/@modelcontextprotocol%2Fclient@2.0.0.patch"
"@modelcontextprotocol/client@2.0.0": "patches/@modelcontextprotocol%2Fclient@2.0.0.patch",
"@corvu/drawer@0.2.4": "patches/@corvu%2Fdrawer@0.2.4.patch"
}
}
+1 -1
View File
@@ -182,7 +182,7 @@ console.log(response.answers.department.choice)
console.log(response.answers.refund.probability)
```
`TypeSafeAI` reads `TYPESAFE_API_KEY`. `OpenCodeZen` exposes the same selector and reads
`TypeSafeAI` reads `TYPESAFE_API_KEY`. `OpenCode` exposes the same selector and reads
`OPENCODE_API_KEY`. OpenRouter and Vercel AI Gateway use the same provider shape:
```ts
+1 -1
View File
@@ -1,6 +1,6 @@
{
"$schema": "https://json.schemastore.org/package.json",
"version": "2.0.27",
"version": "2.0.30",
"name": "@opencode/ai",
"type": "module",
"license": "MIT",
+15 -11
View File
@@ -171,17 +171,7 @@ const countHints = (request: LLMRequest) =>
)
export const applyCachePolicy = (request: LLMRequest): LLMRequest => {
const route = request.model.route.id
if (!RESPECTS_INLINE_HINTS.has(route)) return request
const policy =
(route === "openrouter" || route === "vercel-ai-gateway-messages") &&
(request.cache === undefined || request.cache === "auto")
? gatewayPolicy(request.model.id)
: route === "alibaba-chat" && (request.cache === undefined || request.cache === "auto")
? request.model.id.toLowerCase().startsWith("qwen")
? QWEN
: NONE
: resolve(request.cache)
const policy = selectPolicy(request)
if (!policy.tools && !policy.system && !policy.messages) return request
const hint = makeHint(policy.ttlSeconds)
@@ -193,3 +183,17 @@ export const applyCachePolicy = (request: LLMRequest): LLMRequest => {
if (tools === request.tools && system === request.system && messages === request.messages) return request
return LLMRequest.update(request, { tools, system, messages })
}
// A declared cache format overrides the route allowlist and its model-ID heuristics.
const selectPolicy = (request: LLMRequest): CachePolicyObject => {
const format = request.model.compatibility?.cacheFormat
const route = request.model.route.id
const auto = request.cache === undefined || request.cache === "auto"
if (format === "alibaba") return auto ? QWEN : { ...resolve(request.cache), tools: false }
if (format === "anthropic") return resolve(request.cache)
if (!RESPECTS_INLINE_HINTS.has(route)) return NONE
if (!auto) return resolve(request.cache)
if (route === "openrouter" || route === "vercel-ai-gateway-messages") return gatewayPolicy(request.model.id)
if (route === "alibaba-chat") return request.model.id.toLowerCase().startsWith("qwen") ? QWEN : NONE
return AUTO
}
@@ -516,7 +516,7 @@ const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request:
)
// Bedrock-Claude shares Anthropic's 4-breakpoint cap. Spend the budget in
// tools → system → messages order to favour the highest-impact prefixes.
const breakpoints = BedrockCache.breakpoints(request.model.id)
const breakpoints = BedrockCache.breakpoints(request.model)
const toolConfig = (() => {
if (flattened.tools.length === 0) return undefined
return {
+161 -21
View File
@@ -1,10 +1,15 @@
import { Effect, Option, Schema } from "effect"
import { Effect, Option, Schema, Stream } from "effect"
import { Tool } from "@opencode/schema/tool"
import { Route } from "../route/client.js"
import { Auth } from "../route/auth.js"
import { Endpoint } from "../route/endpoint.js"
import { Framing } from "../route/framing.js"
import { Protocol } from "../route/protocol.js"
import {
HttpTransport,
type Transport,
type TransportExecution,
type TransportPrepareInput,
} from "../route/transport/index.js"
import {
AIError,
LLMEvent,
@@ -25,6 +30,7 @@ import { GeminiGenerateContent } from "./utils/gemini-generate-content.js"
import { Lifecycle } from "./utils/lifecycle.js"
const ADAPTER = "gemini"
const CONTINUATION = "CONTINUATION"
// Google documents this sentinel for replaying Gemini 3 function calls after their original signature was lost.
const SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator"
// Gemini 2.5 rejects a budget under the model's minimum: 512 on Flash-Lite, the highest, and 128 on Pro.
@@ -212,6 +218,7 @@ const GeminiBodyFields = {
tools: optionalArray(GeminiTool),
toolConfig: Schema.optional(GeminiToolConfig),
generationConfig: Schema.optional(GeminiGenerationConfig),
continuationToken: Schema.optional(Schema.String),
}
const GeminiBody = Schema.Struct(GeminiBodyFields)
export type GeminiBody = Schema.Schema.Type<typeof GeminiBody>
@@ -254,7 +261,9 @@ interface ParserState {
readonly finishReason?: string
readonly hasToolCalls: boolean
readonly promptFeedback?: GeminiPromptFeedback
readonly usage?: Usage
readonly usage?: GeminiUsage
/** Usage of the earlier requests of a response Gemini continued across requests. */
readonly continuedUsage?: ReadonlyArray<GeminiUsage>
readonly lifecycle: Lifecycle.State
readonly reasoningSignature?: string
readonly textSignature?: string
@@ -497,7 +506,11 @@ const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request: LLMReque
// `cachedContentTokenCount` subset. `candidatesTokenCount` is *exclusive*
// of `thoughtsTokenCount` — visible-only, not a total — so we sum the two
// to produce the inclusive `outputTokens` the rest of the contract expects.
const mapUsage = (usage: GeminiUsage | undefined, metadataKey: string) => {
const mapUsage = (
usage: GeminiUsage | undefined,
metadataKey: string,
metadata: Record<string, unknown> = usage ?? {},
) => {
if (!usage) return undefined
// Explicit provider nulls decode as `null`; normalize to `undefined` so the
// token arithmetic below treats them like absent counts.
@@ -518,10 +531,35 @@ const mapUsage = (usage: GeminiUsage | undefined, metadataKey: string) => {
cacheReadInputTokens: cached,
reasoningTokens: thoughts,
totalTokens: ProviderShared.totalTokens(promptTokens, outputTokens, usage.totalTokenCount ?? undefined),
providerMetadata: providerMetadata(metadataKey, usage),
providerMetadata: providerMetadata(metadataKey, metadata),
})
}
// Each continued request re-bills the output so far as input. Reporting the first request's input with all output keeps
// input plus output equal to the response's final context size, under-reporting billed input; the summed billed counts
// remain in provider metadata.
const mapContinuedUsage = (requests: ReadonlyArray<GeminiUsage>, metadataKey: string) => {
const sum = (field: keyof GeminiUsage) =>
ProviderShared.sumTokens(...requests.map((usage) => usage[field] ?? undefined))
return mapUsage(
{
promptTokenCount: requests[0].promptTokenCount,
cachedContentTokenCount: requests[0].cachedContentTokenCount,
candidatesTokenCount: sum("candidatesTokenCount"),
thoughtsTokenCount: sum("thoughtsTokenCount"),
},
metadataKey,
{
promptTokenCount: sum("promptTokenCount"),
cachedContentTokenCount: sum("cachedContentTokenCount"),
candidatesTokenCount: sum("candidatesTokenCount"),
thoughtsTokenCount: sum("thoughtsTokenCount"),
totalTokenCount: sum("totalTokenCount"),
requests: requests.length,
},
)
}
const mapFinishReason = (finishReason: string | undefined, hasToolCalls: boolean): FinishReason => {
if (finishReason === undefined) return hasToolCalls ? "tool-calls" : "unknown"
if (finishReason === "STOP") return hasToolCalls ? "tool-calls" : "stop"
@@ -545,7 +583,7 @@ const finish = (state: ParserState): ReadonlyArray<LLMEvent> => {
const promptBlockReason =
state.finishReason === undefined ? (state.promptFeedback?.blockReason ?? undefined) : undefined
const finishReason = state.finishReason ?? promptBlockReason
if (finishReason === undefined && state.usage === undefined) return []
if (finishReason === undefined && state.usage === undefined && state.continuedUsage === undefined) return []
const events: LLMEvent[] = []
let lifecycle = state.lifecycle
@@ -573,7 +611,10 @@ const finish = (state: ParserState): ReadonlyArray<LLMEvent> => {
promptBlockReason === undefined ? mapFinishReason(finishReason, state.hasToolCalls) : "content-filter",
raw: finishReason,
},
usage: state.usage,
usage:
state.continuedUsage === undefined
? mapUsage(state.usage, state.providerMetadataKey)
: mapContinuedUsage([...state.continuedUsage, state.usage ?? {}], state.providerMetadataKey),
providerMetadata:
state.promptFeedback === undefined
? undefined
@@ -582,7 +623,19 @@ const finish = (state: ParserState): ReadonlyArray<LLMEvent> => {
return events
}
const step = (state: ParserState, event: GeminiEvent) => {
const step = (state: ParserState, event: GeminiEvent | NextRequest) => {
// Usage is cumulative within one request, so the next request of the same response counts from zero.
if (event instanceof NextRequest)
return Effect.succeed([
{
...state,
finishReason: undefined,
promptFeedback: undefined,
usage: undefined,
continuedUsage: [...(state.continuedUsage ?? []), state.usage ?? {}],
},
[],
] as const)
if (ProviderShared.isRecord(event.error)) {
const body = ProviderShared.encodeJson(event)
return Effect.fail(
@@ -604,14 +657,13 @@ const step = (state: ParserState, event: GeminiEvent) => {
return Effect.fail(
ProviderShared.eventError(state.route, `Invalid ${state.route} stream event`, ProviderShared.encodeJson(event)),
)
const candidate = event.candidates?.[0]
const nextState = {
...state,
promptFeedback: event.promptFeedback ?? state.promptFeedback,
usage: event.usageMetadata
? (mapUsage(event.usageMetadata, state.providerMetadataKey) ?? state.usage)
: state.usage,
usage: event.usageMetadata ?? state.usage,
finishReason: candidate?.finishReason ?? state.finishReason,
}
const candidate = event.candidates?.[0]
if (candidate?.finishReason && mapFinishReason(candidate.finishReason, state.hasToolCalls) === "error")
return Effect.fail(
ProviderShared.eventError(
@@ -620,11 +672,7 @@ const step = (state: ParserState, event: GeminiEvent) => {
ProviderShared.encodeJson(event),
),
)
if (!candidate?.content)
return Effect.succeed([
{ ...nextState, finishReason: candidate?.finishReason ?? nextState.finishReason },
[],
] as const)
if (!candidate?.content) return Effect.succeed([nextState, []] as const)
const events: LLMEvent[] = []
let hasToolCalls = nextState.hasToolCalls
@@ -784,12 +832,104 @@ const step = (state: ParserState, event: GeminiEvent) => {
nextReasoningId,
nextTextId,
seenCallIds,
finishReason: candidate.finishReason ?? nextState.finishReason,
},
events,
] as const)
}
// =============================================================================
// Transport
// =============================================================================
const GeminiCheckpoint = Schema.Struct({
candidates: optionalNull(
Schema.Array(
Schema.Struct({
finishReason: optionalNull(Schema.String),
continuationToken: optionalNull(Schema.String),
}),
),
),
})
const decodeCheckpoint = Schema.decodeUnknownOption(GeminiCheckpoint)
/** Marks where the transport starts another request for the same response; provider JSON can never match it. */
class NextRequest {}
export interface Prepared {
readonly http: HttpTransport.HttpPrepared<string>
readonly input: TransportPrepareInput<GeminiBody>
}
const sse = HttpTransport.sseJson.with<GeminiBody>()
/**
* SSE transport that continues responses Gemini splits across requests. Chunks carry `continuationToken` checkpoints,
* and a request that reaches its output cap finishes with `CONTINUATION`. The transport resends the original body with
* the latest token, which also resumes a request that ended or dropped before finishing.
*/
export const transport: Transport<GeminiBody, Prepared, unknown> = {
id: sse.id,
prepare: (input) => sse.prepare(input).pipe(Effect.map((http) => ({ http, input }))),
execute: (prepared, request, runtime) =>
Effect.gen(function* () {
const route = request.model.route.id
const label = `${request.model.provider}/${route}`
// Frames are parsed once here, so errors recover each frame's raw text for their body.
const raw = new WeakMap<object, string>()
const respond = (execution: TransportExecution<string>): Stream.Stream<unknown, AIError> =>
Stream.suspend(() => {
let token: string | undefined
let finishReason: string | undefined
let dropped: AIError | undefined
return execution.frames.pipe(
Stream.mapEffect((frame) =>
ProviderShared.parseJson(route, frame, `Invalid ${label} stream event`).pipe(
Effect.map((event) => {
if (typeof event === "object" && event !== null) raw.set(event, frame)
const candidate = Option.getOrUndefined(decodeCheckpoint(event))?.candidates?.[0]
token = candidate?.continuationToken ?? (candidate?.finishReason ? undefined : token)
finishReason = candidate?.finishReason ?? finishReason
return event
}),
),
),
Stream.catchIf(
// A connection failure may resume; a timeout keeps its meaning and ends the response.
(error) => error.reason._tag === "Transport" && error.reason.code !== "Timeout",
(error) => {
dropped = error
return Stream.empty
},
),
Stream.concat(
Stream.suspend(() => {
if (token !== undefined && (finishReason === undefined || finishReason === CONTINUATION))
return Stream.concat(Stream.succeed(new NextRequest()), next(token))
if (dropped) return Stream.fail(dropped)
if (finishReason === CONTINUATION)
return Stream.fail(ProviderShared.eventError(label, "Gemini continued the response without a token"))
return Stream.empty
}),
),
)
})
const next = (continuationToken: string) =>
Stream.unwrap(
sse
.prepare({ ...prepared.input, body: { ...prepared.input.body, continuationToken } })
.pipe(
Effect.flatMap((continued) => sse.execute(continued, request, runtime)),
Effect.map(respond),
),
)
const first = yield* sse.execute(prepared.http, request, runtime)
return {
frames: respond(first),
http: first.http,
body: (frame) => (typeof frame === "object" && frame !== null ? raw.get(frame) : undefined),
}
}),
}
// =============================================================================
// Protocol And Gemini Route
// =============================================================================
@@ -806,8 +946,8 @@ export const protocol = Protocol.make({
// Gemini's schema rules are this API's default, including for tuned endpoints whose IDs do not name Gemini.
sanitizer: "gemini",
stream: {
event: Protocol.jsonEvent(GeminiEvent),
initial: (request) => ({
event: Schema.Union([Schema.instanceOf(NextRequest), GeminiEvent]),
initial: (request): ParserState => ({
route: `${request.model.provider}/${request.model.route.id}`,
providerMetadataKey: request.model.route.providerMetadataKey ?? String(request.model.provider),
hasToolCalls: false,
@@ -830,7 +970,7 @@ export const route = Route.make({
baseURL: DEFAULT_BASE_URL,
}),
auth: Auth.none,
framing: Framing.sse,
transport,
})
export * as Gemini from "./gemini.js"
+3 -1
View File
@@ -417,7 +417,9 @@ export const fromRequest = Effect.fn("MistralChat.fromRequest")(function* (reque
frequency_penalty: request.generation?.frequencyPenalty,
presence_penalty: request.generation?.presencePenalty,
stop: request.generation?.stop,
prompt_cache_key: request.cache === "none" ? undefined : (options.promptCacheKey ?? request.promptCacheKey),
prompt_cache_key: ProviderShared.sendsPromptCacheKey(request)
? (options.promptCacheKey ?? request.promptCacheKey)
: undefined,
safe_prompt: options.safePrompt,
document_image_limit: options.documentImageLimit,
document_page_limit: options.documentPageLimit,
@@ -169,7 +169,12 @@ export const transport = <Body>(options: Options): Transport<Body, Prepared, str
})
return {
http: {
request: ProviderShared.jsonPost({ url: parts.url, body: parts.bodyText, headers: parts.headers }),
request: ProviderShared.jsonPost({
url: parts.url,
body: parts.bodyText,
headers: parts.headers,
encoding: input.request.http?.encoding,
}),
framing: Framing.sse,
middleware: input.middleware,
},
+4 -2
View File
@@ -334,14 +334,14 @@ export const StreamItem = Schema.StructWithRest(
id: Schema.optional(Schema.String),
call_id: Schema.optional(Schema.String),
name: Schema.optional(Schema.String),
namespace: Schema.optional(Schema.String),
namespace: optionalNull(Schema.String),
arguments: Schema.optional(Schema.String),
encrypted_content: optionalNull(Schema.String),
}),
[Schema.Record(Schema.String, Schema.Unknown)],
)
export type StreamItem = Schema.Schema.Type<typeof StreamItem>
export type OutputItem = StreamItem & { readonly id: string }
export type OutputItem = StreamItem & { readonly id: string; readonly namespace?: string }
// Responses-compatible providers put error details at the top level, under `error`, or under
// `response.error`, and gateways reshape them freely: strings, numeric codes, extra fields. Those
@@ -946,6 +946,8 @@ const resolveItem = (
index: number | undefined,
): OutputItem => ({
...item,
// Some gateways serialize an absent namespace as null.
namespace: item.namespace ?? undefined,
id:
item.id ??
(index === undefined ? undefined : state.outputItems[index]) ??
+8 -2
View File
@@ -24,6 +24,7 @@ import {
} from "../schema/index.js"
import { classifyProviderFailure } from "../provider-error.js"
import { isRecord, JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared.js"
import { cacheControl } from "./utils/cache.js"
import { OpenAIOptions } from "./utils/openai-options.js"
import { Lifecycle } from "./utils/lifecycle.js"
import { ToolStream } from "./utils/tool-stream.js"
@@ -827,15 +828,16 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
request.model.compatibility?.zaiToolStream ?? detectZaiToolStream(provider, baseURL, request.model.id)
const hasHistory = hasToolHistory(request.messages)
const hasActiveTools = flattened.tools.length > 0
const lowering = { ...options, cacheControl: options.cacheControl ?? declaredCacheControl(request) }
return {
model: request.model.id,
messages: yield* lowerMessages(flattened.request, options),
messages: yield* lowerMessages(flattened.request, lowering),
tools:
flattened.tools.length === 0
? hasHistory
? []
: undefined
: flattened.tools.map((tool) => lowerTool(tool, options, supportsStrictMode)),
: flattened.tools.map((tool) => lowerTool(tool, lowering, supportsStrictMode)),
tool_choice: hasActiveTools && request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined,
stream: true as const,
...(supportsUsageInStreaming ? { stream_options: { include_usage: true } } : {}),
@@ -853,6 +855,10 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
}
})
// Provider wrappers that pass their own marker writer keep it; otherwise a declared cache format adds one.
const declaredCacheControl = (request: LLMRequest) =>
request.model.compatibility?.cacheFormat === undefined ? undefined : cacheControl()
// =============================================================================
// Stream Parsing
// =============================================================================
+40 -5
View File
@@ -14,6 +14,7 @@ import {
type MediaPart,
type OpenString,
type ProviderID,
type RequestEncoding,
type TextPart,
type ToolEntry,
type ToolResultPart,
@@ -39,10 +40,15 @@ export const knownString = <Known extends string>() =>
export const OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH = 64
// Body-level `prompt_cache_key` is off when caching is disabled or the model
// explicitly rejects the field. Header-based affinity is unaffected.
export const sendsPromptCacheKey = (request: LLMRequest) =>
request.cache !== "none" && request.model.compatibility?.supportsPromptCacheKey !== false
// OpenAI limits `prompt_cache_key` to 64 chars; DeepSeek and Zai inherit the same
// limit via their OpenAI-compatible APIs. Clamp with unicode-aware slicing.
export const promptCacheKey = (request: LLMRequest): string | undefined => {
if (request.cache === "none" || request.promptCacheKey === undefined) return undefined
if (!sendsPromptCacheKey(request) || request.promptCacheKey === undefined) return undefined
const chars = Array.from(request.promptCacheKey)
if (chars.length <= OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH) return request.promptCacheKey
return chars.slice(0, OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH).join("")
@@ -373,11 +379,40 @@ export const validateWith =
* send JSON with a stale content type. The body is passed pre-encoded so
* routes can choose between
* `Schema.encodeSync(payload)` and `ProviderShared.encodeJson(payload)`.
* A `zstd` or `gzip` encoding compresses the body and sets `content-encoding`;
* it falls back to plain JSON when the runtime has no zlib.
*/
export const jsonPost = (input: { readonly url: string; readonly body: string; readonly headers?: Headers.Input }) =>
HttpClientRequest.post(input.url).pipe(
HttpClientRequest.setHeaders(Headers.set(Headers.fromInput(input.headers), "content-type", "application/json")),
HttpClientRequest.bodyText(input.body, "application/json"),
export const jsonPost = (input: {
readonly url: string
readonly body: string
readonly headers?: Headers.Input
readonly encoding?: RequestEncoding
}) => {
const headers = Headers.set(Headers.fromInput(input.headers), "content-type", "application/json")
const compressed = compressBody(input.body, input.encoding)
if (!compressed)
return HttpClientRequest.post(input.url).pipe(
HttpClientRequest.setHeaders(headers),
HttpClientRequest.bodyText(input.body, "application/json"),
)
return HttpClientRequest.post(input.url).pipe(
HttpClientRequest.setHeaders(Headers.set(headers, "content-encoding", compressed.encoding)),
HttpClientRequest.bodyUint8Array(compressed.body, "application/json"),
)
}
function compressBody(text: string, encoding: RequestEncoding | undefined) {
if (encoding === undefined || encoding === "none") return undefined
// Looked up at call time instead of imported: a runtime without node:zlib or its zstd export
// (browsers, older Node, some workerd setups) sends plain JSON rather than failing to load this module.
const zlib = globalThis.process?.getBuiltinModule?.("node:zlib")
try {
const body = encoding === "zstd" ? zlib?.zstdCompressSync?.(text) : zlib?.gzipSync(text)
return body && { encoding, body }
} catch {
// Compression is an optimization, so a failure sends plain JSON instead of failing the request.
return undefined
}
}
export * as ProviderShared from "./shared.js"
@@ -1,5 +1,5 @@
import { Schema } from "effect"
import type { CacheHint } from "../../schema/index.js"
import type { CacheHint, LLMRequest } from "../../schema/index.js"
import { newBreakpoints, ttlBucket } from "./cache.js"
// Bedrock cache markers are positional: emit a `cachePoint` block immediately
@@ -28,14 +28,17 @@ const CLAUDE_5M = [
// Callers share the four-breakpoint budget across system, messages, and tools.
export const BEDROCK_BREAKPOINT_CAP = 4
export const breakpoints = (modelID: string) => {
export const breakpoints = (model: LLMRequest["model"]) => {
// Substring matching also handles regional prefixes and model-bearing ARNs.
const short = CLAUDE_5M.some((id) => modelID.includes(id))
const short = CLAUDE_5M.some((id) => model.id.includes(id))
return {
...newBreakpoints(BEDROCK_BREAKPOINT_CAP),
// An explicit Anthropic cache format opts opaque IDs such as application inference profile ARNs in.
// Assume modern Claude releases retain caching support; older generations need an explicit exception.
// Other model families use implicit caching where available.
supported: modelID.includes("anthropic.claude-") && (short || !LEGACY_CLAUDE.some((id) => modelID.includes(id))),
supported:
model.compatibility?.cacheFormat === "anthropic" ||
(model.id.includes("anthropic.claude-") && (short || !LEGACY_CLAUDE.some((id) => model.id.includes(id)))),
ttl1h: !short,
}
}
@@ -117,7 +117,12 @@ export const make = (
encodeBody: Schema.encodeSync(Schema.fromJsonString(Body)),
})
const response = yield* executor.execute(
ProviderShared.jsonPost({ url: parts.url, body: parts.bodyText, headers: parts.headers }),
ProviderShared.jsonPost({
url: parts.url,
body: parts.bodyText,
headers: parts.headers,
encoding: request.http?.encoding,
}),
options?.http,
)
const text = yield* RequestExecutor.responseStream(response).pipe(
+1 -2
View File
@@ -5,7 +5,6 @@ import { ProviderShared } from "../protocols/shared.js"
import { Auth } from "../route/auth.js"
import { Route, type RouteDefaultsInput } from "../route/client.js"
import { Endpoint } from "../route/endpoint.js"
import { Framing } from "../route/framing.js"
import { ProviderConfigurationError, ProviderID, type LLMRequest, type ModelID } from "../schema/index.js"
import { GoogleVertexShared } from "./google-vertex-shared.js"
@@ -69,7 +68,7 @@ const route = Route.make({
const serviceTier = request.providerOptions?.serviceTier
return typeof serviceTier === "string" ? { "x-vertex-ai-llm-shared-request-type": serviceTier } : {}
},
framing: Framing.sse,
transport: Gemini.transport,
})
export const routes = [route]
+1 -1
View File
@@ -34,7 +34,7 @@ export * as Moonshot from "./moonshot.js"
export * as OpenAI from "./openai.js"
export * as OpenAICompatible from "./openai-compatible.js"
export * as OpenAICompatibleResponses from "./openai-compatible-responses.js"
export * as OpenCodeZen from "./opencode-zen.js"
export * as OpenCode from "./opencode.js"
export * as OpenRouter from "./openrouter.js"
export * as Replicate from "./replicate.js"
export * as Runway from "./runway.js"
@@ -3,7 +3,7 @@ import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
import { SystemOne } from "../experimental/system-one.js"
export const id = ProviderID.make("opencode")
const baseURL = "https://opencode.ai/zen/v1"
const baseURL = "https://opencode.ai/inference/systemone/v1"
export type Options = ProviderAuthOption<"optional"> & {
readonly baseURL?: string
@@ -28,4 +28,4 @@ export const configure = (input: Options = {}) => {
export const provider = configure()
export const experimental = provider.experimental
export * as OpenCodeZen from "./opencode-zen.js"
export * as OpenCode from "./opencode.js"
+5 -3
View File
@@ -7,6 +7,7 @@ import type { HttpMiddleware, Transport, TransportPrepareInput } from "./index.j
import * as ProviderShared from "../../protocols/shared.js"
import {
AIError,
DEFAULT_CHUNK_TIMEOUT_MS,
DEFAULT_HTTP_TIMEOUT_MS,
mergeJsonRecords,
TransportError,
@@ -88,6 +89,7 @@ export const httpJson = <Body, Frame>(input: HttpJsonInput<Body, Frame>): HttpJs
url: parts.url,
body: parts.bodyText,
headers: parts.headers,
encoding: prepareInput.request.http?.encoding,
})
return {
request,
@@ -123,7 +125,7 @@ export const httpJson = <Body, Frame>(input: HttpJsonInput<Body, Frame>): HttpJs
frames: prepared.framing.frame(
RequestExecutor.responseStream(response).pipe(
Stream.timeoutOrElse({
duration: timeoutDuration(request.http?.chunkTimeout),
duration: timeoutDuration(request.http?.chunkTimeout, DEFAULT_CHUNK_TIMEOUT_MS),
orElse: () => Stream.fail(timeout("read", "Timed out waiting for response data", http)),
}),
Stream.interruptWhen(
@@ -139,8 +141,8 @@ export const httpJson = <Body, Frame>(input: HttpJsonInput<Body, Frame>): HttpJs
}),
})
const timeoutDuration = (value: HttpTimeout | undefined) =>
value === false ? Duration.infinity : Duration.millis(value ?? DEFAULT_HTTP_TIMEOUT_MS)
const timeoutDuration = (value: HttpTimeout | undefined, fallback = DEFAULT_HTTP_TIMEOUT_MS) =>
value === false ? Duration.infinity : Duration.millis(value ?? fallback)
export const sseJson = {
id: "http-json/sse",
+32 -5
View File
@@ -52,9 +52,19 @@ export const mergeProviderOptions = (
export const HttpTimeout = Schema.Union([Schema.Number.check(Schema.isGreaterThan(0)), Schema.Literal(false)])
export type HttpTimeout = Schema.Schema.Type<typeof HttpTimeout>
/** Applied to `headerTimeout` and `chunkTimeout` when a request leaves them unset. */
/** Applied to `headerTimeout` when a request leaves it unset. */
export const DEFAULT_HTTP_TIMEOUT_MS = 300_000
/**
* Applied to `chunkTimeout` when a request leaves it unset. Some providers, such as DeepSeek, have specifically asked
* clients to allow at least 15 minutes, because their models can stream nothing for minutes while they reason.
*/
export const DEFAULT_CHUNK_TIMEOUT_MS = 900_000
/** `Content-Encoding` for JSON request bodies; `none` sends plain JSON. */
export const RequestEncoding = Schema.Literals(["zstd", "gzip", "none"])
export type RequestEncoding = Schema.Schema.Type<typeof RequestEncoding>
export class HttpOptions extends Schema.Class<HttpOptions>("AI.HttpOptions")({
body: Schema.optional(JsonSchema),
headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),
@@ -65,6 +75,8 @@ export class HttpOptions extends Schema.Class<HttpOptions>("AI.HttpOptions")({
headerTimeout: Schema.optional(HttpTimeout),
/** Time allowed between streamed response chunks once headers have arrived. */
chunkTimeout: Schema.optional(HttpTimeout),
/** Compression for JSON request bodies. Only set it for endpoints known to decode it. */
encoding: Schema.optional(RequestEncoding),
}) {}
export namespace HttpOptions {
@@ -86,9 +98,18 @@ export const mergeHttpOptions = (...items: ReadonlyArray<HttpOptions | undefined
const timeout = items.findLast((item) => item?.timeout !== undefined)?.timeout
const headerTimeout = items.findLast((item) => item?.headerTimeout !== undefined)?.headerTimeout
const chunkTimeout = items.findLast((item) => item?.chunkTimeout !== undefined)?.chunkTimeout
if (!body && !headers && !query && timeout === undefined && headerTimeout === undefined && chunkTimeout === undefined)
const encoding = items.findLast((item) => item?.encoding !== undefined)?.encoding
if (
!body &&
!headers &&
!query &&
timeout === undefined &&
headerTimeout === undefined &&
chunkTimeout === undefined &&
encoding === undefined
)
return undefined
return new HttpOptions({ body, headers, query, timeout, headerTimeout, chunkTimeout })
return new HttpOptions({ body, headers, query, timeout, headerTimeout, chunkTimeout, encoding })
}
export class GenerationOptions extends Schema.Class<GenerationOptions>("LLM.GenerationOptions")({
@@ -186,6 +207,9 @@ export type LanguageModelMaxTokensFieldCompatibility = Schema.Schema.Type<
typeof LanguageModelMaxTokensFieldCompatibility
>
export const LanguageModelCacheFormatCompatibility = Schema.Literals(["anthropic", "alibaba"])
export type LanguageModelCacheFormatCompatibility = Schema.Schema.Type<typeof LanguageModelCacheFormatCompatibility>
export class LanguageModelCompatibility extends Schema.Class<LanguageModelCompatibility>(
"LLM.LanguageModelCompatibility",
)({
@@ -199,9 +223,12 @@ export class LanguageModelCompatibility extends Schema.Class<LanguageModelCompat
supportsStore: Schema.optional(Schema.Boolean),
supportsUsageInStreaming: Schema.optional(Schema.Boolean),
supportsStrictMode: Schema.optional(Schema.Boolean),
// Accepts `prompt_cache_key` in the Chat Completions body. Chat omits the
// key unless this is set; session-affinity headers still flow regardless.
// Accepts `prompt_cache_key` in the request body. Chat omits the key unless
// this is true; other protocols omit it only when this is false.
// Session-affinity headers still flow regardless.
supportsPromptCacheKey: Schema.optional(Schema.Boolean),
/** Prompt-cache marker syntax the endpoint accepts. Overrides the route default; both send `cache_control`, and `alibaba` skips tool definitions. */
cacheFormat: Schema.optional(LanguageModelCacheFormatCompatibility),
zaiToolStream: Schema.optional(Schema.Boolean),
requireSignature: Schema.optional(Schema.Boolean),
/** Supports Anthropic's thinking-prefix mismatch controls. Overrides model-ID detection. */
+5 -5
View File
@@ -2,7 +2,7 @@ import { describe, expect } from "bun:test"
import { Effect, Layer } from "effect"
import { HttpClientRequest } from "effect/http"
import { Evaluation, EvaluationClient } from "../src/experimental.js"
import { OpenCodeZen, OpenRouter, TypeSafeAI, VercelAIGateway } from "../src/providers.js"
import { OpenCode, OpenRouter, TypeSafeAI, VercelAIGateway } from "../src/providers.js"
import { it } from "./lib/effect.js"
import { dynamicResponse } from "./lib/http.js"
@@ -116,9 +116,9 @@ describe("experimental Evaluation", () => {
),
)
it.effect("configures the OpenCode Zen System One endpoint", () =>
it.effect("configures the OpenCode System One endpoint", () =>
Evaluation.run({
model: OpenCodeZen.configure({ apiKey: "zen-key", baseURL: "https://zen.test/v1" }).experimental.evaluation(
model: OpenCode.configure({ apiKey: "opencode-key", baseURL: "https://opencode.test/v1" }).experimental.evaluation(
"jev-1.13",
),
state: "hello",
@@ -136,8 +136,8 @@ describe("experimental Evaluation", () => {
EvaluationClient.layer.pipe(
Layer.provide(
dynamicResponse((input) => {
expect(input.request.url).toBe("https://zen.test/v1/systemone")
expect(input.request.headers.authorization).toBe("Bearer zen-key")
expect(input.request.url).toBe("https://opencode.test/v1/systemone")
expect(input.request.headers.authorization).toBe("Bearer opencode-key")
return Effect.succeed(
input.respond(
JSON.stringify({
+2 -2
View File
@@ -1,7 +1,7 @@
import { Effect } from "effect"
import { Evaluation, EvaluationClient, EvaluationModel, type EvaluationRoute } from "../src/experimental.js"
import type { Service } from "../src/experimental/evaluation-client.js"
import { OpenCodeZen, OpenRouter, TypeSafeAI, VercelAIGateway } from "../src/providers.js"
import { OpenCode, OpenRouter, TypeSafeAI, VercelAIGateway } from "../src/providers.js"
type Requirements<T> = T extends Effect.Effect<infer _A, infer _E, infer R> ? R : never
type Success<T> = T extends Effect.Effect<infer A, infer _E, infer _R> ? A : never
@@ -34,7 +34,7 @@ void (true satisfies ClientRequirements)
Effect.gen(function* () {
const response = yield* Evaluation.run({
model: OpenCodeZen.experimental.evaluation("jev-1.13"),
model: OpenCode.experimental.evaluation("jev-1.13"),
state: ["hello"],
questions: { greeting: { type: "boolean", instructions: "Greeting?" } },
})
+2 -2
View File
@@ -34,7 +34,7 @@ import {
Fireworks,
Google,
Meta,
OpenCodeZen,
OpenCode,
OpenAI,
OpenAICompatible,
OpenRouter,
@@ -149,7 +149,7 @@ describe("public exports", () => {
expect(OpenRouter.model).toBeFunction()
expect(OpenRouter.experimental.evaluation).toBeFunction()
expect(TypeSafeAI.experimental.evaluation).toBeFunction()
expect(OpenCodeZen.experimental.evaluation).toBeFunction()
expect(OpenCode.experimental.evaluation).toBeFunction()
expect(VercelAIGateway.experimental.evaluation).toBeFunction()
expect(XAI.model).toBeFunction()
expect(XAI.provider.responses).toBe(XAI.responses)
@@ -3,11 +3,11 @@
"metadata": {
"model": "jev-1.13-free",
"tags": [
"prefix:opencode-zen-evaluation",
"prefix:opencode-evaluation",
"provider:opencode",
"protocol:system-one"
],
"name": "opencode-zen-evaluation/evaluates-choice-score-and-boolean-questions",
"name": "opencode-evaluation/evaluates-choice-score-and-boolean-questions",
"recordedAt": "2026-09-22T03:44:57.511Z"
},
"interactions": [
@@ -15,7 +15,7 @@
"transport": "http",
"request": {
"method": "POST",
"url": "https://opencode.ai/zen/v1/systemone",
"url": "https://opencode.ai/inference/systemone/v1/systemone",
"headers": {
"content-type": "application/json"
},
+2 -2
View File
@@ -69,7 +69,7 @@ describe("HTTP transport timeouts", () => {
}),
)
it.effect("fails when the response body stalls for five minutes", () =>
it.effect("fails when the response body stalls for fifteen minutes", () =>
Effect.gen(function* () {
const server = yield* stalledServer
const fiber = yield* LLMClient.generate(LLM.request({ model, prompt: "Hello" })).pipe(
@@ -79,7 +79,7 @@ describe("HTTP transport timeouts", () => {
)
yield* Deferred.await(server.stalled)
yield* Effect.yieldNow
yield* TestClock.adjust("5 minutes")
yield* TestClock.adjust("15 minutes")
const error = yield* Fiber.join(fiber)
expect(error.reason).toMatchObject({ _tag: "Transport", transport: "http", operation: "read", code: "Timeout" })
@@ -1,6 +1,6 @@
import { describe, expect } from "bun:test"
import { Effect } from "effect"
import { CacheHint, LLM, Message, ToolCallPart } from "../../src/index.js"
import { CacheHint, LanguageModel, LLM, Message, ToolCallPart } from "../../src/index.js"
import { AmazonBedrock } from "../../src/providers.js"
import { compileRequest } from "../../src/route/client.js"
import { it } from "../lib/effect.js"
@@ -116,4 +116,53 @@ describe("Bedrock Converse cache policy", () => {
)
}
}
const arn = "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abc123"
for (const ttlSeconds of [undefined, 3600]) {
it.effect(
`emits checkpoints for an opaque ARN declaring the Anthropic cache format (TTL: ${ttlSeconds ?? "default"})`,
() =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
LLM.request({
model: LanguageModel.update(bedrock.model(arn), { compatibility: { cacheFormat: "anthropic" } }),
system: [
{ type: "text", text: "Agent" },
{ type: "text", text: "Project" },
],
tools: [{ name: "lookup", description: "Lookup", inputSchema: { type: "object" } }],
prompt: "Question",
cache:
ttlSeconds === undefined ? undefined : { tools: true, system: true, messages: { tail: 1 }, ttlSeconds },
}),
)
const marker = { cachePoint: ttlSeconds === undefined ? { type: "default" } : { type: "default", ttl: "1h" } }
expect(prepared.body).toMatchObject({
modelId: arn,
toolConfig: { tools: [{ toolSpec: { name: "lookup" } }, marker] },
system: [{ text: "Agent" }, marker, { text: "Project" }, marker],
messages: [{ role: "user", content: [{ text: "Question" }, marker] }],
})
if (ttlSeconds === undefined) expect(JSON.stringify(prepared.body)).not.toContain('"ttl"')
}),
)
}
for (const id of [arn, "amazon.nova-lite-v1:0"]) {
it.effect(`ignores the Alibaba cache format for ${id}`, () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
LLM.request({
model: LanguageModel.update(bedrock.model(id), { compatibility: { cacheFormat: "alibaba" } }),
system: "System prefix",
prompt: "Question",
}),
)
expect(JSON.stringify(prepared.body)).not.toContain("cachePoint")
}),
)
}
})
@@ -1,7 +1,7 @@
import { describe, expect } from "bun:test"
import { Effect } from "effect"
import { Evaluation, EvaluationModel, type EvaluationOptions } from "../../src/experimental.js"
import { OpenCodeZen, OpenRouter, TypeSafeAI } from "../../src/providers.js"
import { OpenCode, OpenRouter, TypeSafeAI } from "../../src/providers.js"
import { recordedTests } from "../recorded-test.js"
const questions = {
@@ -32,8 +32,8 @@ const typesafe = recordedTests({
metadata: { model: "jev-latest" },
})
const zen = recordedTests({
prefix: "opencode-zen-evaluation",
const opencode = recordedTests({
prefix: "opencode-evaluation",
provider: "opencode",
protocol: "system-one",
requires: ["OPENCODE_API_KEY"],
@@ -55,9 +55,9 @@ describe("experimental Evaluation recorded", () => {
),
)
zen.effect("evaluates choice score and boolean questions", () =>
opencode.effect("evaluates choice score and boolean questions", () =>
assertEvaluation(
OpenCodeZen.configure({ apiKey: process.env.OPENCODE_API_KEY ?? "fixture" }).experimental.evaluation(
OpenCode.configure({ apiKey: process.env.OPENCODE_API_KEY ?? "fixture" }).experimental.evaluation(
"jev-1.13-free",
),
),
+317 -3
View File
@@ -1,11 +1,12 @@
import { describe, expect } from "bun:test"
import { Effect } from "effect"
import { LLM, AIError, LLMRequest, Message, ToolCallPart, ToolDefinition, Usage, Media } from "../../src/index.js"
import { Deferred, Effect, Fiber } from "effect"
import * as TestClock from "effect/testing/TestClock"
import { LLM, AIError, LLMEvent, LLMRequest, Message, ToolCallPart, ToolDefinition, Usage, Media } from "../../src/index.js"
import { Auth, LLMClient } from "../../src/route.js"
import { compileRequest } from "../../src/route/client.js"
import * as Gemini from "../../src/protocols/gemini.js"
import { it } from "../lib/effect.js"
import { fixedResponse } from "../lib/http.js"
import { dynamicResponse, fixedResponse } from "../lib/http.js"
import { sseEvents, sseRaw } from "../lib/sse.js"
const model = Gemini.route
@@ -1832,3 +1833,316 @@ describe("Gemini route", () => {
}),
)
})
describe("Gemini response continuation", () => {
const continuedRequest = LLM.request({
model: Gemini.route
.with({
endpoint: { baseURL: "https://generativelanguage.test/v1beta/" },
auth: Auth.header("x-goog-api-key", "test"),
})
.model({ id: "gemini-test" }),
prompt: "Count.",
tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
})
// Serves one scripted SSE body per request, or a body whose connection drops after it, and records every sent body.
const scripted = (responses: ReadonlyArray<string | { readonly dropped: string } | ReadableStream<Uint8Array>>) => {
const bodies: Array<Record<string, unknown>> = []
const layer = dynamicResponse((input) =>
Effect.sync(() => {
bodies.push(JSON.parse(input.text))
const response = responses[bodies.length - 1]
if (typeof response === "string" || response instanceof ReadableStream)
return input.respond(response, { headers: { "content-type": "text/event-stream" } })
let sent = false
return input.respond(
new ReadableStream({
pull(controller) {
if (sent) return controller.error(new Error("connection reset"))
sent = true
controller.enqueue(new TextEncoder().encode(response.dropped))
},
}),
{ headers: { "content-type": "text/event-stream" } },
)
}),
)
return { bodies, layer }
}
const chunks = (...values: ReadonlyArray<unknown>) =>
values.map((value) => sseRaw(`data: ${JSON.stringify(value)}`)).join("")
const text = (value: string, extra: Record<string, unknown> = {}) => ({
candidates: [{ content: { role: "model", parts: [{ text: value }] }, ...extra }],
})
const continuation = (token?: string) => ({
candidates: [
{ content: { role: "model", parts: [{ text: "" }] }, finishReason: "CONTINUATION", continuationToken: token },
],
})
it.effect("stitches text split across three requests into one block", () =>
Effect.gen(function* () {
const server = scripted([
sseEvents(
{
candidates: [
{ content: { role: "model", parts: [{ text: "plan", thought: true, thoughtSignature: "sig_1" }] } },
],
},
text("THIRTEEN THOUSAND TWO"),
continuation("token-1"),
),
sseEvents(
text(" HUNDRED SEVEN"),
// The finishing chunk's token supersedes an earlier checkpoint's.
text("TY-TWO", { continuationToken: "checkpoint" }),
continuation("token-2"),
),
sseEvents(text(" DONE", { finishReason: "STOP" })),
])
const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
expect(response.text).toBe("THIRTEEN THOUSAND TWO HUNDRED SEVENTY-TWO DONE")
expect(response.reasoning).toBe("plan")
expect(response.events.filter((event) => event.type !== "text-delta").map((event) => event.type)).toEqual([
"step-start",
"reasoning-start",
"reasoning-delta",
"reasoning-end",
"text-start",
"text-end",
"step-finish",
"finish",
])
expect(response.events.find((event) => event.type === "reasoning-end")).toMatchObject({
providerMetadata: { google: { thoughtSignature: "sig_1" } },
})
expect(response.finishReason).toEqual({ normalized: "stop", raw: "STOP" })
expect(server.bodies).toHaveLength(3)
expect(server.bodies[0]).not.toHaveProperty("continuationToken")
expect(server.bodies[1]).toEqual({ ...server.bodies[0], continuationToken: "token-1" })
expect(server.bodies[2]).toEqual({ ...server.bodies[0], continuationToken: "token-2" })
}),
)
it.effect("finishes with a signed tool call from a later request", () =>
Effect.gen(function* () {
const server = scripted([
sseEvents(text("Looking"), continuation("token-1")),
sseEvents({
candidates: [
{
content: {
role: "model",
parts: [
{ text: " it up." },
{ functionCall: { id: "call_1", name: "lookup", args: {} }, thoughtSignature: "call_sig" },
],
},
finishReason: "STOP",
},
],
}),
])
const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
expect(response.text).toBe("Looking it up.")
expect(response.events.filter((event) => event.type === "text-start")).toHaveLength(1)
expect(response.events.find((event) => event.type === "tool-call")).toMatchObject({
id: "call_1",
providerMetadata: { google: { thoughtSignature: "call_sig" } },
})
expect(response.finishReason).toEqual({ normalized: "tool-calls", raw: "STOP" })
}),
)
it.effect("forgets a block once the resumed request finishes", () =>
Effect.gen(function* () {
const server = scripted([
sseEvents(text("THIRTEEN", { continuationToken: "checkpoint-1" }), { promptFeedback: { blockReason: "OTHER" } }),
sseEvents(text(" THOUSAND", { finishReason: "STOP" })),
])
const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
expect(response.text).toBe("THIRTEEN THOUSAND")
expect(response.finishReason).toEqual({ normalized: "stop", raw: "STOP" })
expect(response.events.filter(LLMEvent.is.finish).map((event) => event.providerMetadata)).toEqual([undefined])
}),
)
it.effect("resumes a dropped stream from its latest checkpoint", () =>
Effect.gen(function* () {
const server = scripted([
{ dropped: chunks(text("THIRTEEN"), text(" THOUSAND", { continuationToken: "checkpoint-1" })) },
sseEvents(text(" TWO", { finishReason: "STOP" })),
])
const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
expect(response.text).toBe("THIRTEEN THOUSAND TWO")
expect(response.finishReason).toEqual({ normalized: "stop", raw: "STOP" })
expect(server.bodies[1]).toEqual({ ...server.bodies[0], continuationToken: "checkpoint-1" })
}),
)
it.effect("counts the usage of a dropped request once resumed", () =>
Effect.gen(function* () {
const server = scripted([
{
dropped: chunks(
{ ...text("THIRTEEN"), usageMetadata: { promptTokenCount: 120, candidatesTokenCount: 5 } },
{
...text(" THOUSAND", { continuationToken: "checkpoint-1" }),
usageMetadata: { promptTokenCount: 142, candidatesTokenCount: 32768, totalTokenCount: 32910 },
},
),
},
sseEvents({
...text(" TWO", { finishReason: "STOP" }),
usageMetadata: { promptTokenCount: 32910, candidatesTokenCount: 100, totalTokenCount: 33010 },
}),
])
const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
expect(response.usage).toEqual(
new Usage({
inputTokens: 142,
outputTokens: 32868,
nonCachedInputTokens: 142,
totalTokens: 33010,
providerMetadata: {
google: {
promptTokenCount: 33052,
candidatesTokenCount: 32868,
totalTokenCount: 65920,
requests: 2,
},
},
}),
)
}),
)
it.effect("continues a stream that ends at a checkpoint without finishing", () =>
Effect.gen(function* () {
const server = scripted([
sseEvents(text("THIRTEEN", { continuationToken: "checkpoint-1" })),
sseEvents(text(" THOUSAND", { finishReason: "STOP" })),
])
const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
expect(response.text).toBe("THIRTEEN THOUSAND")
expect(server.bodies[1]).toEqual({ ...server.bodies[0], continuationToken: "checkpoint-1" })
}),
)
it.effect("fails a stream dropped before any checkpoint", () =>
Effect.gen(function* () {
const server = scripted([{ dropped: chunks(text("Partial")) }])
const error = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer), Effect.flip)
expect(error.reason._tag).toBe("Transport")
expect(server.bodies).toHaveLength(1)
}),
)
it.effect("does not resume a response cut off by its own timeout", () =>
Effect.gen(function* () {
const stalled = yield* Deferred.make<void>()
let sent = false
const server = scripted([
new ReadableStream({
pull(controller) {
if (sent) return new Promise<void>(() => Deferred.doneUnsafe(stalled, Effect.void))
sent = true
controller.enqueue(new TextEncoder().encode(chunks(text("THIRTEEN", { continuationToken: "checkpoint-1" }))))
},
}),
])
const fiber = yield* LLMClient.generate(
LLMRequest.update(continuedRequest, { http: { timeout: 1_000 } }),
).pipe(Effect.provide(server.layer), Effect.flip, Effect.forkChild({ startImmediately: true }))
yield* Deferred.await(stalled)
yield* TestClock.adjust("1 second")
const error = yield* Fiber.join(fiber)
expect(error.reason).toMatchObject({ _tag: "Transport", code: "Timeout" })
expect(server.bodies).toHaveLength(1)
}),
)
it.effect("fails a continuation without a token", () =>
Effect.gen(function* () {
const server = scripted([sseEvents(text("Partial"), continuation())])
const error = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer), Effect.flip)
expect(error).toMatchObject({
reason: { _tag: "InvalidProviderOutput", http: { status: 200 } },
message: "Gemini continued the response without a token",
})
expect(server.bodies).toHaveLength(1)
}),
)
it.effect("does not continue a length finish", () =>
Effect.gen(function* () {
const server = scripted([
sseEvents(text("Partial", { finishReason: "MAX_TOKENS", continuationToken: "token-1" })),
])
const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
expect(response.finishReason).toEqual({ normalized: "length", raw: "MAX_TOKENS" })
expect(server.bodies).toHaveLength(1)
}),
)
it.effect("reports the first request's input with all output", () =>
Effect.gen(function* () {
const usage = [
{ promptTokenCount: 142, candidatesTokenCount: 32768, totalTokenCount: 32910 },
{ promptTokenCount: 32910, candidatesTokenCount: 32768, totalTokenCount: 65678 },
{
promptTokenCount: 65678,
cachedContentTokenCount: 32911,
candidatesTokenCount: 32768,
totalTokenCount: 98446,
},
{
promptTokenCount: 98446,
cachedContentTokenCount: 65679,
candidatesTokenCount: 7257,
totalTokenCount: 105703,
},
]
const server = scripted([
sseEvents(
{ ...text("a"), usageMetadata: { promptTokenCount: 120, candidatesTokenCount: 10, totalTokenCount: 130 } },
{ ...continuation("token-1"), usageMetadata: usage[0] },
),
sseEvents({ ...continuation("token-2"), usageMetadata: usage[1] }),
sseEvents({ ...continuation("token-3"), usageMetadata: usage[2] }),
sseEvents({ ...text("b", { finishReason: "STOP" }), usageMetadata: usage[3] }),
])
const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
expect(response.usage).toEqual(
new Usage({
inputTokens: 142,
outputTokens: 105561,
nonCachedInputTokens: 142,
totalTokens: 105703,
providerMetadata: {
google: {
promptTokenCount: 197176,
cachedContentTokenCount: 98590,
candidatesTokenCount: 105561,
totalTokenCount: 302737,
requests: 4,
},
},
}),
)
}),
)
})
@@ -539,6 +539,50 @@ describe("Google Vertex providers", () => {
}),
)
it.effect("continues split Gemini responses with the Vertex request body", () =>
Effect.gen(function* () {
const sent: Array<{ readonly authorization: string | null; readonly body: Record<string, unknown> }> = []
const responses = [
sseEvents({
candidates: [
{
content: { role: "model", parts: [{ text: "Hel" }] },
finishReason: "CONTINUATION",
continuationToken: "token-1",
},
],
}),
sseEvents({ candidates: [{ content: { role: "model", parts: [{ text: "lo." }] }, finishReason: "STOP" }] }),
]
const response = yield* LLMClient.generate(
LLM.request({
model: GoogleVertex.configure({
accessToken: "vertex-token",
project: "vertex-project",
providerOptions: { labels: { component: "opencode" }, serviceTier: "flex" },
}).model("gemini-test"),
prompt: "Say hello.",
}),
).pipe(
Effect.provide(
dynamicResponse((input) =>
Effect.sync(() => {
sent.push({ authorization: input.request.headers.authorization ?? null, body: JSON.parse(input.text) })
return input.respond(responses[sent.length - 1], { headers: { "content-type": "text/event-stream" } })
}),
),
),
)
expect(response.text).toBe("Hello.")
expect(response.events.filter((event) => event.type === "text-start")).toHaveLength(1)
expect(sent.map((request) => request.authorization)).toEqual(["Bearer vertex-token", "Bearer vertex-token"])
expect(sent[0].body).toMatchObject({ labels: { component: "opencode" } })
expect(sent[0].body).not.toHaveProperty("serviceTier")
expect(sent[1].body).toEqual({ ...sent[0].body, continuationToken: "token-1" })
}),
)
test("rejects tuned Gemini models in express mode", () => {
expect(() => GoogleVertex.configure({ apiKey: "fixture" }).model("endpoints/1234567890")).toThrow(
expect.objectContaining({
+11 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, test } from "bun:test"
import { ConfigProvider, Effect } from "effect"
import { HttpClientRequest } from "effect/http"
import { LLM, LLMEvent, Message, SystemPart, ToolDefinition, Media } from "../../src/index.js"
import { LanguageModel, LLM, LLMEvent, Message, SystemPart, ToolDefinition, Media } from "../../src/index.js"
import { Mistral } from "../../src/providers/index.js"
import { MistralChat } from "../../src/protocols/index.js"
import { LLMClient } from "../../src/route.js"
@@ -188,6 +188,16 @@ describe("Mistral Chat", () => {
)
expect(uncached.body.prompt_cache_key).toBeUndefined()
const unsupported = yield* compileRequest(
LLM.request({
model: LanguageModel.update(model, { compatibility: { supportsPromptCacheKey: false } }),
prompt: "Hello",
promptCacheKey: "common-key",
providerOptions: { promptCacheKey: "native-key" },
}),
)
expect(unsupported.body.prompt_cache_key).toBeUndefined()
const longKey = "cache-key-".repeat(10)
const unbounded = yield* compileRequest(
LLM.request({
@@ -99,6 +99,43 @@ describe("OpenAI-compatible Chat route", () => {
}),
)
it.effect("places cache breakpoints only when compatibility declares the format", () =>
Effect.gen(function* () {
const prepare = (cacheFormat: "anthropic" | "alibaba" | undefined) =>
compileRequest(
LLM.request({
model: OpenAICompatibleChat.route
.with({ provider: "custom", endpoint: { baseURL: "https://api.custom.test/v1" } })
.model({ id: "claude-sonnet-5", compatibility: cacheFormat === undefined ? undefined : { cacheFormat } }),
system: "You are concise.",
prompt: "Say hello.",
tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: {} })],
}),
)
const declared = yield* prepare("anthropic")
expect(declared.body).toMatchObject({
messages: [
{ role: "system", content: [{ type: "text", text: "You are concise.", cache_control: { type: "ephemeral" } }] },
{ role: "user", content: [{ type: "text", text: "Say hello.", cache_control: { type: "ephemeral" } }] },
],
tools: [{ function: { name: "lookup" }, cache_control: { type: "ephemeral" } }],
})
expect(JSON.stringify(declared.body)).not.toContain('"ttl"')
const alibaba = yield* prepare("alibaba")
expect(alibaba.body).toMatchObject({
messages: [
{ role: "system", content: [{ type: "text", text: "You are concise.", cache_control: { type: "ephemeral" } }] },
{ role: "user", content: [{ type: "text", text: "Say hello.", cache_control: { type: "ephemeral" } }] },
],
})
expect(alibaba.body.tools?.[0]?.cache_control).toBeUndefined()
expect(JSON.stringify((yield* prepare(undefined)).body)).not.toContain("cache_control")
}),
)
it.effect("configures the max tokens request field", () =>
Effect.gen(function* () {
const compatible = OpenAICompatibleChat.route
@@ -644,6 +644,27 @@ describe("Open Responses-compatible route", () => {
}),
)
it.effect("treats a null function call namespace as absent", () =>
Effect.gen(function* () {
const item = { type: "function_call", id: "fc_1", call_id: "call_1", name: "lookup", namespace: null }
const response = yield* LLMClient.generate(request).pipe(
Effect.provide(
fixedResponse(
sseEvents(
{ type: "response.output_item.added", output_index: 0, item: { ...item, arguments: "" } },
{ type: "response.function_call_arguments.done", item_id: "fc_1", output_index: 0, arguments: "{}" },
{ type: "response.output_item.done", output_index: 0, item: { ...item, arguments: "{}" } },
{ type: "response.completed", response: { id: "resp_1", output: [{ ...item, arguments: "{}" }] } },
),
),
),
)
expect(response.toolCalls).toEqual([expect.objectContaining({ id: "call_1", name: "lookup", input: {} })])
expect(response.toolCalls[0]?.namespace).toBeUndefined()
}),
)
it.effect("rejects missing, null, and non-string event IDs even with a registered output index", () =>
Effect.gen(function* () {
yield* Effect.forEach(
@@ -2117,6 +2117,24 @@ describe("OpenAI Responses route", () => {
}),
)
it.effect("omits the prompt cache key when compatibility disables it", () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
LLM.request({
model: LanguageModel.update(model, { compatibility: { supportsPromptCacheKey: false } }),
prompt: "Hello",
promptCacheKey: "request_cache",
}),
)
expect(prepared.body).not.toHaveProperty("prompt_cache_key")
expect(model.compatibility?.supportsPromptCacheKey).toBeUndefined()
expect(
(yield* compileRequest(LLM.request({ model, prompt: "Hello", promptCacheKey: "request_cache" }))).body,
).toHaveProperty("prompt_cache_key", "request_cache")
}),
)
it.effect("parses text and usage stream fixtures", () =>
Effect.gen(function* () {
const body = sseEvents(
+21 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect } from "bun:test"
import { Effect } from "effect"
import { CacheHint, LLM, Message } from "../../src/index.js"
import { CacheHint, LanguageModel, LLM, Message } from "../../src/index.js"
import { LLMClient } from "../../src/route.js"
import { compileRequest } from "../../src/route/client.js"
import * as OpenRouter from "../../src/providers/openrouter.js"
@@ -127,6 +127,26 @@ describe("OpenRouter", () => {
}),
)
it.effect("places breakpoints for any upstream when compatibility declares the cache format", () =>
Effect.gen(function* () {
const model = OpenRouter.configure({ apiKey: "test-key" }).model("vendor/claude-proxy")
const prepared = yield* compileRequest(
LLM.request({
model: LanguageModel.update(model, { compatibility: { cacheFormat: "anthropic" } }),
system: "Base agent",
tools: [{ name: "lookup", description: "Lookup", inputSchema: { type: "object", properties: {} } }],
prompt: "Hello",
}),
)
expect(prepared.body.tools?.[0]?.cache_control).toEqual({ type: "ephemeral" })
expect(prepared.body.messages).toMatchObject([
{ role: "system", content: [{ text: "Base agent", cache_control: { type: "ephemeral" } }] },
{ role: "user", content: [{ text: "Hello", cache_control: { type: "ephemeral" } }] },
])
}),
)
it.effect("sends no default breakpoints to upstreams that cache without them", () =>
Effect.gen(function* () {
const openrouter = OpenRouter.configure({ apiKey: "test-key" })
+57
View File
@@ -0,0 +1,57 @@
import { describe, expect } from "bun:test"
import { gunzipSync, zstdDecompressSync } from "node:zlib"
import { Effect } from "effect"
import { HttpClientRequest } from "effect/http"
import { LLM, type RequestEncoding } from "../src/index.js"
import { LLMClient } from "../src/route.js"
import { configure } from "../src/providers/openai.js"
import { dynamicResponse } from "./lib/http.js"
import { deltaChunk, finishChunk } from "./lib/openai-chunks.js"
import { sseEvents } from "./lib/sse.js"
import { it } from "./lib/effect.js"
const model = configure({ baseURL: "https://api.openai.test/v1/", apiKey: "test" }).chat("gpt-4.1-mini")
const send = (prompt: string, encoding?: RequestEncoding) =>
Effect.gen(function* () {
const seen: { encoding: string | null; body: Uint8Array }[] = []
const server = dynamicResponse((input) =>
Effect.gen(function* () {
const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
seen.push({
encoding: web.headers.get("content-encoding"),
body: new Uint8Array(yield* Effect.promise(() => web.arrayBuffer())),
})
return input.respond(sseEvents(deltaChunk({ role: "assistant", content: "Hi" }), finishChunk("stop")), {
headers: { "content-type": "text/event-stream" },
})
}),
)
yield* LLMClient.generate(LLM.request({ model, prompt, http: encoding ? { encoding } : undefined })).pipe(
Effect.provide(server),
)
return seen[0]
})
describe("HTTP request encoding", () => {
it.effect("compresses the JSON body with the requested encoding", () =>
Effect.gen(function* () {
const zstd = yield* send("Hello", "zstd")
expect(zstd.encoding).toBe("zstd")
expect(JSON.parse(zstdDecompressSync(zstd.body).toString())).toMatchObject({ model: "gpt-4.1-mini" })
const gzip = yield* send("Hello", "gzip")
expect(gzip.encoding).toBe("gzip")
expect(JSON.parse(gunzipSync(gzip.body).toString())).toMatchObject({ model: "gpt-4.1-mini" })
}),
)
it.effect("sends plain JSON when unset or none", () =>
Effect.gen(function* () {
for (const sent of [yield* send("Hello"), yield* send("Hello", "none")]) {
expect(sent.encoding).toBeNull()
expect(JSON.parse(new TextDecoder().decode(sent.body))).toMatchObject({ model: "gpt-4.1-mini" })
}
}),
)
})
+11 -12
View File
@@ -39,7 +39,7 @@ bun run test:e2e:local
bun run test:e2e:local -- --grep "settings"
```
CI builds the app once and runs the same suite against Vite preview, serving production assets from `dist`. Managed built runs never reuse an existing server, so a running dev server cannot silently replace the production build. To run this mode locally:
CI builds the app once and runs the same suite against a static Bun server (`e2e/utils/serve.ts`) that serves the production assets in `dist` with Vite preview's SPA fallback rules. Managed built runs never reuse an existing server, so a running dev server cannot silently replace the production build. To run this mode locally:
```bash
bun run test:e2e:built
@@ -64,24 +64,23 @@ Compiled CLI startup and service lifecycle coverage runs separately in CI via `p
Environment options:
- `PLAYWRIGHT_BUILD=1` (build and preview locally; always enabled when `CI` is set)
- `PLAYWRIGHT_BUILD=1` (build and serve `dist` locally; always enabled when `CI` is set)
- `PLAYWRIGHT_SERVER_HOST` / `PLAYWRIGHT_SERVER_PORT` (dev fixture API address, default: `127.0.0.1:4096`; built runs use the app's origin, matching production)
- `PLAYWRIGHT_PORT` (managed dev or preview server port, default: `3000`)
- `PLAYWRIGHT_PORT` (managed dev or static server port, default: `3000`)
- `PLAYWRIGHT_BASE_URL` (use an externally managed app instead of starting a server; otherwise defaults to `http://127.0.0.1:<PLAYWRIGHT_PORT>`)
## Deployment
The `deploy` GitHub Actions workflow uses SST to deploy the web app from these branches in `anomalyco/opencode`:
The `deploy` GitHub Actions workflow uses SST to deploy the web app to `beta.opencode.ai` on every push to the
`beta` branch in `anomalyco/opencode`. The `dev` and `production` stages do not deploy the web app.
| Branch | Site |
| ------------ | --------------------- |
| `dev` | `app.dev.opencode.ai` |
| `production` | `app.opencode.ai` |
| `beta` | `beta.opencode.ai` |
`beta` is the team's dogfooding branch: `dev` merged in by hand, plus commits pushed directly to it. Do not rebase or
force-push it. Each push also runs the `publish` workflow, which ships the same commit as the OpenCode Beta desktop app
(see `packages/desktop/README.md`).
Changes merged into `v2` reach the beta site when they are promoted to `beta`. The beta SST stage deploys
only the web app, using the same `WebApp` StaticSite definition as production. It sets the build channel
and Sentry environment to `beta` without deploying the API, console, database, or billing infrastructure.
The beta SST stage deploys only the web app, using the `WebApp` StaticSite definition in `infra/webapp.ts`. It sets
the build channel and Sentry environment to `beta` without deploying the API, console, database, or billing
infrastructure.
`VITE_OPENCODE_SERVER_MODE` controls which server the web build provides at startup:
@@ -1,4 +1,7 @@
import { expect, sourceURL, story } from "../../storybook/playwright/story"
import type { ParentProps } from "solid-js"
import type { Command } from "@opencode/gui-extensions/sdk"
import type { Item } from "../src/runtime/extension/host"
const source = (path: string) => sourceURL(new URL(path, import.meta.url))
@@ -9,21 +12,49 @@ const modules = {
language: source("../src/runtime/i18n/language.tsx"),
browser: source("../../gui-extensions/src/browser/index.ts"),
browserRenderer: source("../../gui-extensions/src/browser/renderer.tsx"),
browserPanel: source("../../gui-extensions/src/browser/panel.tsx"),
file: source("../../gui-extensions/src/file/index.ts"),
fileRenderer: source("../../gui-extensions/src/file/renderer.tsx"),
commands: source("../src/shell/commands/command.tsx"),
sdk: source("../../gui-extensions/src/sdk/index.ts"),
render: source("../src/runtime/extension/render.tsx"),
settings: source("../src/settings/model.tsx"),
platform: source("../src/runtime/platform/platform.tsx"),
solid: source("./extension-host.fixture.tsx"),
}
story.beforeEach(async ({ mount, page }) => {
// Any story loads the app styles; the fixture mounts the real side region and extensions beside it.
await mount("ui-line-comment--editor")
await page.evaluate(async (modules) => {
const [{ mountBrowserRegion }, host, panels, language, browser, file] = await Promise.all([
const [
{ mountBrowserRegion },
host,
panels,
language,
browser,
file,
commands,
sdk,
renderer,
settings,
platform,
solid,
] = await Promise.all([
import(modules.fixture),
import(modules.host),
import(modules.panels),
import(modules.language),
import(modules.browser),
import(modules.file),
import(modules.commands),
import(modules.sdk),
import(modules.render),
import(modules.settings),
import(modules.platform),
import(modules.solid),
// Load the pane before mounting: Vite must not reload the page to optimize its dependencies mid-fixture.
import(modules.browserPanel),
])
mountBrowserRegion({
@@ -35,10 +66,87 @@ story.beforeEach(async ({ mount, page }) => {
{ ...browser.default, renderer: () => import(modules.browserRenderer) },
{ ...file.default, renderer: () => import(modules.fileRenderer) },
],
Shell: (props: ParentProps) =>
solid.createComponent(platform.PlatformProvider, {
value: { platform: "web", openExternal() {}, restart: async () => undefined, notify: async () => undefined },
get children() {
return solid.createComponent(settings.SettingsProvider, {
get children() {
return solid.createComponent(commands.CommandProvider, {
get children() {
return props.children
},
})
},
})
},
}),
Commands: (props: { close: () => void }) => {
const command = commands.useCommand()
const extensions = host.useExtensionHost()
command.register("fixture-session", () => [
{
id: "tab.close",
title: "Close session tab",
keybind: "mod+w",
onSelect: props.close,
},
])
// Storybook aliases the app's command hook to a no-op. Bridge the real extension contributions
// to the real dispatcher imported by source URL, so the shortcut runs rather than its alias.
command.register("fixture-extensions", () =>
extensions.items(sdk.Command).map((item: Item<Command>) => {
const scope = item.value.scope
return {
id: `${item.extension}.${item.value.id}`,
title: item.value.title,
keybind: item.value.bind,
disabled: item.value.enabled === false,
hidden: item.value.hidden,
editable: item.value.editable,
when: scope
? (event: KeyboardEvent) => event.target instanceof Element && !!event.target.closest(scope)
: undefined,
onSelect: () => item.value.run(),
}
}),
)
return null
},
Contribution: renderer.Contribution,
})
}, modules)
})
story("closes a blank browser tab from its address field without closing the session", async ({ page }) => {
const root = page.getByTestId("browser-region-fixture")
const outside = root.getByRole("button", { name: "Beta", exact: true })
await expect(root.getByText("Registrations: 1", { exact: true })).toBeVisible()
await outside.click()
await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible()
await root.getByRole("button", { name: "Blank page", exact: true }).click()
await expect(root.getByRole("tab", { name: "New tab", exact: true })).toHaveAttribute("aria-selected", "true")
// Prove the scope while browser.close is still registered.
await outside.focus()
await outside.press("ControlOrMeta+w")
await expect(root.getByTestId("session-state")).toHaveText("closed")
await expect(root.getByTestId("browser-closes")).toHaveText("[]")
await expect(root.getByRole("tab", { name: "New tab", exact: true })).toBeVisible()
await outside.click()
await expect(root.getByTestId("session-state")).toHaveText("open")
const address = root.getByRole("combobox", { name: "Browser address", exact: true })
await address.fill("example.com")
await expect(address).toBeFocused()
await address.press("ControlOrMeta+w")
await expect(root.getByRole("tab", { name: "New tab", exact: true })).toHaveCount(0)
await expect(root.getByTestId("browser-closes")).toHaveText('["tab_33333333-3333-3333-3333-333333333333"]')
await expect(root.getByTestId("session-state")).toHaveText("open")
})
story("keeps a restored browser tab selected and undrawn until the desktop's first inventory", async ({ page }) => {
const root = page.getByTestId("browser-region-fixture")
const tabs = root.getByRole("tab")
@@ -22,6 +22,8 @@ for (const direction of ["ltr", "rtl"]) {
await expect(component.locator('[data-action="composer-alternate-delivery"]')).toHaveCount(
alternate === "none" ? 0 : 1,
)
// A late Inter swap resizes the delivery keybind and shifts the toolbar; measure after fonts settle.
await page.evaluate(() => document.fonts.ready.then(() => undefined))
for (const width of [1024, 360]) {
await page.setViewportSize({ width, height: 720 })
@@ -110,6 +112,7 @@ for (const direction of ["ltr", "rtl"]) {
await add.click()
await expect(page.getByRole("menuitem", { name: "Images and files" })).toBeVisible()
await page.keyboard.press("Escape")
await expect(add).toBeFocused()
expect(await add.boundingBox()).toEqual(fixedAdd)
}
@@ -368,3 +371,59 @@ story("keeps default thinking accessible by keyboard without composer hover", as
await expect(control).not.toBeFocused()
await expect(control).toHaveCSS("opacity", "0")
})
story.describe("mobile variant drawer", () => {
story.use({ viewport: { width: 360, height: 720 } })
// Guards patches/@corvu%2Fdrawer@0.2.4.patch. The drawer starts its opening transition two frames after it opens.
// Dismissing it before then used to slide it open anyway, and dismissing it in that frame left it closing off screen
// for good, holding focus and disabling pointer input on the page. Playwright input cannot target those frames, so
// the page dismisses it.
for (const moment of ["before", "as"] as const) {
story(`closes and restores focus when dismissed ${moment} it starts opening`, async ({ mount, page }) => {
const component = await mount("opencode-composer-flow--model-and-variant")
const variant = component.getByRole("button", { name: "Choose model variant" })
const drawer = page.getByRole("dialog", { name: "Choose model variant", exact: true })
const high = drawer.getByRole("button", { name: "high", exact: true })
// Load the lazy drawer first so the dismissal below races only the drawer's own transition.
await variant.click()
await expect(high).toBeInViewport()
const content = await drawer.elementHandle()
if (!content) throw new Error("Missing variant drawer")
await page.keyboard.press("Escape")
await expect(drawer).toBeHidden()
await expect(variant).toBeFocused()
await variant.evaluate(
(trigger: HTMLElement, race) =>
new Promise<void>((resolve) => {
const dismiss = () => {
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }))
resolve()
}
// Mutation records arrive before the browser renders the opening transition's first frame.
const observer = new MutationObserver(() => {
if (!race.content.hasAttribute("data-opening")) return
observer.disconnect()
dismiss()
})
if (race.moment === "as") observer.observe(race.content, { attributeFilter: ["data-opening"] })
trigger.click()
if (race.moment === "before") dismiss()
}),
{ content, moment },
)
await expect(drawer).toBeHidden()
await expect(variant).toBeFocused()
await expect(page.locator("body")).not.toHaveCSS("pointer-events", "none")
await variant.click()
await expect(high).toBeInViewport()
})
}
})
@@ -1,19 +1,187 @@
import { expect, story } from "../../storybook/playwright/story"
story("shows question navigation shortcuts", async ({ mount, page }) => {
const component = await mount("app-current-session-surface--question-request")
const shortcut = await page.evaluate(() => (/Mac|iPhone|iPad|iPod/.test(navigator.platform) ? "⌘⏎" : "Ctrl+⏎"))
const next = component.getByRole("button", { name: "Next", exact: true })
await expect(next.locator('[data-slot="question-submit-shortcut"]')).toHaveText(shortcut)
story("resizes the dock to fit different answer counts", async ({ mount }) => {
const component = await mount("app-current-session-surface--question-answer-counts")
const question = component.locator('[data-component="dock-prompt"][data-kind="question"]')
const next = question.getByRole("button", { name: "Next", exact: true })
await expect(question.getByRole("radio", { name: /Focused/ })).toBeFocused()
await expect(next).toBeEnabled()
const height = () => question.evaluate((element) => element.getBoundingClientRect().height)
const initial = await height()
await next.click()
await expect(component.getByRole("button", { name: "Submit", exact: true })).toContainText(shortcut)
await expect.poll(height).toBeGreaterThan(initial)
await expect(question.getByRole("checkbox", { name: "Diagnostics", exact: true })).toBeVisible()
const expanded = await height()
const back = question.getByRole("button", { name: "Back", exact: true })
await expect(back).toBeEnabled()
await back.click()
await expect.poll(height).toBeLessThan(expanded)
await expect(question.getByRole("radio", { name: /Focused/ })).toBeVisible()
})
story("selects single answers and toggles multiple answers with number keys", async ({ mount }) => {
const component = await mount("app-current-session-surface--question-request")
const question = component.locator('[data-component="dock-prompt"][data-kind="question"]')
const focused = question.getByRole("radio", { name: /Focused/ })
const wide = question.getByRole("radio", { name: /Wide/ })
const customRadio = question.getByRole("radio", { name: "Type your own answer…", exact: true })
const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true })
const next = question.getByRole("button", { name: "Next", exact: true })
await expect(focused).toBeFocused()
await focused.press("2")
await expect(wide).toBeChecked()
await expect(focused).not.toBeChecked()
await expect(wide).toBeFocused()
await next.press("1")
await expect(focused).toBeChecked()
await expect(wide).not.toBeChecked()
await focused.press("3")
await expect(customRadio).toBeChecked()
await expect(input).toBeFocused()
await expect(focused).not.toBeChecked()
await expect(wide).not.toBeChecked()
await input.press("Enter")
await expect(customRadio).toBeFocused()
await customRadio.press("2")
await expect(wide).toBeChecked()
await expect(customRadio).not.toBeChecked()
await next.click()
const files = question.getByRole("checkbox", { name: "Changed files", exact: true })
const terminal = question.getByRole("checkbox", { name: "Terminal", exact: true })
const customCheckbox = question.getByRole("checkbox", { name: "Type your own answer…", exact: true })
await expect(files).toBeFocused()
await files.press("1")
await expect(files).toBeChecked()
await files.press("2")
await expect(terminal).toBeChecked()
await expect(files).toBeChecked()
await terminal.press("2")
await expect(terminal).not.toBeChecked()
await expect(files).toBeChecked()
await terminal.press("4")
await expect(customCheckbox).toBeChecked()
await expect(input).toBeFocused()
await expect(files).toBeChecked()
await expect(terminal).not.toBeChecked()
await input.press("Enter")
await expect(customCheckbox).toBeFocused()
await customCheckbox.press("4")
await expect(customCheckbox).not.toBeChecked()
await expect(files).toBeChecked()
await expect(terminal).not.toBeChecked()
})
story("ignores modified, out-of-range, and repeated number shortcuts", async ({ mount, page }) => {
const component = await mount("app-current-session-surface--question-request")
const question = component.locator('[data-component="dock-prompt"][data-kind="question"]')
const focused = question.getByRole("radio", { name: /Focused/ })
const wide = question.getByRole("radio", { name: /Wide/ })
await expect(focused).toBeFocused()
await focused.press("1")
await focused.press("9")
await focused.press("Alt+2")
await expect(focused).toBeChecked()
await expect(wide).not.toBeChecked()
await question.getByRole("button", { name: "Next", exact: true }).click()
const terminal = question.getByRole("checkbox", { name: "Terminal", exact: true })
await expect(question.getByRole("checkbox", { name: "Changed files", exact: true })).toBeFocused()
await page.keyboard.down("2")
await expect(terminal).toBeChecked()
await page.keyboard.down("2")
await expect(terminal).toBeChecked()
await page.keyboard.up("2")
})
story("types digits into the custom answer without selecting numbered options", async ({ mount }) => {
const component = await mount("app-current-session-surface--question-request")
const question = component.locator('[data-component="dock-prompt"][data-kind="question"]')
const focused = question.getByRole("radio", { name: /Focused/ })
const custom = question.getByRole("radio", { name: "Type your own answer…", exact: true })
const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true })
await expect(focused).toBeFocused()
await focused.press("3")
await expect(input).toBeFocused()
await input.press("1")
await input.press("2")
await input.press("3")
await expect(input).toHaveValue("123")
await expect(custom).toBeChecked()
await expect(focused).not.toBeChecked()
await expect(question.getByRole("radio", { name: /Wide/ })).not.toBeChecked()
})
story("shows question navigation shortcuts in buttons and tooltips", async ({ mount, page }) => {
const component = await mount("app-current-session-surface--question-request")
const mac = await page.evaluate(() => /Mac|iPhone|iPad|iPod/.test(navigator.platform))
const shortcut = mac ? "⌘⏎" : "Ctrl+⏎"
const next = component.getByRole("button", { name: "Next", exact: true })
await expect(next.locator('[data-slot="question-submit-shortcut"]')).toBeVisible()
await expect(next.locator('[data-slot="question-submit-shortcut"]')).toHaveText(shortcut)
await expect(next).toHaveAttribute("aria-keyshortcuts", "Meta+Enter Control+Enter")
await next.hover()
await expect(page.getByRole("tooltip")).toContainText("Next")
await expect(page.getByRole("tooltip")).toContainText(shortcut)
await next.press(mac ? "Meta+Enter" : "Control+Enter")
const submit = component.getByRole("button", { name: "Submit", exact: true })
await expect(submit.locator('[data-slot="question-submit-shortcut"]')).toBeVisible()
await expect(submit.locator('[data-slot="question-submit-shortcut"]')).toHaveText(shortcut)
await expect(submit).toHaveAttribute("aria-keyshortcuts", "Meta+Enter Control+Enter")
await submit.hover()
await expect(page.getByRole("tooltip")).toContainText("Submit")
await expect(page.getByRole("tooltip")).toContainText(shortcut)
const back = component.getByRole("button", { name: "Back", exact: true })
const backShortcut = await page.evaluate(() => (/Mac|iPhone|iPad|iPod/.test(navigator.platform) ? "⌘[" : "Alt+←"))
await expect(back).toHaveText("Back")
await expect(back).toHaveAttribute("aria-keyshortcuts", mac ? "Meta+[" : "Alt+ArrowLeft")
await back.hover()
await expect(page.getByRole("tooltip")).toContainText(backShortcut)
await page.keyboard.press(
await page.evaluate(() => (/Mac|iPhone|iPad|iPod/.test(navigator.platform) ? "Meta+[" : "Alt+ArrowLeft")),
)
await expect(page.getByRole("tooltip")).toContainText(mac ? "⌘[" : "Alt+←")
await back.press(mac ? "Meta+[" : "Alt+ArrowLeft")
await expect(next).toBeVisible()
})
story("keeps the custom answer input and dock geometry stable while editing", async ({ mount }) => {
const component = await mount("app-current-session-surface--question-request")
const question = component.locator('[data-component="dock-prompt"][data-kind="question"]')
const row = question.locator('[data-slot="question-option"][data-custom="true"]')
const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true })
const toggle = question.getByRole("radio", { name: "Type your own answer…", exact: true })
await expect(question.getByRole("radio", { name: /Focused/ })).toBeFocused()
await expect(input).toBeEditable()
await expect(input).toHaveValue("")
const node = await input.evaluateHandle((element) => element)
const height = () => question.evaluate((element) => element.getBoundingClientRect().height)
const initial = await height()
const draft = "A custom answer long enough to wrap if the editor becomes multiline instead of staying single-line"
const predefined = question.getByRole("radio", { name: /Focused/ })
await predefined.click()
await input.focus()
await expect(input).toBeFocused()
await expect(predefined).toBeChecked()
await expect(toggle).not.toBeChecked()
await row.click({ position: { x: 4, y: 4 } })
await expect(toggle).toBeChecked()
await expect(input).toBeFocused()
await expect(input).toHaveValue("")
await expect(predefined).not.toBeChecked()
await input.fill(draft)
await expect(input).toHaveValue(draft)
await expect(toggle).toBeChecked()
await expect(predefined).not.toBeChecked()
await expect.poll(height).toBe(initial)
await input.press("Enter")
await expect(toggle).toBeFocused()
await expect(input).toHaveValue(draft)
await row.click({ position: { x: 30, y: 20 } })
await expect(input).toBeFocused()
await expect(input).toHaveValue(draft)
await expect
.poll(() => input.evaluate((element, original) => element === original && original.isConnected, node))
.toBe(true)
await node.dispose()
})
@@ -48,6 +48,15 @@ test("lists recent sessions before a query is entered", async ({ page }) => {
await expect(page.getByRole("heading", { name: paletteSession.title, exact: true })).toBeVisible()
})
test("reopens from its shortcut as soon as it closes", async ({ page }) => {
const { dialog, input } = await openCommandPalette(page)
await input.press("Escape")
await expect(dialog).toHaveCount(0)
// A closed dialog stops blocking shortcuts when it leaves the screen, not when it is disposed afterwards.
await page.keyboard.press("ControlOrMeta+Shift+P")
await expect(dialog.getByRole("textbox")).toBeFocused()
})
test("appends search results without resetting the selected command", async ({ page }) => {
const { dialog, input } = await openCommandPalette(page)
const files = Promise.withResolvers<void>()
@@ -4,6 +4,89 @@ import { openDraft, openSession } from "../utils/workspace"
test.use({ permissions: ["clipboard-read", "clipboard-write"] })
test("a catalog refresh cannot replace an existing session's model", async ({ page }) => {
const alpha = { id: "alpha", name: "Alpha", variants: { high: {} } }
const beta = { id: "beta", name: "Beta" }
const catalog = { current: provider(alpha, beta) }
const switches: unknown[] = []
const prompts: unknown[] = []
const sessionID = "ses_catalog_selection"
page.on("request", (request) => {
if (request.method() === "POST" && new URL(request.url()).pathname === `/api/session/${sessionID}/model`)
switches.push(request.postDataJSON())
})
const view = await openSession(page, {
name: "CatalogSelection",
sessions: [{ id: sessionID, agent: "build", model: { id: "alpha", providerID: "opencode", variant: "high" } }],
provider: () => catalog.current,
onPrompt: (input) => void prompts.push(input.body),
seed: { storage: { "opencode.global.dat:model": { recent: [{ providerID: "opencode", modelID: "beta" }] } } },
})
const control = page.locator('[data-action="composer-model"]')
await expect(control).toHaveText("Alpha")
await view.editor.fill("Keep my selected model")
catalog.current = provider(beta)
await view.push([
{
id: "evt_catalog_missing",
created: T0 + 1,
type: "model.updated",
location: { directory: view.directory },
data: {},
},
])
await expect(control).toHaveText("Select model")
await view.editor.press("Enter")
await expect(page.getByText("Select an agent and model", { exact: true })).toBeVisible()
await expect(view.editor).toHaveText("Keep my selected model")
expect(switches).toEqual([])
expect(prompts).toEqual([])
catalog.current = provider(alpha, beta)
await view.push([
{
id: "evt_catalog_restored",
created: T0 + 2,
type: "model.updated",
location: { directory: view.directory },
data: {},
},
])
await expect(control).toHaveText("Alpha")
await expect(page.getByRole("button", { name: "Choose model variant", exact: true })).toHaveText("high")
await view.editor.press("Enter")
await expect.poll(() => prompts.length).toBe(1)
expect(switches).toEqual([{ model: { id: "alpha", providerID: "opencode", variant: "high" } }])
catalog.current = provider(beta)
await view.push([
{
id: "evt_catalog_removed",
created: T0 + 3,
type: "model.updated",
location: { directory: view.directory },
data: {},
},
])
await expect(control).toHaveText("Select model")
await control.click()
await page
.getByRole("dialog", { name: "Select model" })
.getByRole("button", { name: "Beta Free", exact: true })
.click()
await expect(control).toHaveText("Beta")
await view.editor.fill("Use the replacement I chose")
await view.editor.press("Enter")
await expect.poll(() => prompts.length).toBe(2)
expect(switches).toEqual([
{ model: { id: "alpha", providerID: "opencode", variant: "high" } },
{ model: { id: "beta", providerID: "opencode" } },
])
})
async function draft(page: Page) {
const { editor } = await openDraft(page, { name: "ComposerDraft", provider: NO_PROVIDER })
await editor.click()
@@ -227,6 +310,35 @@ test("keeps a narrow session composer contained when invoking a built-in", async
await expect(editor).toBeEmpty()
})
test("keeps focus in a dialog that replaces the model dialog and returns it to the composer caret", async ({
page,
}) => {
const { editor } = await openSession(page, { name: "ComposerDialogFocus", provider: NO_PROVIDER })
await editor.fill("keep me")
await editor.press("End")
await editor.press("ArrowLeft")
await editor.press("ArrowLeft")
await editor.press("ArrowLeft")
await editor.press("ControlOrMeta+'")
const models = page.getByRole("dialog", { name: "Select model", exact: true })
await expect(models.getByRole("searchbox", { name: "Search models", exact: true })).toBeFocused()
await models.getByRole("button", { name: "Manage models", exact: true }).click()
await expect(models).toBeHidden()
const manage = page.getByRole("dialog", { name: "Manage models", exact: true })
const search = manage.getByRole("searchbox", { name: "Search models", exact: true })
await expect(search).toBeFocused()
// Code behind the dialog that focuses the composer must not pull focus out of the open dialog.
await editor.evaluate((element) => element.focus())
await expect(search).toBeFocused()
await page.keyboard.press("Escape")
await expect(manage).toBeHidden()
await expect(editor).toBeFocused()
await page.keyboard.type(",")
await expect(editor).toHaveText("keep, me")
})
test("lists slash commands in their built-in order", async ({ page }) => {
const { editor } = await openSession(page, {
name: "ComposerSlash",
@@ -292,6 +404,57 @@ for (const row of [
})
}
test("marks a Console provider with its workspace only when it is also connected directly", async ({ page }) => {
const model = (id: string, name: string) => ({ [id]: { id, name, limit: { context: 200_000 } } })
const managed = (id: string, canonical: string, name: string, models: ReturnType<typeof model>) => ({
id,
canonical,
integrationID: "opencode",
name: `Anomaly / ${name}`,
models,
})
await openSession(page, {
name: "ComposerConsoleProviders",
provider: {
all: [
managed("opencode", "opencode", "OpenCode", model("console-model", "Console Model")),
managed("console-google", "google", "Google", model("managed-gemini", "Managed Gemini")),
managed("console-openai", "openai", "OpenAI", model("managed-gpt", "Managed GPT")),
{ id: "google", canonical: "google", name: "Google", models: model("direct-gemini", "Direct Gemini") },
],
connected: ["opencode", "console-google", "console-openai", "google"],
default: { providerID: "opencode", modelID: "console-model" },
},
seed: {
storage: {
"opencode.global.dat:model": {
user: [
["opencode", "console-model"],
["console-google", "managed-gemini"],
["console-openai", "managed-gpt"],
["google", "direct-gemini"],
].map(([providerID, modelID]) => ({ providerID, modelID, visibility: "show" })),
recent: [],
variant: {},
},
},
},
})
await page.locator('[data-component="composer"] [data-action="composer-model"]').click()
const menu = page.getByRole("menu")
await expect(menu.getByRole("menuitemradio", { name: "Direct Gemini", exact: true })).toBeVisible()
const headings = menu.locator('[data-slot="menu-v2-group-label"]')
await expect(headings).toHaveCount(4)
await expect(headings.filter({ hasText: /^GoogleAnomaly$/ })).toHaveCount(1)
await expect(headings.filter({ hasText: /^Google$/ })).toHaveCount(1)
await expect(headings.filter({ hasText: /^OpenAI$/ })).toHaveCount(1)
await expect(headings.filter({ hasText: /^OpenCode$/ })).toHaveCount(1)
await expect(menu.getByText(/Anomaly \//)).toHaveCount(0)
})
test("shows thinking on hover or a non-default selection while preserving keyboard access", async ({ page }) => {
const { editor: input } = await openSession(page, {
name: "ComposerThinking",
@@ -74,14 +74,32 @@ async function setup(page: Page, input: { tabs: TabSeed[]; a?: Partial<MockServe
)
.toBe(true)
const enableAutoAccept = async () => {
await page.keyboard.press("Control+,")
const autoAccept = page.getByTestId("settings-screen").locator('[data-action="settings-auto-accept-permissions"]')
await autoAccept.locator('[data-slot="switch-control"]').click()
await expect(autoAccept.getByRole("switch")).toBeChecked()
return {
replies,
sessionGets,
transport: servers[SERVER]!.transport,
listed,
enableAutoAccept: () => enableAutoAccept(page),
}
}
return { replies, sessionGets, transport: servers[SERVER]!.transport, listed, enableAutoAccept }
async function enableAutoAccept(page: Page) {
await page.keyboard.press("Control+,")
const autoAccept = page.getByTestId("settings-screen").locator('[data-action="settings-auto-accept-permissions"]')
await autoAccept.locator('[data-slot="switch-control"]').click()
await expect(autoAccept.getByRole("switch")).toBeChecked()
}
async function chooseProjectAutoAccept(page: Page, project: string, current: string, choice: "On" | "Off") {
const settings = page.getByTestId("settings-screen")
await settings.getByRole("tab", { name: "Projects", exact: true }).click()
await settings.getByRole("button", { name: project, exact: true }).click()
const autoAccept = settings.locator('[data-action="settings-project-auto-accept-permissions"]')
await expect(autoAccept).toHaveText(current)
await autoAccept.click()
await page.getByRole("option", { name: choice, exact: true }).click()
await expect(autoAccept).toHaveText(choice)
await settings.getByRole("button", { name: "Back to projects", exact: true }).click()
}
const reply = (sessionID: string, permissionID: string) => ({
@@ -201,3 +219,60 @@ test("auto-accept approves a request discovered by opening a session", async ({
await view.enableAutoAccept()
await expect.poll(() => view.replies).toEqual([reply(sessionA.id, "permission-synced-a")])
})
test("a project's auto-accept choice overrides the default in both directions", async ({ page }) => {
const api = session({ id: "ses_project_api", directory: "/work/api", title: "API session", projectID: "proj_api" })
const web = session({ id: "ses_project_web", directory: "/work/web", title: "Web session", projectID: "proj_web" })
const requests = { [api.id]: [pending("permission-api", api.id)], [web.id]: [pending("permission-web", web.id)] }
const replies: string[] = []
await mockServers(page, {
[SERVER]: {
directory: "/work/api",
project: project({ id: "proj_api", directory: "/work/api" }),
projects: [
project({ id: "proj_api", directory: "/work/api" }),
project({ id: "proj_web", directory: "/work/web" }),
],
provider: { all: [], connected: [], default: {} },
sessions: [api, web],
pageMessages: () => ({ items: [] }),
sessionStatus: { [api.id]: { type: "running" }, [web.id]: { type: "running" } },
permissions: () => Object.values(requests).flat(),
sessionPermissions: requests,
onPermissionReply: (reply) => replies.push(reply.permissionID),
},
})
await seed(page, {
projects: { local: [{ worktree: "/work/api" }, { worktree: "/work/web" }] },
tabs: [api.id, web.id],
})
const dock = page.locator('[data-component="dock-prompt"][data-kind="permission"]')
const settings = page.getByTestId("settings-screen")
await page.goto(sessionHref(web.id))
await expectSessionTitle(page, web.title)
await expect(dock.getByText("git status")).toBeVisible()
// On for api while the default is off; off for web before the default turns on.
await page.keyboard.press("Control+,")
await chooseProjectAutoAccept(page, "api", "Use default (Off)", "On")
await expect.poll(() => replies).toEqual(["permission-api"])
await chooseProjectAutoAccept(page, "web", "Use default (Off)", "Off")
await settings.getByRole("tab", { name: "Preferences", exact: true }).click()
const autoAccept = settings.locator('[data-action="settings-auto-accept-permissions"]')
await autoAccept.locator('[data-slot="switch-control"]').click()
await expect(autoAccept.getByRole("switch")).toBeChecked()
await settings.getByRole("button", { name: "Back to app" }).click()
await expectSessionTitle(page, web.title)
await expect(dock.getByText("git status")).toBeVisible()
expect(replies).toEqual(["permission-api"])
// Back on the default, web follows it.
await page.keyboard.press("Control+,")
await settings.getByRole("tab", { name: "Projects", exact: true }).click()
await settings.getByRole("button", { name: "web", exact: true }).click()
await settings.locator('[data-action="settings-project-auto-accept-permissions"]').click()
await page.getByRole("option", { name: "Use default (On)" }).click()
await expect.poll(() => replies).toEqual(["permission-api", "permission-web"])
})
+262 -12
View File
@@ -86,7 +86,9 @@ test("Git initialization belongs to its session and refreshes after a session sw
await expect(pending).toHaveCount(0)
})
test("a rejected Git init releases its session's button without showing an error in another session", async ({ page }) => {
test("a rejected Git init releases its session's button without showing an error in another session", async ({
page,
}) => {
await openSession(page, {
name: "ReviewInitFailure",
project: { vcs: undefined },
@@ -143,7 +145,7 @@ test("open file tab browses, searches, and tracks missing files", async ({ page
const panel = page.locator("#review-panel")
const sidebar = panel.locator('[data-slot="session-review-v2-sidebar"]')
const sidebarToggle = panel.getByRole("button", { name: "Toggle file tree" })
const contextButton = page.getByRole("button", { name: "View context usage" })
const contextButton = page.getByRole("button", { name: "Toggle session context" })
const openFile = panel.getByRole("button", { name: "Open file" })
const tab = (name: string) => panel.getByRole("tab", { name, exact: true })
await contextButton.click()
@@ -181,7 +183,7 @@ test("open file tab browses, searches, and tracks missing files", async ({ page
const missingResponse = page.waitForResponse((response) => response.url().includes("/api/fs/read/README.md"))
await workspace.push([filesystemEvent(directory, "README.md", "unlink")])
await missingResponse
await expect(page.getByText("Failed to load file", { exact: true })).toBeVisible()
await expect(page.getByText("Failed to load file", { exact: true })).toHaveCount(0)
await expect(tab("File not found: README.md")).toHaveAttribute("aria-selected", "true")
await expect(panel.getByText("File not found: README.md", { exact: true })).toBeVisible()
@@ -309,7 +311,7 @@ test("context closes the side region only when its button opened it", async ({ p
})
const panel = page.locator("#review-panel")
const toggle = page.getByRole("button", { name: "Toggle review", exact: true })
const contextButton = page.getByRole("button", { name: "View context usage" })
const contextButton = page.getByRole("button", { name: "Toggle session context" })
const context = panel.getByRole("tab", { name: "Context", exact: true })
await contextButton.click()
@@ -333,6 +335,83 @@ test("context closes the side region only when its button opened it", async ({ p
await expect(panel.locator("#session-side-panel-review-tab")).toHaveAttribute("aria-selected", "true")
})
test("context hides free-model cost but keeps paid-model zero cost", async ({ page }) => {
const cases = [
{ id: "ses_context_free", title: "Free model", model: "free", cost: 0, usage: false, text: "0" },
{ id: "ses_context_paid", title: "Paid model", model: "paid", cost: 0, usage: false, text: "0·$0.00" },
{ id: "ses_context_used", title: "Paid usage", model: "paid", cost: 1.25, usage: true, text: "2k·$1.25" },
{ id: "ses_context_free_used", title: "Free usage", model: "free", cost: 0, usage: true, text: "2k" },
{ id: "ses_context_mixed", title: "Previously paid", model: "free", cost: 1.25, usage: true, text: "2k·$1.25" },
{ id: "ses_context_unknown", title: "Unknown pricing", model: "missing", cost: 0, usage: false, text: "0·$0.00" },
{ id: "ses_context_output", title: "Output pricing", model: "output", cost: 0, usage: false, text: "0·$0.00" },
// The root's model is free, but its subagent spent on a paid model: the family total shows.
{ id: "ses_context_family", title: "Paid subagent", model: "free", cost: 0, usage: true, text: "2k·$1.25" },
// A completed compaction resets the context until the next reply reports usage, as in the TUI.
{ id: "ses_context_compacted", title: "Compacted", model: "paid", cost: 1.25, usage: true, text: "0·$1.25" },
]
await openSession(page, {
name: "ContextPricing",
provider: provider(
{ id: "free", name: "Free", cost: { input: 0, output: 0 } },
{ id: "paid", name: "Paid", cost: { input: 1, output: 3 } },
{ id: "output", name: "Output", cost: { input: 0, output: 1 } },
),
sessions: [
...cases.map((item) => ({
id: item.id,
title: item.title,
model: { id: item.model, providerID: "opencode" },
cost: item.cost,
})),
{
id: "ses_context_family_child",
parentID: "ses_context_family",
title: "Subagent run",
model: { id: "paid", providerID: "opencode" },
cost: 1.25,
},
],
pageMessages: (id) => ({
items: cases.flatMap((item): SessionMessageInfo[] =>
item.id === id && item.usage
? [
{
id: `msg_${item.id}`,
type: "assistant",
agent: "build",
model: { id: item.model, providerID: "opencode" },
tokens: { input: 1500, output: 500, reasoning: 0, cache: { read: 0, write: 0 } },
content: [{ type: "text", text: "Done." }],
time: { created: 1, completed: 2 },
},
...(item.id === "ses_context_compacted"
? [
{
id: `msg_${item.id}_compaction`,
type: "compaction" as const,
status: "completed" as const,
reason: "manual" as const,
summary: "Current state",
recent: "",
time: { created: 3 },
},
]
: []),
]
: [],
),
}),
})
const button = page.getByRole("button", { name: "Toggle session context", exact: true })
for (const item of cases) {
await page.locator("[data-titlebar-tab-slot]", { hasText: item.title }).click()
await expectSessionTitle(page, item.title)
await expect(button).toHaveText(item.text)
}
})
test("file tree expands Windows paths and scrolls long names in both directions", async ({ page }) => {
const directory = "C:/OpenCode/OpenFileExpand"
const longFilename = "a-very-long-file-name-that-must-overflow-the-file-sidebar-instead-of-being-truncated.ts"
@@ -493,12 +572,156 @@ test("rereads a file each time an artifact link opens it", async ({ page }) => {
await expect(tab).toHaveAttribute("aria-selected", "true")
await expect(panel.getByText("second draft", { exact: true })).toBeVisible()
await expect(panel.getByText("first draft", { exact: true })).toHaveCount(0)
// A restored file tab whose file was deleted shows its inline not-found state without a toast; clicking a broken link
// when no tab is open for it shows the toast.
await page.route("**/api/fs/read/shopping.txt*", (route) =>
route.fulfill({
status: 404,
headers: { "access-control-allow-origin": "*" },
// SAFETY: the server's wire body for a missing file, which the client decodes into its own error.
// oxlint-disable-next-line anti-slop-effect/no-manual-tagged-construction -- see SAFETY above
json: { _tag: "FileNotFoundError", path: "shopping.txt", message: "File not found: shopping.txt" },
}),
)
await page.reload()
const missingTab = panel.getByRole("tab", { name: "File not found: shopping.txt", exact: true })
await expect(missingTab).toHaveAttribute("aria-selected", "true")
await expect(panel.getByText("File not found: shopping.txt", { exact: true })).toBeVisible()
await expect(page.getByText("Failed to load file", { exact: true })).toHaveCount(0)
await missingTab.locator("..").getByRole("button", { name: "Close tab" }).click()
await expect(missingTab).toHaveCount(0)
await link.click()
await expect(page.getByText("Failed to load file", { exact: true })).toBeVisible()
await expect(missingTab).toHaveCount(0)
})
/** What the image case's frame probe records on the window. */
type ImageProbe = { problems: string[]; frames: number; running: boolean }
test("image files keep the review panel painted while loading", async ({ page }) => {
test("image gestures anchor zoom, pan, and reset independently of the pane", async ({ page }) => {
// Some browsers expose no natural dimensions for a viewBox-only SVG.
await page.addInitScript(() => {
for (const name of ["naturalWidth", "naturalHeight"]) {
const original = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, name)!
Object.defineProperty(HTMLImageElement.prototype, name, {
...original,
get() {
return this.alt === "second.svg" ? 0 : original.get?.call(this)
},
})
}
})
await openSession(page, {
name: "ImageGestures",
fileList: () => [],
fileContent: (path) => ({
content:
path === "second.svg"
? '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1600"><rect width="1600" height="1600" fill="#6699aa"/></svg>'
: '<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1600"><rect width="1600" height="1600" fill="#6699aa"/></svg>',
}),
pageMessages: () => ({
items: [
{
id: "msg_images",
type: "assistant",
agent: "build",
model: { id: "test", providerID: "opencode" },
content: [{ type: "text", text: "[First](first.svg) [Second](second.svg)" }],
time: { created: 1, completed: 2 },
},
],
}),
})
await page.getByRole("link", { name: "First", exact: true }).click()
const panel = page.locator("#review-panel")
const image = panel.getByRole("img", { name: "first.svg", exact: true })
const stage = panel.locator('[data-slot="artifact-stage"]')
const fit = panel.getByRole("button", { name: "Fit", exact: true })
await expect(image).toBeVisible()
await expect(fit).toBeDisabled()
// Wait for the side pane's opening motion before choosing a gesture anchor.
await image.hover()
const initial = (await image.boundingBox())!
const pane = (await panel.boundingBox())!
const anchor = { x: Math.round(initial.x + initial.width * 0.55), y: Math.round(initial.y + initial.height * 0.55) }
await page.mouse.move(anchor.x, anchor.y)
// A continuous pinch catches anchor drift while the image still fits one axis.
const cdp = await page.context().newCDPSession(page)
await cdp.send("Input.synthesizePinchGesture", {
...anchor,
scaleFactor: 2,
relativeSpeed: 500,
gestureSourceType: "mouse",
})
await cdp.detach()
await expect(fit).toBeEnabled()
const zoomed = (await image.boundingBox())!
expect(zoomed.width).toBeCloseTo(initial.width * 2, 1)
expect((anchor.x - zoomed.x) / zoomed.width).toBeCloseTo((anchor.x - initial.x) / initial.width, 4)
expect((anchor.y - zoomed.y) / zoomed.height).toBeCloseTo((anchor.y - initial.y) / initial.height, 4)
expect(await panel.boundingBox()).toEqual(pane)
expect(await page.evaluate(() => window.visualViewport?.scale)).toBe(1)
await page.mouse.wheel(40, 60)
await expect.poll(async () => (await image.boundingBox())!.x).toBeCloseTo(zoomed.x - 40, 1)
expect((await image.boundingBox())!.y).toBeCloseTo(zoomed.y - 60, 1)
const scrolled = (await image.boundingBox())!
await page.mouse.down()
await page.mouse.move(anchor.x + 60, anchor.y + 40, { steps: 5 })
await page.mouse.up()
await expect(fit).toBeEnabled()
expect((await image.boundingBox())!.x).toBeCloseTo(scrolled.x + 60, 1)
expect((await image.boundingBox())!.y).toBeCloseTo(scrolled.y + 40, 1)
// Touch uses the same captured-pointer path and must not generate a click-to-fit.
const touch = await page.context().newCDPSession(page)
await touch.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x: anchor.x, y: anchor.y }] })
await touch.send("Input.dispatchTouchEvent", {
type: "touchMove",
touchPoints: [{ x: anchor.x - 30, y: anchor.y - 20 }],
})
await touch.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] })
await touch.detach()
await expect(fit).toBeEnabled()
expect((await image.boundingBox())!.x).toBeCloseTo(scrolled.x + 30, 1)
expect((await image.boundingBox())!.y).toBeCloseTo(scrolled.y + 20, 1)
// Keyboard-accessible fit restores the exact original geometry.
await fit.focus()
await page.keyboard.press("Enter")
await expect(fit).toBeDisabled()
expect(await image.boundingBox()).toEqual(initial)
expect(
await stage.evaluate((element) =>
element.dispatchEvent(new WheelEvent("wheel", { deltaY: 40, bubbles: true, cancelable: true })),
),
).toBe(true)
await image.click()
await expect(fit).toBeEnabled()
await page.getByRole("link", { name: "Second", exact: true }).click()
await expect(panel.getByRole("img", { name: "second.svg", exact: true })).toBeVisible()
await expect(fit).toBeDisabled()
await panel.getByRole("img", { name: "second.svg", exact: true }).hover()
const second = (await panel.getByRole("img", { name: "second.svg", exact: true }).boundingBox())!
expect(second.width).toBeGreaterThan(0)
expect(second.height).toBeGreaterThan(0)
await page.keyboard.down("Control")
await page.mouse.wheel(0, -50)
await expect(fit).toBeEnabled()
await page.keyboard.up("Control")
await fit.click()
await page.setViewportSize({ width: 1200, height: 700 })
await expect
.poll(async () => {
const frame = (await stage.boundingBox())!
const media = (await panel.getByRole("img", { name: "second.svg", exact: true }).boundingBox())!
return media.width <= frame.width - 47 && media.height <= frame.height - 47
})
.toBe(true)
})
test("image files load into the review panel and keep it painted while loading", async ({ page }) => {
await page.setViewportSize({ width: 960, height: 900 })
const directory = "C:/OpenCode/ReviewImage"
const image = "assets/preview.png"
@@ -512,7 +735,13 @@ test("image files keep the review panel painted while loading", async ({ page })
read.resolve()
await release.promise
return { type: "binary", content: "iVBORw0KGgo=", encoding: "base64", mimeType: "image/png" }
// A 1x1 PNG.
return {
type: "binary",
content: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",
encoding: "base64",
mimeType: "image/png",
}
},
fileList: (path) => {
if (!path) return [fileNode(directory, "assets", "directory"), fileNode(directory, "src", "directory")]
@@ -568,6 +797,10 @@ test("image files keep the review panel painted while loading", async ({ page })
release.resolve()
await response
await expect(page.locator('[data-slot="session-review-v2-file-name"]')).toHaveText("preview.png")
await expect(page.locator("#review-panel").getByRole("img", { name: image, exact: true })).toHaveJSProperty(
"naturalWidth",
1,
)
const loaded = await frames()
await expect.poll(frames).toBeGreaterThan(loaded)
expect(
@@ -581,17 +814,23 @@ test("image files keep the review panel painted while loading", async ({ page })
).toEqual([])
})
test("video files expand into an in-window theatre overlay and collapse on Escape without remounting", async ({
test("video files over 25 MB play in the viewer, expand into the theatre overlay, and collapse on Escape without remounting", async ({
page,
}) => {
const directory = "C:/OpenCode/ReviewVideo"
const file = "demo.webm"
const file = "arcade-update-draft.mp4"
const webm = Buffer.from(
"GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAH5EU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHWTbuMU6uEElTDZ1OsggEyTbuMU6uEHFO7a1OsggHj7AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmsCrXsYMPQkBNgIxMYXZmNjMuMS4xMDJXQYxMYXZmNjMuMS4xMDJEiYhAj0AAAAAAABZUrmvXrgEAAAAAAABO14EBc8WIiQeUklk95R2cgQAitZyDdW5kiIEAhoVWX1ZQOIOBASPjg4Q7msoA4JCwgUC6gSSagQJVsIRVuYEBVe6BAOwBAAAAAAAAAgAAElTDZ/pzc59jwIBnyJlFo4dFTkNPREVSRIeMTGF2ZjYzLjEuMTAyc3PVY8CLY8WIiQeUklk95R1nyKBFo4dFTkNPREVSRIeTTGF2YzYzLjEuMTAyIGxpYnZweGfIoUWjiERVUkFUSU9ORIeTMDA6MDA6MDEuMDAwMDAwMDAwAB9DtnWt54EAo6iBAACAsAIAnQEqQAAkAABHCIWFiJmEiAICAAaOT8zHm/FYAP7/q1CAHFO7a5G7j7OBALeK94EB8YIBsfCBAw==",
const head = Buffer.from(
"AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAAMm1kYXSCSYNCAAPwAjYAOCQcGEIAADBgAABYS///mpmB/////7FMC////+OkgAAAAAL+bW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAAA+gAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAil0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAA+gAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAEAAAAAkAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAPoAAAAAAABAAAAAAGhbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAAAQABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAABTG1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQxzdGJsAAAAqHN0c2QAAAAAAAAAAQAAAJh2cDA5AAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAEAAJABIAAAASAAAAAAAAAABF0xhdmM2My4xLjEwMiBsaWJ2cHgtdnA5AAAAAAAAAAAAGP//AAAAFHZwY0MBAAAAAAqCAgICAAAAAAAKZmllbAEAAAAAEHBhc3AAAAABAAAAAQAAABRidHJ0AAAAAAAAJxAAAAAAAAAAGHN0dHMAAAAAAAAAAQAAAAEAAEAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAACoAAAABAAAAFHN0Y28AAAAAAAAAAQAAACwAAABhdWR0YQAAAFltZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAACxpbHN0AAAAJKl0b28AAAAcZGF0YQAAAAEAAAAATGF2ZjYzLjEuMTAy",
"base64",
)
const mp4 = Buffer.alloc(38_400_000)
head.copy(mp4)
mp4.writeUInt32BE(mp4.length - head.length, head.length)
mp4.write("free", head.length + 4, "ascii")
await openSession(page, {
name: "ReviewVideo",
fileList: (path) => (path ? [] : [fileNode(directory, file)]),
@@ -603,7 +842,7 @@ test("video files expand into an in-window theatre overlay and collapse on Escap
route.fulfill({
status: 200,
headers: { "access-control-allow-origin": "*", "content-type": "application/octet-stream" },
body: webm,
body: mp4,
}),
)
@@ -612,12 +851,17 @@ test("video files expand into an in-window theatre overlay and collapse on Escap
await panel.getByRole("button", { name: file }).click()
await expect(panel.getByRole("tab", { name: file, exact: true })).toHaveAttribute("aria-selected", "true")
const toolbar = panel.locator('[data-slot="artifact-toolbar"]')
const stage = panel.locator('[data-slot="artifact-stage"]')
const video = stage.locator('video[data-slot="artifact-media"]')
const fullscreen = stage.getByRole("button", { name: "Enter full screen", exact: true })
const exitFullscreen = stage.getByRole("button", { name: "Exit full screen", exact: true })
await expect(video).toBeVisible()
await expect(toolbar).toContainText("64 × 36")
await expect(toolbar).toContainText("0:01")
await expect(toolbar).toContainText("38.4 MB")
await expect(panel.getByText(/Binary file/)).toHaveCount(0)
await expect(fullscreen).toHaveAttribute("aria-pressed", "false")
const inlineBounds = (await stage.boundingBox())!
expect(inlineBounds.width).toBeLessThan(1000)
@@ -646,6 +890,12 @@ test("video files expand into an in-window theatre overlay and collapse on Escap
await page.mouse.click(8, 8)
await expect(fullscreen).toHaveAttribute("aria-pressed", "false")
expect(await video.evaluate((element) => element.dataset.e2eProbe)).toBe("retained")
// Chromium's controls also answer a double click with native fullscreen, which covers the backdrop. Opting out with
// controlslist="nofullscreen" would end their click-to-play as well.
await video.click()
await expect.poll(() => video.evaluate((element: HTMLVideoElement) => element.currentTime)).toBeGreaterThan(0)
expect(await page.evaluate(() => document.fullscreenElement)).toBeNull()
})
test("restores review state and the side-panel tab per session", async ({ page }) => {
@@ -697,7 +947,7 @@ test("restores review state and the side-panel tab per session", async ({ page }
await page.getByRole("option", { name: "Branch changes" }).click()
await page.getByRole("button", { name: "beta.ts" }).click()
await selectedFile("beta.ts")
await page.getByRole("button", { name: "View context usage" }).click()
await page.getByRole("button", { name: "Toggle session context" }).click()
await selectedTab("Context")
await switchSession("Gamma review state")
@@ -224,8 +224,15 @@ test("follow-up preference controls Enter while Mod+Enter uses the alternate del
await expect(view.input).toHaveText("")
})
test("a steer shows in the timeline as the composer clears, before its selection commits", async ({ page }) => {
const mock = createQueueMock([])
test("a steer shows as pending in the timeline as the composer clears, before its selection commits", async ({
page,
}) => {
// The running execution has delivered input, so a new steer waits behind its work.
const mock = createQueueMock(
[],
[{ id: "msg_queue_delivered", type: "user", text: "First prompt", time: { created: 1 } }],
)
const view = await openQueue(page, mock, "steer")
const commit = await holdRoute(page, (url) => url.pathname === `/api/session/${sessionID}/model`, { method: "POST" })
@@ -233,16 +240,21 @@ test("a steer shows in the timeline as the composer clears, before its selection
hasText: "steer while the model commits",
})
await expect(userRow(page, "msg_queue_delivered")).toContainText("First prompt")
await view.input.fill("steer while the model commits")
await view.input.press("Enter")
await commit.arrived
await expect(view.input).toHaveText("")
await expect(prompt).toBeVisible()
await expect(prompt.locator('[data-component="user-message"]')).toHaveAttribute("data-pending", "true")
// It turns pending at once rather than fading from the delivered color it may have rendered with first.
await expect(prompt.locator('[data-slot="user-message-text"]')).toHaveCSS("transition-duration", "0s")
expect(mock.prompts).toEqual([])
commit.release()
await expect.poll(() => mock.prompts.map((item) => item.text)).toEqual(["steer while the model commits"])
await expect(prompt).toHaveCount(1)
await expect(prompt.locator('[data-component="user-message"]')).toHaveAttribute("data-pending", "true")
})
test("a steer into an idle session leaves the finished turn finished until delivery", async ({ page }) => {
@@ -1027,10 +1039,23 @@ for (const delivery of ["steer", "queue"] as const) {
})
.toBe(true)
// Working ends the work the model has seen, so the steer it has not seen yet waits below it.
const working = transcript.locator('[data-component="session-working"]')
await expect(tools.or(working).or(pending)).toHaveText([
/^Used\s*2\s*Read, Grep$/,
/Working/,
/U2: Also check the retry path\./,
])
mock.rows.splice(0, 1)
mock.emit("session.inbox.delivered", { sessionID, inboxID })
await expect(thinking).toHaveCount(0)
await expect(pending).toHaveCount(1)
await expect(tools.or(pending).or(working)).toHaveText([
/^Used\s*2\s*Read, Grep$/,
/U2: Also check the retry path\./,
/Working/,
])
if (colors) {
await expect(bubble).toHaveAttribute("data-delivery-marker", "pending")
@@ -83,6 +83,93 @@ test("shows a pending question dock", async ({ page }) => {
expect((await reply).postDataJSON()).toEqual({ answer: { q0: "minimal" } })
})
test("replies with predefined choices and the edited custom multiselect answer", async ({ page }) => {
await mockServer(page, {
forms: [
{
id: "frm_question_multiselect",
sessionID,
title: "Questions",
metadata: { kind: "question" },
fields: [
{
key: "q0",
type: "multiselect",
title: "Include",
description: "Which supporting surfaces should remain visible?",
options: [
{ value: "files", label: "Changed files" },
{ value: "terminal", label: "Terminal" },
],
custom: true,
},
],
},
],
})
await page.goto(sessionHref(sessionID))
await expectSessionTitle(page, title)
const question = page.locator('[data-component="dock-prompt"][data-kind="question"]')
const files = question.getByRole("checkbox", { name: "Changed files", exact: true })
const terminal = question.getByRole("checkbox", { name: "Terminal", exact: true })
const custom = question.getByRole("checkbox", { name: "Type your own answer…", exact: true })
const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true })
const cancellations: string[] = []
page.on("request", (request) => {
if (
request.method() === "DELETE" &&
new URL(request.url()).pathname === `/api/session/${sessionID}/form/frm_question_multiselect`
)
cancellations.push(request.url())
})
await expect(files).not.toBeChecked()
await files.click()
await input.fill("Original custom answer")
await expect(custom).toBeChecked()
await expect(files).toBeChecked()
await terminal.click()
await expect(terminal).toBeChecked()
await expect(custom).toBeChecked()
await expect(files).toBeChecked()
await custom.click()
await expect(custom).not.toBeChecked()
await expect(input).toHaveValue("Original custom answer")
await expect(files).toBeChecked()
await expect(terminal).toBeChecked()
await input.focus()
await expect(custom).not.toBeChecked()
await expect(files).toBeChecked()
await expect(terminal).toBeChecked()
await custom.click()
await expect(custom).toBeChecked()
await expect(input).toHaveValue("Original custom answer")
await expect(files).toBeChecked()
await expect(terminal).toBeChecked()
await input.fill("Updated custom answer")
await input.press("Escape")
await expect(input).not.toBeFocused()
await expect(question.getByRole("button", { name: "Submit", exact: true })).toBeEnabled()
await expect(input).toHaveValue("Updated custom answer")
await expect(custom).toBeChecked()
await expect(files).toBeChecked()
await expect(terminal).toBeChecked()
expect(cancellations).toEqual([])
const reply = page.waitForRequest(
(request) =>
request.method() === "POST" &&
new URL(request.url()).pathname === `/api/session/${sessionID}/form/frm_question_multiselect/reply`,
)
await question.getByRole("button", { name: "Submit", exact: true }).press("Control+Enter")
expect((await reply).postDataJSON()).toEqual({ answer: { q0: ["files", "terminal", "Updated custom answer"] } })
expect(cancellations).toEqual([])
})
test("shows a pending permission dock", async ({ page }) => {
const replies: { sessionID: string; permissionID: string; body: unknown }[] = []
await mockServer(page, {
@@ -18,6 +18,11 @@ for (const custom of [false, true]) {
const summary = page.getByRole("dialog", { name: "Session details", exact: true })
await expect(page.locator('[data-component="composer-editor"]')).toBeEditable()
await expect(trigger).toBeEnabled()
// The trigger scrolls with the timeline under its sticky header, and Kobalte closes a tooltip whenever its
// trigger scrolls. A cold timeline keeps scrolling to its bottom until it reveals its rows, so hover after that.
await expect(
page.locator(`[data-timeline-row="UserMessage"][data-message-id="${fixture.expected.sourceMessageIDs.at(-1)}"]`),
).toBeVisible()
await trigger.hover()
const tooltip = page.getByRole("tooltip")
await expect(tooltip).toContainText("Summary")
+494 -1
View File
@@ -1,7 +1,7 @@
import { expect, test, type Page } from "@playwright/test"
import type { ConfigEntry, OpenCodeEvent, WorktreeDirectory } from "@opencode/client/promise"
import { NO_PROVIDER, REMOTE_SERVER, SERVER, holdRoute, project, session } from "../utils/app"
import { mockOpenCodeServer } from "../utils/mock-server"
import { mockMissingLocation, mockOpenCodeServer } from "../utils/mock-server"
import { mockRemoteServer, mockWorkspace, openSettings, type WorkspaceInput } from "../utils/workspace"
const directory = "C:/Projects/settings-demo"
@@ -248,6 +248,41 @@ test("project settings open as a nested view that keeps its route", async ({ pag
await expect(settings.getByRole("heading", { name: "Projects", exact: true })).toBeVisible()
})
// The desktop app reopens its last settings URL on launch, so a crash on this page would repeat on every restart.
test("a project whose folder is gone opens its settings with a notice", async ({ page }) => {
await mockWorkspace(page, {
name: "Settings demo",
directory,
provider: NO_PROVIDER,
sessions: [],
seed: { tabs: [] },
})
await mockMissingLocation(page, directory)
const plugins = page.waitForResponse((response) => {
const url = new URL(response.url())
return url.pathname === "/api/plugin" && url.searchParams.get("location[directory]") === directory
})
await page.goto(
`/settings?server=${encodeURIComponent(SERVER)}&project=${encodeURIComponent(directory)}&tab=extensions`,
)
expect((await plugins).status()).toBe(404)
const settings = page.getByTestId("settings-screen")
const notice = settings.getByRole("status").filter({ hasText: "Project folder not found" })
await expect(notice).toContainText(directory)
await settings.getByRole("tab", { name: "Plugins", exact: true }).click()
await expect(
settings.getByRole("tabpanel", { name: "Plugins", exact: true }).getByText("No plugins yet", { exact: true }),
).toBeVisible()
await settings.getByRole("tab", { name: "General", exact: true }).click()
await expect(settings.getByRole("textbox", { name: "Project name", exact: true })).toBeVisible()
await expect(notice).toContainText(directory)
})
for (const field of [
{
name: "color",
@@ -750,6 +785,464 @@ for (const row of [
})
}
const consoleIntegrations = [
{
id: "opencode",
name: "OpenCode Console",
methods: [
{ id: "device", type: "oauth", label: "OpenCode Console account" },
{ type: "key", label: "API key (service account)" },
],
connections: [],
},
{ id: "opencode-go", name: "OpenCode Go", methods: [{ type: "key" }], connections: [] },
]
for (const row of [
{ provider: "OpenCode Console", connect: "Connect OpenCode Console", signIn: "Connecting to OpenCode Console" },
{ provider: "OpenCode Go", connect: "Connect OpenCode Go", signIn: "Connecting to OpenCode Go" },
]) {
test(`providers: ${row.provider} signs in from the Console intro`, async ({ page, context }) => {
const url = "https://auth.example.test/device?user_code=ABCD-EFGH"
await context.route("https://auth.example.test/**", (route) => route.fulfill({ body: "Sign in" }))
const { settings } = await open(page, { integrations: consoleIntegrations, onIntegrationOAuth: () => ({ url }) })
// Registered after the mock server so it sees the sign-in request first.
const start = await holdRoute(page, (url) => url.pathname === "/api/integration/opencode/connect/oauth", {
method: "POST",
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
await settings
.locator(".settings-provider-row", { hasText: row.provider })
.getByRole("button", { name: "Connect", exact: true })
.click()
const intro = page.getByRole("dialog", { name: row.connect, exact: true })
const container = page.locator('[data-slot="dialog-container"]')
await expect(
intro.getByText("Sign in with your OpenCode Console account to use the available models."),
).toBeVisible()
await expect(intro.getByRole("button", { name: "Use API key", exact: true })).toBeVisible()
expect((await container.boundingBox())?.height).toBe(512)
const popup = page.waitForEvent("popup")
await intro.getByRole("button", { name: "Continue in the browser", exact: true }).click()
await start.arrived
await expect(intro.getByRole("button", { name: "Opening browser…", exact: true })).toBeDisabled()
expect((await container.boundingBox())?.height).toBe(512)
start.release()
await expect(await popup).toHaveURL(url)
const signIn = page.getByRole("dialog", { name: row.signIn, exact: true })
await expect(signIn.getByRole("group", { name: "Device code: ABCD-EFGH", exact: true })).toBeVisible()
await expect(signIn.getByRole("button", { name: "Copy sign-in link", exact: true })).toBeVisible()
await expect(signIn.getByRole("button", { name: "Use API key", exact: true })).toHaveCount(0)
await expect.poll(async () => (await container.boundingBox())?.height).toBeLessThan(512)
})
}
test("providers: the connect dialog lists connected providers and manages their accounts", async ({ page }) => {
const accounts = [
{ type: "credential", id: "cred_work", label: "Work", method: "key" },
{ type: "credential", id: "cred_personal", label: "Personal", method: "key" },
]
const state = { active: "cred_work" }
const activated: string[] = []
const { settings } = await open(page, {
integrations: () => [
{
id: "openai",
name: "OpenAI",
methods: [{ type: "key", label: "API key" }],
connections: accounts.toSorted((a, b) => Number(b.id === state.active) - Number(a.id === state.active)),
},
{ id: "anthropic", name: "Anthropic", methods: [{ type: "key", label: "API key" }], connections: [] },
],
onCredentialActivate: (credentialID) => {
activated.push(credentialID)
state.active = credentialID
},
onCredentialUpdate: (credentialID, body) => {
const account = accounts.find((item) => item.id === credentialID)
if (account && body.label) account.label = body.label
},
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
await settings.getByRole("button", { name: "Show more providers", exact: true }).click()
const dialog = page.getByRole("dialog")
const openai = dialog.locator('[data-provider-id="openai"]')
const count = openai.locator('[data-component="tag"]')
await expect(count).toHaveText("2")
await expect(count).toHaveAttribute("aria-label", "2 accounts")
await expect(dialog.locator('[data-provider-id="anthropic"]').locator('[data-component="tag"]')).toHaveCount(0)
await openai.click()
await expect(page.getByRole("dialog", { name: "OpenAI", exact: true })).toBeVisible()
const list = dialog.getByRole("radiogroup", { name: "Connected accounts", exact: true })
await expect(list.getByRole("radio", { name: "Work", exact: true })).toHaveAttribute("aria-checked", "true")
// Rows keep their order when the active account changes.
await expect(list.getByRole("radio")).toHaveText(["Personal", "Work"])
await list.getByRole("radio", { name: "Personal", exact: true }).click()
await expect(list.getByRole("radio", { name: "Personal", exact: true })).toHaveAttribute("aria-checked", "true")
await expect(list.getByRole("radio")).toHaveText(["Personal", "Work"])
expect(activated).toEqual(["cred_personal"])
await list.getByRole("button", { name: "Personal options", exact: true }).click()
await page.getByRole("menuitem", { name: "Rename", exact: true }).click()
const name = list.getByRole("textbox", { name: "Account name", exact: true })
await expect(name).toBeFocused()
await expect(name).toHaveValue("Personal")
await name.fill("Home")
await name.press("Enter")
await expect(list.getByRole("radio")).toHaveText(["Home", "Work"])
await expect(list.getByRole("radio", { name: "Home", exact: true })).toHaveAttribute("aria-checked", "true")
await list.getByRole("button", { name: "Home options", exact: true }).click()
await page.getByRole("menuitem", { name: "Rename", exact: true }).click()
await name.fill("Ignored")
await name.press("Escape")
await expect(list.getByRole("radio")).toHaveText(["Home", "Work"])
await expect(page.getByRole("dialog", { name: "OpenAI", exact: true })).toBeVisible()
await list.getByRole("button", { name: "Work options", exact: true }).click()
await page.getByRole("menuitem", { name: "Remove", exact: true }).click()
await expect(dialog.getByText("Remove Work?", { exact: true })).toBeVisible()
const removed = page.waitForRequest(
(request) => request.method() === "DELETE" && new URL(request.url()).pathname === "/api/credential/cred_work",
)
await dialog.getByRole("button", { name: "Remove", exact: true }).click()
await removed
await dialog.getByRole("button", { name: "Add another account", exact: true }).click()
await expect(dialog.getByPlaceholder("API key")).toBeVisible()
await dialog.getByRole("button", { name: "Navigate back", exact: true }).click()
await expect(list).toBeVisible()
})
test("providers: adding a Go account uses a Go key, and a lone sign-in starts once", async ({ page, context }) => {
await context.route("https://auth.example.test/**", (route) => route.fulfill({ body: "Sign in" }))
const attempts: string[] = []
const { settings } = await open(page, {
integrations: [
...consoleIntegrations.filter((integration) => integration.id !== "opencode-go"),
{
id: "opencode-go",
name: "OpenCode Go",
methods: [{ type: "key" }],
connections: [{ type: "credential", id: "cred_go", label: "Go key", method: "key" }],
},
{
id: "github-copilot",
name: "GitHub Copilot",
methods: [{ id: "device", type: "oauth", label: "GitHub" }],
connections: [{ type: "credential", id: "cred_gh", label: "Octocat", method: "oauth" }],
},
],
onIntegrationOAuth: (input) => {
attempts.push(input.integrationID)
return { url: "https://auth.example.test/device?user_code=GH12-3456" }
},
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
await settings.getByRole("button", { name: "Show more providers", exact: true }).click()
const dialog = page.getByRole("dialog")
await dialog.locator('[data-provider-id="opencode-go"]').click()
await dialog.getByRole("button", { name: "Add another account", exact: true }).click()
await expect(dialog.getByPlaceholder("API key")).toBeVisible()
expect(attempts).toEqual([])
await dialog.getByRole("button", { name: "Navigate back", exact: true }).click()
await expect(dialog.getByRole("radio", { name: "Go key", exact: true })).toBeVisible()
await dialog.getByRole("button", { name: "Navigate back", exact: true }).click()
await dialog.locator('[data-provider-id="github-copilot"]').click()
const popup = page.waitForEvent("popup")
await dialog.getByRole("button", { name: "Add another account", exact: true }).click()
await popup
await expect.poll(() => attempts).toEqual(["github-copilot"])
expect(attempts).toEqual(["github-copilot"])
})
test("providers: the account options rename and remove the active account", async ({ page }) => {
const account = { type: "credential", id: "cred_work", label: "Work", method: "key" }
const other = { type: "credential", id: "cred_personal", label: "Personal", method: "key" }
const removed: string[] = []
const { settings } = await open(page, {
provider: { all: [{ id: "openai", name: "OpenAI", models: {} }], connected: ["openai"], default: {} },
integrations: () => [
{
id: "openai",
name: "OpenAI",
methods: [{ type: "key", label: "API key" }],
connections: [account, other].filter((item) => !removed.includes(item.id)),
},
],
onCredentialUpdate: (credentialID, body) => {
const target = [account, other].find((item) => item.id === credentialID)
if (target && body.label) target.label = body.label
},
})
page.on("request", (request) => {
const path = new URL(request.url()).pathname
if (request.method() === "DELETE" && path.startsWith("/api/credential/")) removed.push(path.split("/").at(-1)!)
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
const trigger = settings.getByRole("button", { name: "Manage OpenAI accounts", exact: true })
await expect(trigger).toHaveText("Work")
await trigger.click()
await expect(page.getByRole("menuitemradio", { name: "Work", exact: true })).toHaveAttribute("aria-checked", "true")
await expect(page.getByRole("menuitem", { name: "Add account", exact: true })).toBeVisible()
await page.keyboard.press("Escape")
const options = settings.getByRole("button", { name: "Work options", exact: true })
await expect(options).toHaveCSS("height", "28px")
await options.click()
await page.getByRole("menuitem", { name: "Rename", exact: true }).click()
const name = settings.getByRole("textbox", { name: "Account name", exact: true })
await expect(name).toBeFocused()
await expect(name).toHaveValue("Work")
await name.fill("Team")
await name.press("Enter")
await expect(trigger).toHaveText("Team")
expect(other.label).toBe("Personal")
await settings.getByRole("button", { name: "Team options", exact: true }).click()
await page.getByRole("menuitem", { name: "Rename", exact: true }).click()
await name.fill("Ignored")
await name.press("Escape")
await expect(trigger).toHaveText("Team")
await settings.getByRole("button", { name: "Team options", exact: true }).click()
await page.getByRole("menuitem", { name: "Rename", exact: true }).click()
await name.fill("Shared")
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
await expect(trigger).toHaveText("Shared")
await settings.getByRole("button", { name: "Shared options", exact: true }).click()
await page.getByRole("menuitem", { name: "Remove", exact: true }).click()
await expect.poll(() => removed).toEqual(["cred_work"])
})
test("providers: switching to a Zen API key does not wait for a Console workspace", async ({ page }) => {
const accounts = [
{ type: "credential", id: "cred_console", label: "Anomaly", method: "oauth" },
{ type: "credential", id: "cred_zen", label: "Zen key", method: "key" },
]
const state = { active: "cred_console" }
const { settings } = await open(page, {
provider: () =>
state.active === "cred_console"
? {
all: [
{ id: "opencode", integrationID: "opencode", name: "Anomaly / OpenCode", models: {} },
{ id: "console-google", integrationID: "opencode", name: "Anomaly / Google", models: {} },
],
connected: ["opencode", "console-google"],
default: {},
}
: {
all: [
{
id: "opencode",
name: "OpenCode Zen",
models: { paid: { id: "paid", name: "Paid", cost: { input: 3 } } },
},
],
connected: ["opencode"],
default: {},
},
integrations: () => [
{
id: "opencode",
name: "OpenCode Console",
methods: [{ id: "device", type: "oauth", label: "OpenCode Console account" }],
connections: accounts.toSorted((a, b) => Number(b.id === state.active) - Number(a.id === state.active)),
},
],
onCredentialActivate: (credentialID) => {
state.active = credentialID
},
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
const trigger = settings.getByRole("button", { name: "Manage OpenCode Console accounts", exact: true })
await expect(trigger).toHaveText("Anomaly")
await trigger.click()
const catalogReads: string[] = []
page.on("request", (request) => {
if (request.method() === "GET" && new URL(request.url()).pathname === "/api/provider")
catalogReads.push(request.url())
})
await page.getByRole("menuitemradio", { name: "Zen key", exact: true }).click()
await expect(page.getByText("OpenCode Console account switched")).toBeVisible()
// One refresh after the switch; a Console workspace poll would keep reading the catalog.
expect(catalogReads).toHaveLength(1)
})
test("providers: connecting OpenCode Go keeps the Console row in place", async ({ page, context }) => {
await context.route("https://auth.example.test/**", (route) => route.fulfill({ body: "Sign in" }))
// After the sign-in the server reloads the workspace, briefly serving only the free catalog.
const state = { authorized: false, pendingReads: 0 }
const workspace = {
all: [
{ id: "opencode", integrationID: "opencode", name: "Anomaly / OpenCode", models: {} },
{ id: "console-google", integrationID: "opencode", name: "Anomaly / Google", models: {} },
],
connected: ["opencode", "console-google"],
default: {},
}
const catalog = () => {
if (state.pendingReads > 0) {
state.pendingReads--
return { all: [{ id: "opencode", name: "OpenCode", models: {} }], connected: ["opencode"], default: {} }
}
if (!state.authorized) return workspace
return {
all: [...workspace.all, { id: "opencode-go", integrationID: "opencode-go", name: "OpenCode Go", models: {} }],
connected: [...workspace.connected, "opencode-go"],
default: {},
}
}
const { settings } = await open(page, {
provider: catalog,
integrations: () => [
{
id: "opencode",
name: "OpenCode Console",
methods: [{ id: "device", type: "oauth", label: "OpenCode Console account" }],
connections: [{ type: "credential", id: "cred_console", label: "Anomaly", method: "oauth" }],
},
{
id: "opencode-go",
name: "OpenCode Go",
methods: [{ type: "key" }],
connections: state.authorized ? [{ type: "credential", id: "cred_go", label: "Anomaly", method: "oauth" }] : [],
},
],
onIntegrationOAuth: () => ({ url: "https://auth.example.test/device?user_code=GOGO-1234" }),
onIntegrationOAuthStatus: () => {
if (!state.authorized) {
state.authorized = true
state.pendingReads = 3
}
return "complete"
},
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
const connected = settings.locator('[data-component="connected-providers-section"]')
await expect(connected.getByText("OpenCode Console", { exact: true })).toBeVisible()
await connected.evaluate((element) => {
new MutationObserver(() => {
if (!element.textContent?.includes("OpenCode Console")) element.dataset.flashed = ""
}).observe(element, { childList: true, subtree: true, characterData: true })
})
await settings
.locator(".settings-provider-row", { hasText: "OpenCode Go" })
.getByRole("button", { name: "Connect", exact: true })
.click()
const popup = page.waitForEvent("popup")
await page.getByRole("button", { name: "Continue in the browser", exact: true }).click()
await popup
await expect(page.getByText("OpenCode Go connected", { exact: true })).toBeVisible()
await expect(page.getByRole("dialog")).toHaveCount(0)
await expect(connected.getByText("OpenCode Go", { exact: true })).toBeVisible()
await expect(connected.getByText("OpenCode Console", { exact: true })).toBeVisible()
await expect(connected).not.toHaveAttribute("data-flashed")
})
test("providers: switching Console accounts keeps the list until the new workspace loads", async ({ page }) => {
const accounts = [
{ type: "credential", id: "cred_clara", label: "Clara", method: "oauth" },
{ type: "credential", id: "cred_anomaly", label: "Anomaly", method: "oauth" },
]
// The server loads the new workspace's providers a few catalog reads after the switch.
const state = { active: "cred_clara", pendingReads: 0 }
const workspace = () => accounts.find((account) => account.id === state.active)!.label
const catalog = () => {
if (state.pendingReads > 0) {
state.pendingReads--
return {
all: [{ id: "opencode", name: "OpenCode", models: { free: { id: "free", name: "Free", cost: { input: 0 } } } }],
connected: ["opencode"],
default: {},
}
}
return {
all: [
{ id: "opencode", integrationID: "opencode", name: `${workspace()} / OpenCode`, models: {} },
{ id: "console-google", integrationID: "opencode", name: `${workspace()} / Google`, models: {} },
],
connected: ["opencode", "console-google"],
default: {},
}
}
const { settings } = await open(page, {
provider: catalog,
integrations: () => [
{
id: "opencode",
name: "OpenCode Console",
methods: [{ id: "device", type: "oauth", label: "OpenCode Console account" }],
connections: accounts.toSorted((a, b) => Number(b.id === state.active) - Number(a.id === state.active)),
},
],
onCredentialActivate: (credentialID) => {
state.active = credentialID
state.pendingReads = 2
},
})
await settings.getByRole("tab", { name: "Providers", exact: true }).click()
const connected = settings.locator('[data-component="connected-providers-section"]')
const trigger = connected.getByRole("button", { name: "Manage OpenCode Console accounts", exact: true })
await expect(trigger).toHaveText("Clara")
await connected.evaluate((element) => {
new MutationObserver(() => {
if (element.textContent?.includes("No connected providers")) element.dataset.flashed = ""
}).observe(element, { childList: true, subtree: true, characterData: true })
})
await trigger.click()
await page.getByRole("menuitemradio", { name: "Anomaly", exact: true }).click()
await expect(page.getByText("OpenCode Console account switched")).toBeVisible()
await expect(trigger).toHaveText("Anomaly")
await expect(connected).not.toHaveAttribute("data-flashed")
})
test("the add server dialog keeps focus above fullscreen settings", async ({ page }) => {
await mockRemoteServer(page, { directory: "/remote/settings-demo" })
const { settings } = await open(page)
+52 -10
View File
@@ -109,7 +109,7 @@ test("terminal stacks under review by default and spans the bottom when configur
),
]
await openSession(page, { name: "SideStack", pty: {}, vcsDiff: diffs })
const { session } = await openSession(page, { name: "SideStack", pty: {}, vcsDiff: diffs })
const toggle = page.getByRole("button", { name: "Toggle review" })
const reviewPanel = page.locator("#review-panel")
const terminalPanel = page.locator("#terminal-panel")
@@ -163,13 +163,30 @@ test("terminal stacks under review by default and spans the bottom when configur
expect(Math.abs(closing.terminalBottom - stacked.terminalBottom)).toBeLessThanOrEqual(1)
expect(closing.anchor).toBeLessThanOrEqual(8)
expect(closing.terminalGap).toBeLessThanOrEqual(1)
expect(closing.reviewOverlap).toBeLessThanOrEqual(1)
await toggle.click()
await expect(reviewPanel).toBeVisible()
await expectMarked(review)
await expectTreeSentinel(page)
// Hiding the terminal mid-motion: both surfaces fill their regions and the clipped terminal keeps its size.
// Panels restored by a reload skip their entrance animation, and must still move together when the terminal hides.
await expect
.poll(() =>
page.evaluate(
(key) => JSON.parse(localStorage.getItem("opencode.window.browser.dat:tabs.panes") ?? "{}")[key],
tabKey(session.id),
),
)
.toMatchObject({ review: true, terminal: true })
await page.reload()
await expect(reviewPanel).toBeVisible()
await expect(terminal).toBeVisible()
await expectTreeSentinel(page)
await mark(terminal)
// Hiding the terminal mid-motion: both surfaces fill their regions, the review never runs under the gap, and the
// clipped terminal keeps its size.
const open = await stackGeometry(page)
await holdTransitions(page)
await page.keyboard.press("Control+Backquote")
@@ -180,6 +197,7 @@ test("terminal stacks under review by default and spans the bottom when configur
expect(hiding.terminalRegion).toBeLessThan(open.terminalRegion - 1)
expect(hiding.terminalRegion).toBeGreaterThan(1)
expect(hiding.reviewGap).toBeLessThanOrEqual(1)
expect(hiding.reviewOverlap).toBeLessThanOrEqual(1)
expect(hiding.terminalGap).toBeLessThanOrEqual(1)
expect(Math.abs(hiding.content.width - open.content.width)).toBeLessThanOrEqual(1)
expect(Math.abs(hiding.content.height - open.content.height)).toBeLessThanOrEqual(1)
@@ -293,6 +311,23 @@ for (const direction of ["ltr", "rtl"] as const) {
return actions.y + actions.height / 2 - (button.y + button.height / 2)
})
.toBe(0)
// Toggling the terminal under the review leaves the review header and the toggle in place.
const header = async () => {
const box = await page.locator('[data-slot="session-side-panel-actions"]').boundingBox()
return box && { y: box.y, height: box.height }
}
const stacked = await header()
for (const visible of [false, true]) {
await page.keyboard.press("Control+Backquote")
await expect(terminal).toBeVisible({ visible })
await expect.poll(header).toEqual(stacked)
await expect.poll(() => toggle.boundingBox()).toEqual(position)
}
await toggle.press("Enter")
await expect(toggle).toHaveAttribute("aria-expanded", "false")
await expect(toggle).toBeFocused()
@@ -321,6 +356,7 @@ async function expectTreeSentinel(page: Page) {
// Pauses each CSS transition as it starts, so a real toggle can be measured mid-motion.
function holdTransitions(page: Page) {
return page.evaluate(() => {
// SAFETY: only these two helpers write this optional global, in the declared shape.
const host = window as Window & { e2eHold?: { active: boolean } }
if (!host.e2eHold) {
@@ -341,7 +377,9 @@ function holdTransitions(page: Page) {
function releaseTransitions(page: Page) {
return page.evaluate(() => {
;(window as Window & { e2eHold?: { active: boolean } }).e2eHold!.active = false
// SAFETY: `holdTransitions` installed this global, in this shape, before any release.
const host = window as Window & { e2eHold?: { active: boolean } }
host.e2eHold!.active = false
document
.getAnimations()
.filter((item) => item instanceof CSSTransition && item.playState === "paused")
@@ -359,7 +397,7 @@ async function stackGeometry(page: Page, progress?: number) {
(item) =>
item instanceof CSSTransition && item.playState === "paused" && item.transitionProperty === "height",
)
.map((item) => ((item.effect as KeyframeEffect).target as Element).getAttribute("data-slot")),
.map((item) => (item.effect instanceof KeyframeEffect ? item.effect.target?.getAttribute("data-slot") : null)),
)
if (progress !== undefined) {
@@ -371,9 +409,10 @@ async function stackGeometry(page: Page, progress?: number) {
.getAnimations()
.filter((item): item is CSSTransition => item instanceof CSSTransition && item.playState === "paused")
const region = transitions.find(
(item) => ((item.effect as KeyframeEffect).target as Element).getAttribute("data-slot") === "session-side-region",
)
const slot = (item: CSSTransition) =>
item.effect instanceof KeyframeEffect ? item.effect.target?.getAttribute("data-slot") : null
const region = transitions.find((item) => slot(item) === "session-side-region")
if (progress !== undefined) {
const time = Number(region!.effect!.getTiming().duration) * progress
@@ -382,17 +421,20 @@ async function stackGeometry(page: Page, progress?: number) {
const box = (selector: string) => document.querySelector(selector)?.getBoundingClientRect()
const reviewRegion = box('[data-slot="session-side-region"]')!
const gap = box('[data-slot="session-side-panel-gap"]')!
const terminalRegion = box('[data-slot="session-side-terminal-region"]')!
const review = box("#review-panel")
const terminal = box("#terminal-panel")!
const content = box('[data-slot="terminal-panel-content"]')!
return {
moving: transitions.map((item) => ((item.effect as KeyframeEffect).target as Element).getAttribute("data-slot")),
moving: transitions.map(slot),
terminalRegion: terminalRegion.height,
terminalBottom: terminal.bottom,
anchor: Math.abs(terminal.top - content.top),
reviewGap: review ? Math.abs(reviewRegion.height - review.height) : 0,
// The gap paints over the review region, so any overlap hides the review's bottom corners.
reviewOverlap: reviewRegion.bottom - gap.top,
terminalGap: Math.abs(terminalRegion.height - terminal.height),
content: { width: content.width, height: content.height },
}
@@ -413,8 +455,8 @@ async function expectTerminalControlsAligned(terminal: Locator, toggle: Locator)
.poll(async () => {
const centers = await Promise.all(
[terminal.getByRole("button", { name: "New terminal", exact: true }), toggle].map((button) =>
button.locator("svg").evaluate((element) => {
const svg = element as SVGSVGElement
button.locator("svg").evaluate((svg) => {
if (!(svg instanceof SVGGraphicsElement)) return Number.NaN
const path = svg.getBBox()
return new DOMPoint(path.x + path.width / 2, path.y + path.height / 2).matrixTransform(svg.getScreenCTM()!)
@@ -57,9 +57,13 @@ test("keeps the parent title anchored when opening a subagent", async ({ page })
await page.evaluate((direction) => (document.documentElement.dir = direction), direction)
await expectSessionTitle(page, parentTitle)
// The title first renders in the loading header, which the timeline replaces once messages arrive.
// Measuring before then can read the detached heading, whose empty bounds put the start at 0.
const agents = page.getByRole("button", { name: "Used 1 Agent", exact: true })
await expect(agents).toBeVisible()
const start = await titleInlineStart(page.locator("[data-session-title]").getByRole("heading", { name: parentTitle }))
await page.getByRole("button", { name: "Used 1 Agent", exact: true }).click()
await agents.click()
await page.locator(`a[href="${sessionHref(childID)}"]`).click()
await expectSessionTitle(page, taskDescription)
+395 -32
View File
@@ -56,6 +56,71 @@ test("tab strip keeps draft tabs as wide as session tabs and navigates on mouse
await expectPath(page, sessionHref(b.id))
})
test("inactive session attention dots share the close control without marking the avatar or active tab", async ({
page,
}) => {
await mockWorkspace(page, {
name: "Tabs",
sessions: [a, b],
sessionPermissions: {
[b.id]: [
{ id: "permission-tab-b", sessionID: b.id, action: "shell", resources: ["git status"], metadata: {}, save: [] },
],
},
})
await page.goto(sessionHref(a.id))
const tabA = page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(a.id)}"])`)
const tabB = page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(b.id)}"])`)
const dot = tabB.locator('[data-slot="tab-unread-dot"]')
const close = tabB.getByRole("button", { name: "Close tab", exact: true })
await expect(tabA.locator('[data-slot="tab-title"]')).toHaveText(a.title)
await expect(tabB.locator('[data-slot="tab-title"]')).toHaveText(b.title)
await page.mouse.move(0, 0)
await expect(dot).toBeVisible()
await expect(tabB.locator('[data-slot="tab-avatar-unread-dot"]')).toBeHidden()
await expect(close).toHaveCSS("opacity", "0")
await expect(tabB.locator('[data-slot="project-avatar-unread-dot"]')).toHaveCount(0)
await expect
.poll(() =>
dot.evaluate((element) => {
const dot = element.getBoundingClientRect()
const slot = element.parentElement!.getBoundingClientRect()
return (
Math.abs(dot.x + dot.width / 2 - slot.x - slot.width / 2) +
Math.abs(dot.y + dot.height / 2 - slot.y - slot.height / 2)
)
}),
)
.toBeLessThan(1)
await tabB.hover()
await expect(dot).toBeHidden()
await expect(close).toHaveCSS("opacity", "1")
await page.mouse.move(0, 0)
await tabB.locator("[data-titlebar-tab-link]").focus()
await page.keyboard.press("Tab")
await expect(close).toBeFocused()
await expect(dot).toBeHidden()
await expect(close).toHaveCSS("opacity", "1")
await close.blur()
await expect(dot).toBeVisible()
await tabB.locator("[data-titlebar-tab-link]").click()
await expectPath(page, sessionHref(b.id))
await expect(tabB).toHaveAttribute("data-active", "true")
await expect(dot).toHaveCount(0)
await tabA.locator("[data-titlebar-tab-link]").click()
await expectPath(page, sessionHref(a.id))
await page.mouse.move(0, 0)
await expect(dot).toBeVisible()
await tabB.hover()
await close.click()
await expect(tabB).toHaveCount(0)
await expectPath(page, sessionHref(a.id))
})
test("a tab does not reopen its title editor while a rename is saving", async ({ page }) => {
await mockWorkspace(page, { name: "Tabs", sessions: [a, b] })
await page.goto(sessionHref(a.id))
@@ -97,44 +162,139 @@ test("keyboard navigation follows the visible tab order and skips unresolved tab
await expectPath(page, sessionHref(c.id))
})
test("option arrows move to the previous or next tab, and with shift to the next unread one", async ({ page }) => {
await mockWorkspace(page, {
name: "Tabs",
sessions: [a, b, c],
sessionPermissions: {
[c.id]: [
{ id: "permission-tab-c", sessionID: c.id, action: "shell", resources: ["git status"], metadata: {}, save: [] },
],
},
})
await page.goto(sessionHref(a.id))
await page.mouse.move(0, 0)
await expect(
page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(c.id)}"]) [data-slot="tab-unread-dot"]`),
).toBeVisible()
await page.keyboard.press("Alt+ArrowDown")
await expectPath(page, sessionHref(b.id))
await page.keyboard.press("Alt+ArrowUp")
await expectPath(page, sessionHref(a.id))
await page.keyboard.press("Shift+Alt+ArrowDown")
await expectPath(page, sessionHref(c.id))
})
for (const row of [
{ tabLayout: "horizontal", width: 360 },
{ tabLayout: "vertical", width: 390 },
{ tabLayout: "horizontal", width: 360, hasTouch: false, direction: "ltr" },
{ tabLayout: "vertical", width: 390, hasTouch: true, direction: "rtl" },
]) {
test(`mobile drawer exposes close controls and navigates between tabs (${row.tabLayout})`, async ({ page }) => {
await page.setViewportSize({ width: row.width, height: 720 })
await mockWorkspace(page, {
name: "Tabs",
sessions: [a, b, c],
seed: { settings: { appearance: { tabLayout: row.tabLayout } } },
test.describe(`mobile drawer (${row.tabLayout})`, () => {
test.use({ hasTouch: row.hasTouch })
test(`mobile drawer exposes close controls and navigates between tabs (${row.tabLayout})`, async ({ page }) => {
await page.setViewportSize({ width: row.width, height: 720 })
await mockWorkspace(page, {
name: "Tabs",
sessions: [a, b, c],
sessionPermissions: {
[b.id]: [
{
id: "permission-mobile-b",
sessionID: b.id,
action: "shell",
resources: ["git status"],
metadata: {},
save: [],
},
],
},
seed: { settings: { appearance: { tabLayout: row.tabLayout } } },
})
await page.goto(sessionHref(a.id))
await page.locator("html").evaluate((element, direction) => element.setAttribute("dir", direction), row.direction)
await page.getByRole("button", { name: "Tabs", exact: true }).click()
const drawer = page.locator('[data-slot="mobile-tabs-drawer"]')
const tabA = drawer.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(a.id)}"])`)
const tabB = drawer.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(b.id)}"])`)
await expect(tabA).toHaveAttribute("data-active", "true")
await expect(tabA.locator('[data-slot="tab-close"]')).toBeVisible()
await expect(tabB.locator('[data-slot="tab-close"]')).toBeVisible()
await expect(tabB.locator('[data-slot="tab-unread-dot"]')).toBeVisible()
await expect(tabB.locator('[data-slot="tab-unread-slot"]')).toHaveCSS("width", "20px")
await expect(tabB.locator('[data-slot="tab-unread-slot"]')).toHaveCSS("height", "20px")
await expect
.poll(() =>
tabB.evaluate((element) => {
const dot = element.querySelector('[data-slot="tab-unread-slot"]')!.getBoundingClientRect()
const close = element.querySelector('[data-slot="tab-close"]')!.getBoundingClientRect()
return dot.right <= close.left || dot.left >= close.right
}),
)
.toBe(true)
await expect(tabB.locator('[data-slot="tab-avatar-unread-dot"]')).toBeHidden()
await expect(tabB.getByRole("button", { name: "Close tab", exact: true })).toHaveCSS("opacity", "1")
await expect(page.locator('[data-slot="vertical-tabs-sidebar"]')).toHaveCount(0)
await tabB.locator(`a[href="${sessionHref(b.id)}"]`).click()
await expectPath(page, sessionHref(b.id))
await expect(page.getByRole("dialog", { name: "Tabs", exact: true })).toBeHidden()
if (row.tabLayout !== "vertical") return
await page.setViewportSize({ width: 1280, height: 720 })
await expect(
page
.locator('[data-slot="vertical-tabs-sidebar"]')
.locator(`[data-titlebar-tab-link][href="${sessionHref(b.id)}"]`),
).toBeVisible()
await expect(page.locator('[data-slot="titlebar-tabs"]')).toHaveCount(0)
})
await page.goto(sessionHref(a.id))
await page.getByRole("button", { name: "Tabs", exact: true }).click()
const drawer = page.locator('[data-slot="mobile-tabs-drawer"]')
const tabA = drawer.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(a.id)}"])`)
const tabB = drawer.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(b.id)}"])`)
await expect(tabA).toHaveAttribute("data-active", "true")
await expect(tabA.locator('[data-slot="tab-close"]')).toBeVisible()
await expect(tabB.locator('[data-slot="tab-close"]')).toBeVisible()
await expect(page.locator('[data-slot="vertical-tabs-sidebar"]')).toHaveCount(0)
await tabB.locator(`a[href="${sessionHref(b.id)}"]`).click()
await expectPath(page, sessionHref(b.id))
await expect(page.getByRole("dialog", { name: "Tabs", exact: true })).toBeHidden()
if (row.tabLayout !== "vertical") return
await page.setViewportSize({ width: 1280, height: 720 })
await expect(
page
.locator('[data-slot="vertical-tabs-sidebar"]')
.locator(`[data-titlebar-tab-link][href="${sessionHref(b.id)}"]`),
).toBeVisible()
await expect(page.locator('[data-slot="titlebar-tabs"]')).toHaveCount(0)
})
}
test("icon-only inactive tabs retain their avatar and attention badge instead of showing a close overlay", async ({
page,
}) => {
await mockWorkspace(page, {
name: "CompactTabs",
sessions: [
a,
b,
...Array.from({ length: 30 }, (_, index) => ({ id: `ses_compact_${index}`, title: `Compact ${index}` })),
],
sessionPermissions: {
[b.id]: [
{
id: "permission-compact-b",
sessionID: b.id,
action: "shell",
resources: ["git status"],
metadata: {},
save: [],
},
],
},
})
await page.goto(sessionHref(a.id))
const tabB = page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(b.id)}"])`)
await expect(tabB.locator('[data-slot="tab-title"]')).toBeHidden()
await expect(tabB.locator('[data-component="project-avatar-v2"]')).toBeVisible()
await expect(tabB.locator('[data-slot="tab-avatar-unread-dot"]')).toBeVisible()
await expect(tabB.locator('[data-slot="tab-avatar-unread-dot"]')).toHaveCSS("width", "6px")
await expect(tabB.locator('[data-slot="tab-avatar-unread-dot"]')).toHaveCSS("height", "6px")
await expect(tabB.locator('[data-slot="tab-close"]')).toBeHidden()
await tabB.hover()
await expect(tabB.locator('[data-slot="tab-close"]')).toBeHidden()
await tabB.locator("[data-titlebar-tab-link]").click()
await expectPath(page, sessionHref(b.id))
await expect(tabB.locator('[data-slot="tab-avatar-unread-dot"]')).toHaveCount(0)
})
test("vertical tabs resize, scroll, show shortcut hints, and navigate", async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 480 })
const directory = "C:/OpenCode/Tabs"
@@ -202,6 +362,145 @@ test("vertical tabs resize, scroll, show shortcut hints, and navigate", async ({
await expectPath(page, sessionHref(b.id))
})
test("vertical tab gaps hover and select the nearest row", async ({ page }) => {
await mockWorkspace(page, {
name: "Tabs",
sessions: [a, b, c],
seed: { settings: { appearance: { tabLayout: "vertical" } } },
})
await page.goto(sessionHref(a.id))
const sidebar = page.locator('[data-slot="vertical-tabs-sidebar"]')
const rows = sidebar.locator("[data-titlebar-tab]")
const tabB = rows.filter({ has: page.locator(`a[href="${sessionHref(b.id)}"]`) })
const tabC = rows.filter({ has: page.locator(`a[href="${sessionHref(c.id)}"]`) })
await expect(rows.locator("[data-titlebar-tab-title]")).toHaveText([a.title, b.title, c.title])
const upper = await tabB.boundingBox()
const lower = await tabC.boundingBox()
if (!upper || !lower) throw new Error("vertical tabs have no bounding boxes")
expect(lower.y - upper.y - upper.height).toBe(4)
const middle = upper.y + upper.height + 2
// The two halves belong to their nearest row; an exact tie belongs to the next row.
for (const [offset, id] of [
[-1, b.id],
[0, c.id],
] as const) {
await page.mouse.move(upper.x + upper.width / 2, middle + offset)
await expect(sidebar.locator("[data-titlebar-tab]:hover [data-titlebar-tab-link]")).toHaveAttribute(
"href",
sessionHref(id),
)
}
await page.mouse.click(upper.x + upper.width / 2, middle + 1)
await expectPath(page, sessionHref(c.id))
await page.mouse.move(upper.x + upper.width / 2, middle - 1)
await page.mouse.down()
await page.mouse.move(upper.x + upper.width / 2, lower.y + lower.height - 2, { steps: 8 })
await page.mouse.up()
await expect(rows.locator("[data-titlebar-tab-title]")).toHaveText([a.title, c.title, b.title])
await tabB.getByRole("button", { name: "Close tab", exact: true }).click()
await expect(rows.locator("[data-titlebar-tab-title]")).toHaveText([a.title, c.title])
await expectPath(page, sessionHref(c.id))
const list = await sidebar.locator("[data-titlebar-tab-list]").boundingBox()
if (!list) throw new Error("vertical tab list has no bounding box")
for (const [x, y] of [
[list.x + list.width / 2, list.y - 1],
[list.x + list.width / 2, list.y + list.height + 1],
[list.x - 1, list.y + list.height / 2],
[list.x + list.width + 1, list.y + list.height / 2],
]) {
await page.mouse.move(x, y)
await expect(sidebar.locator("[data-titlebar-tab]:hover")).toHaveCount(0)
}
})
test("tab preview opens cold, switches immediately between tabs, and closes outside the strip", async ({ page }) => {
const d = { id: "ses_tab_d", title: "Library" }
await mockWorkspace(page, {
name: "Tabs",
sessions: [a, b, c, d],
seed: { settings: { appearance: { tabLayout: "vertical" } } },
})
await page.goto(sessionHref(a.id))
const sidebar = page.locator('[data-slot="vertical-tabs-sidebar"]')
const rows = sidebar.locator("[data-titlebar-tab]")
const tabB = rows.filter({ has: page.locator(`a[href="${sessionHref(b.id)}"]`) })
const tabC = rows.filter({ has: page.locator(`a[href="${sessionHref(c.id)}"]`) })
const preview = page.locator('[data-component="session-tab-popover"]')
await expect(rows.locator("[data-titlebar-tab-title]")).toHaveText([a.title, b.title, c.title, d.title])
// Until it is paused the installed clock follows real time, and it starts slightly ahead of the runner's wall clock,
// so `pauseAt(new Date())` can name an instant the page has already passed. Pause at a fixed offset from an explicit
// install time instead; the offset only has to outlast the real time between the two calls.
const start = Date.now()
await page.clock.install({ time: start })
await page.clock.pauseAt(start + 10_000)
await tabB.hover()
await page.clock.runFor(700)
await expect(preview).toHaveCount(0)
await page.clock.runFor(50)
await expect(preview).toContainText(b.title)
await page.clock.runFor(10_000)
await expect(preview).toContainText(b.title)
const box = await tabB.boundingBox()
if (!box) throw new Error("vertical tab has no bounding box")
await page.mouse.move(box.x + box.width / 2, box.y + box.height + 1)
await page.clock.runFor(1000)
await expect(preview).toContainText(b.title)
await tabB.getByRole("button", { name: "Close tab", exact: true }).hover()
await page.clock.runFor(1000)
await expect(preview).toContainText(b.title)
await tabC.hover({ position: { x: box.width - 1, y: box.height / 2 } })
await page.clock.runFor(20)
await expect(preview).toHaveCount(1)
await expect(preview).toContainText(c.title)
await expect(preview).toHaveCSS("pointer-events", "none")
await rows.filter({ has: page.locator(`a[href="${sessionHref(d.id)}"]`) }).hover()
await page.clock.runFor(20)
await expect(preview).toHaveCount(1)
await expect(preview).toContainText(d.title)
const card = await preview.boundingBox()
if (!card) throw new Error("tab preview has no bounding box")
// The card is informational: entering its painted area leaves the tab strip.
await page.mouse.move(card.x + card.width / 2, card.y + card.height / 2)
await page.clock.runFor(20)
await expect(preview).toHaveCount(0)
await tabB.hover()
await page.clock.runFor(800)
await expect(preview).toContainText(b.title)
await page.mouse.down()
await page.mouse.move(box.x + box.width / 2, box.y + box.height + 20, { steps: 8 })
await page.clock.runFor(1000)
await expect(preview).toHaveCount(0)
await page.mouse.up()
// Removing an open tab must not leave the shared preview state permanently warm.
await tabB.hover()
await page.clock.runFor(800)
await expect(preview).toContainText(b.title)
await tabB.getByRole("button", { name: "Close tab", exact: true }).click()
await page.mouse.move(900, 500)
await page.clock.runFor(600)
await tabC.hover()
await page.clock.runFor(700)
await expect(preview).toHaveCount(0)
await page.clock.runFor(50)
await expect(preview).toContainText(c.title)
})
test("closing the active server's last tab opens the remaining server tab", async ({ page }) => {
const sessionA = session({ id: "ses_server_a", directory: "C:/server-a", title: "Server A session" })
const sessionB = session({ id: "ses_server_b", directory: "/home/server-b", title: "Server B session" })
@@ -533,6 +832,70 @@ test("each session tab shows its own file tab after a switch to a session in ano
}
})
test("tab shortcuts cycle side-panel tabs when the side panel is focused with multiple tabs", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 })
const directory = "C:/OpenCode/SidePanelTabs"
const alpha = { id: "ses_side_tabs_alpha", title: "Side tabs alpha" }
const beta = { id: "ses_side_tabs_beta", title: "Side tabs beta" }
await openSession(page, {
name: "SidePanelTabs",
sessions: [alpha, beta],
fileList: (path) => (path ? [] : ["README.md"].map((file) => fileNode(directory, file))),
fileContent: (path) => ({ type: "text", content: `contents:${path}` }),
seed: { panes: { [alpha.id]: { review: true }, [beta.id]: { review: true } } },
})
const panel = page.locator("#review-panel")
const reviewTab = panel.getByRole("tab", { name: "Review", exact: true })
const fileTab = panel.getByRole("tab", { name: "README.md", exact: true })
const composer = page.getByRole("textbox", { name: "Prompt", exact: true })
await panel.getByRole("button", { name: "Open file" }).click()
await panel.getByRole("button", { name: "README.md", exact: true }).click()
await expect(fileTab).toHaveAttribute("aria-selected", "true")
await expect(panel.getByText("contents:README.md", { exact: true })).toBeVisible()
// Focus outside the side panel still cycles session tabs even when multiple side-panel tabs are open.
await composer.click()
await page.keyboard.press("Control+Tab")
await expectPath(page, sessionHref(beta.id))
await page.keyboard.press("ControlOrMeta+Alt+ArrowLeft")
await expectPath(page, sessionHref(alpha.id))
await expect(fileTab).toHaveAttribute("aria-selected", "true")
// Focus inside the side panel cycles the drawn side-panel tabs and keeps focus inside the side panel.
await panel.getByText("contents:README.md", { exact: true }).click()
await page.keyboard.press("Control+Tab")
await expect(reviewTab).toHaveAttribute("aria-selected", "true")
await expectPath(page, sessionHref(alpha.id))
await page.keyboard.press("Control+Tab")
await expect(fileTab).toHaveAttribute("aria-selected", "true")
await expectPath(page, sessionHref(alpha.id))
await page.keyboard.press("Control+Shift+Tab")
await expect(reviewTab).toHaveAttribute("aria-selected", "true")
await expectPath(page, sessionHref(alpha.id))
await page.keyboard.press("ControlOrMeta+Alt+ArrowRight")
await expect(fileTab).toHaveAttribute("aria-selected", "true")
await expectPath(page, sessionHref(alpha.id))
await page.keyboard.press("ControlOrMeta+Alt+ArrowLeft")
await expect(reviewTab).toHaveAttribute("aria-selected", "true")
await expectPath(page, sessionHref(alpha.id))
// Once only one side-panel tab remains, the shortcut returns to cycling session tabs.
await page.keyboard.press("Control+Tab")
await expect(fileTab).toHaveAttribute("aria-selected", "true")
await page.keyboard.press("ControlOrMeta+w")
await expect(fileTab).toHaveCount(0)
await expect(reviewTab).toHaveAttribute("aria-selected", "true")
await reviewTab.click()
await page.keyboard.press("Control+Tab")
await expectPath(page, sessionHref(beta.id))
})
// Windows has no native menu bar: the titlebar menu owns Paste, which only the desktop edit action can perform.
test("the Windows titlebar menu pastes through the desktop edit action", async ({ page }) => {
await mockWorkspace(page, { name: "WindowsMenu", sessions: [] })
@@ -151,6 +151,23 @@ test("focuses a terminal created from the new-terminal button", async ({ page })
await expect.poll(() => active.evaluate((element) => element.contains(document.activeElement))).toBe(true)
})
test("focuses the terminal opened from the command palette", async ({ page }) => {
const { editor } = await openSession(page, workspace)
const terminal = page.locator('[data-component="terminal"]')
await editor.click()
await page.keyboard.press("ControlOrMeta+Shift+P")
const palette = page.getByRole("dialog")
const search = palette.getByRole("textbox")
await expect(search).toBeFocused()
await search.fill("Toggle terminal")
await expect(palette.getByRole("option", { name: /^Toggle terminal/ })).toHaveAttribute("aria-selected", "true")
await search.press("Enter")
await expect(palette).toHaveCount(0)
await expect(terminal.locator("textarea")).toHaveCount(1)
await expect.poll(() => terminal.evaluate((element) => element.contains(document.activeElement))).toBe(true)
})
test("closing the last restored terminal does not create a hidden replacement", async ({ page }) => {
const cached = { id: "pty_cached", title: "Terminal 1" }
@@ -30,7 +30,7 @@ for (const width of [1440, 390]) {
const spacer = content.querySelector('[data-timeline-row="bottom-spacer"]')
;(window as Window & { __coldReveal?: Reveal }).__coldReveal = {
window.__coldReveal = {
pending: content.querySelectorAll('[data-component="markdown"]:not([data-markdown-ready])').length,
clipped: [...content.querySelectorAll<HTMLElement>("[data-timeline-key]")].flatMap((row) =>
(row.firstElementChild?.getBoundingClientRect().height ?? 0) > row.getBoundingClientRect().height + 1
@@ -55,7 +55,7 @@ for (const width of [1440, 390]) {
await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "hidden")
release.resolve()
await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible")
const reveal = await page.evaluate(() => (window as Window & { __coldReveal?: Reveal }).__coldReveal)
const reveal = await page.evaluate(() => window.__coldReveal)
expect(reveal).toMatchObject({ pending: 0, clipped: [], tables: 1, codeBlocks: 4 })
expect(Math.abs(reveal?.bottomError ?? Infinity)).toBeLessThanOrEqual(1)
// The gap above the composer is part of the tail.
@@ -274,7 +274,23 @@ test("loads the transcript code font before opening rich history", async ({ page
await page.goto(sessionHref(fixture.sourceID))
await expect(page.getByText("A transcript with no code", { exact: true })).toBeVisible()
expect((await font).ok()).toBe(true)
await expect.poll(() => page.evaluate(() => document.fonts.check('440 13px "IBM Plex Mono"'))).toBe(true)
// Chromium recreates every @font-face as "unloaded", keeping its downloaded file, whenever a lazily loaded
// stylesheet with @layer rules activates ahead of one already applied, so the preloaded face's status alone is
// not stable. Once fonts settle, the first layout of new code must take that file at once, which marks the
// current face loaded; a face that still has to fetch its file reports "loading" here instead.
expect(
await page.evaluate(async () => {
await document.fonts.ready
const code = document.body.appendChild(document.createElement("code"))
code.style.font = "440 13px var(--font-family-mono)"
code.textContent = "code"
code.getBoundingClientRect()
const loaded = document.fonts.check('440 13px "IBM Plex Mono"')
code.remove()
return loaded
}),
).toBe(true)
})
test("waits for the requested session's history before constructing its cold timeline", async ({ page }) => {
@@ -464,6 +480,13 @@ async function expectAtTail(page: Page, lastUserID: string) {
type TabPaint = { first?: { last: boolean; bottomError?: number }; settled: boolean; removed: number; stop(): void }
declare global {
interface Window {
__coldReveal?: Reveal
__tabPaint?: TabPaint
}
}
// Samples painted frames of the timeline showing `sessionID`: the first frame that shows any of its messages, and
// every node of the first settled frame (at the tail, Markdown rendered) that is later removed.
async function sampleTabPaint(page: Page, sessionID: string) {
@@ -482,7 +505,7 @@ async function sampleTabPaint(page: Page, sessionID: string) {
},
}
;(window as Window & { __tabPaint?: TabPaint }).__tabPaint = state
window.__tabPaint = state
new MutationObserver((records) => {
if (!state.settled || !running) return
records.forEach((record) =>
@@ -520,10 +543,11 @@ async function sampleTabPaint(page: Page, sessionID: string) {
)
}
const visible = [...root.querySelectorAll<HTMLElement>("[data-message-id]")]
.filter(inView)
.map((element) => element.dataset.messageId!)
.filter((id) => destination.has(id))
const visible = [...root.querySelectorAll<HTMLElement>("[data-message-id]")].flatMap((element) => {
const id = element.dataset.messageId
return id && inView(element) && destination.has(id) ? [id] : []
})
const spacer = root.querySelector('[data-timeline-row="bottom-spacer"]')?.getBoundingClientRect()
const bottomError = spacer ? spacer.bottom - view.bottom : undefined
@@ -556,20 +580,20 @@ async function sampleTabPaint(page: Page, sessionID: string) {
last: history.findLast((message) => message.type === "user")!.id,
},
)
const read = () => page.evaluate(() => (window as Window & { __tabPaint?: TabPaint }).__tabPaint!.first)
const read = () => page.evaluate(() => window.__tabPaint!.first)
return {
async firstPaint() {
await expect.poll(read).toBeDefined()
await expect
.poll(() => page.evaluate(() => (window as Window & { __tabPaint?: TabPaint }).__tabPaint!.settled))
.poll(() => page.evaluate(() => window.__tabPaint!.settled))
.toBe(true)
return (await read())!
},
stop: () =>
page.evaluate(() => {
const state = (window as Window & { __tabPaint?: TabPaint }).__tabPaint!
const state = window.__tabPaint!
state.stop()
return state.removed
@@ -3,6 +3,7 @@ import { timelinePresets } from "@opencode/session-ui/timeline/detail"
import { createTwoFilesPatch } from "diff"
import {
assistantMessage,
historyMessages,
partUpdated,
renderedPartID,
sessionID,
@@ -12,6 +13,7 @@ import {
toolPart,
userMessage,
userText,
validateTimelineMessages,
waitForVisualSettle,
} from "../utils/timeline"
import {
@@ -459,12 +461,22 @@ for (const outline of [
for (const failed of [false, true]) {
test(`keeps a submitted prompt in place until Working shows${failed ? " after an error" : ""}`, async ({ page }) => {
await setupTimeline(page, {
seedHistory: true,
messages: [
userMessage(),
...(failed
? [{ ...assistantMessage([]), error: { type: "provider.error", message: "Previous request failed" } }]
: []),
sessionMessages: [
...validateTimelineMessages([
...historyMessages(18),
userMessage(),
...(failed
? [{ ...assistantMessage([]), error: { type: "provider.error", message: "Previous request failed" } }]
: []),
]),
// The previous execution ended at an idle marker, so the submitted prompt starts a turn instead of
// waiting as a steer behind that one.
{
id: "msg_1002_timeline_idle",
type: "idle",
outcome: failed ? "failed" : "succeeded",
time: { created: 1700000003000 },
},
],
})
const working = page.locator('[data-component="session-working"]')
@@ -494,7 +506,7 @@ for (const failed of [false, true]) {
// Records the prompt row in every frame from submission until Working has shown.
const observation = await page.evaluateHandle((text) => {
const frames: { prompt?: number; working: boolean }[] = []
const frames: { prompt: number | undefined; working: boolean }[] = []
let frame = 0
const sample = () => {
@@ -503,7 +515,7 @@ for (const failed of [false, true]) {
)
frames.push({
...(prompt ? { prompt: prompt.getBoundingClientRect().y } : {}),
prompt: prompt?.getBoundingClientRect().y,
working: !!document.querySelector('[data-component="session-working"]'),
})
frame = requestAnimationFrame(sample)
+15 -4
View File
@@ -68,8 +68,7 @@ const upgraded = { storage: { "highlights.v1": { version: "1.9.1" } } }
test("What's New shows the highlights since the version seen, pages to Get started, and is seen once shown", async ({
page,
}) => {
const requests = await serveChangelog(page)
await start(page, upgraded)
const requests = await startUpgraded(page)
const dialog = page.getByRole("dialog")
const title = dialog.getByRole("heading", { level: 1 })
const next = dialog.getByRole("button", { name: "Next", exact: true })
@@ -102,8 +101,7 @@ test("What's New shows the highlights since the version seen, pages to Get start
})
test("Don't show these in the future turns release notes off and closes What's New", async ({ page }) => {
await serveChangelog(page)
await start(page, upgraded)
await startUpgraded(page)
const dialog = page.getByRole("dialog")
await expect(dialog.getByRole("heading", { level: 1 })).toHaveText("Split panes")
await dialog.getByRole("button", { name: "Don't show these in the future", exact: true }).click()
@@ -222,6 +220,19 @@ async function start(page: Page, seed: SeedInput) {
await expectAppVisible(page.getByRole("button", { name: "Settings", exact: true }))
}
/**
* Starts as a user who last saw 1.9.1 and serves the changelog only once Home renders. What's New is a modal that hides
* Home from assistive technology, so opening it first would hide the Settings button `start` waits for.
*/
async function startUpgraded(page: Page) {
const held = Promise.withResolvers<void>()
const requests = await serveChangelog(page, changelog, held.promise)
await start(page, upgraded)
held.resolve()
return requests
}
function stored(page: Page, key: string) {
return page.evaluate((name) => localStorage.getItem(name), key).then((raw) => JSON.parse(raw ?? "null"))
}
+13
View File
@@ -125,6 +125,19 @@ const Group = HttpApiGroup.make("mock")
error: MockNotFound.pipe(HttpApiSchema.status(404)),
}),
)
.add(
HttpApiEndpoint.post("credentialActivate", "/api/credential/:credentialID/activate", {
params: { credentialID: Schema.String },
success: NoContent,
}),
)
.add(
HttpApiEndpoint.patch("credentialUpdate", "/api/credential/:credentialID", {
params: { credentialID: Schema.String },
payload: JsonPayload,
success: NoContent,
}),
)
.add(
HttpApiEndpoint.delete("credentialRemove", "/api/credential/:credentialID", {
params: { credentialID: Schema.String },
+57 -11
View File
@@ -44,7 +44,11 @@ export type MockFileContent =
export interface MockServerConfig {
server?: string
provider: Resolvable<MockProviderCatalog>
integrations?: unknown[]
integrations?: Resolvable<unknown[]>
// Runs on POST /api/credential/:id/activate; the fixture swaps its integrations and catalog to the new account.
onCredentialActivate?: (credentialID: string) => void
// Runs on PATCH /api/credential/:id with the request body; the fixture applies the new label.
onCredentialUpdate?: (credentialID: string, body: { label?: string }) => void
onConnectKey?: (input: { integrationID: string; body: unknown }) => void
// Terminal shells the settings offer (`/api/config/shell`).
shells?: unknown[]
@@ -103,6 +107,8 @@ export interface MockServerConfig {
// Starts an OAuth attempt (POST .../connect/oauth) and returns its authorization URL; the attempt then stays pending.
// Without it, OAuth connects answer 501 MockUnsupported.
onIntegrationOAuth?: (input: { integrationID: string; directory: string; body: unknown }) => { url: string }
// Answers status polls for an OAuth attempt; without it every attempt stays pending.
onIntegrationOAuthStatus?: (attemptID: string) => "pending" | "complete"
plugins?: Resolvable<unknown[]>
skills?: Resolvable<unknown[]>
// Replaces the `/api/worktree` inventory, which defaults to the directory plus project sandboxes.
@@ -470,6 +476,21 @@ export async function mockOpenCodeServer(page: Page, config: MockServerConfig) {
return { server, pty: transport.pty, push }
}
// Answers every Location-scoped request for `directory` as the server does once that folder is deleted.
export function mockMissingLocation(page: Page, directory: string) {
return page.route(
(url) => url.pathname.startsWith("/api/") && url.searchParams.get("location[directory]") === directory,
(route) =>
route.fulfill({
status: 404,
// SAFETY: the server's wire body for a missing Location, which the client decodes into its own error.
// oxlint-disable-next-line anti-slop-effect/no-manual-tagged-construction -- see SAFETY above
json: { _tag: "LocationNotFoundError", location: { directory }, message: `Location not found: ${directory}` },
headers: { "access-control-allow-origin": "*" },
}),
)
}
// Mocks several servers on one page. Each origin gets its own handler and its own SSE transport for events.
export async function mockServers(page: Page, servers: Record<string, Omit<MockServerConfig, "server" | "events">>) {
return Object.fromEntries(
@@ -758,9 +779,15 @@ function mockHandlers(
Effect.gen(function* () {
const path = decodeURIComponent(new URL(ctx.request.url, "http://localhost").pathname.slice(13))
const value = yield* Effect.promise(() => Promise.resolve(config.fileContent?.(path)))
const content = Predicate.isString(value) ? value : (value?.content ?? "")
return HttpServerResponse.uint8Array(new TextEncoder().encode(content))
if (Predicate.isString(value)) return HttpServerResponse.uint8Array(new TextEncoder().encode(value))
// Like the server, stream base64 content as the bytes it encodes.
return HttpServerResponse.uint8Array(
value?.encoding === "base64"
? Buffer.from(value.content, "base64")
: new TextEncoder().encode(value?.content ?? ""),
)
}),
)
// Raw, so a hook's answer can replace the status and body.
@@ -843,19 +870,20 @@ function mockHandlers(
model: () => Effect.succeed({ location: location(config), data: currentModels(resolve(config.provider)) }),
modelDefault: () =>
Effect.succeed({ location: location(config), data: currentDefaultModel(resolve(config.provider)) }),
integrationList: () => Effect.succeed({ location: location(config), data: config.integrations ?? [] }),
integrationList: () =>
Effect.sync(() => ({ location: location(config), data: resolve(config.integrations ?? []) })),
integrationGet: (ctx) =>
Effect.succeed({
Effect.sync(() => ({
location: location(config),
data: config.integrations
?.filter(Predicate.isObject)
data: resolve(config.integrations ?? [])
.filter(Predicate.isObject)
.find((integration) => integration.id === ctx.params.integrationID) ?? {
id: ctx.params.integrationID,
name: ctx.params.integrationID,
methods: [{ type: "key", label: "API key" }],
connections: [],
},
}),
})),
integrationConnect: (ctx) =>
Effect.sync(() => config.onConnectKey?.({ integrationID: ctx.params.integrationID, body: ctx.payload })).pipe(
Effect.andThen(noContent),
@@ -892,9 +920,18 @@ function mockHandlers(
return Effect.succeed({
location: location(config, requestDirectory(config, ctx.request)),
data: { status: "pending", time: { created, expires: created + 600_000 } },
data: {
status: config.onIntegrationOAuthStatus?.(ctx.params.attemptID) ?? "pending",
time: { created, expires: created + 600_000 },
},
})
}),
credentialActivate: (ctx) =>
Effect.sync(() => config.onCredentialActivate?.(ctx.params.credentialID)).pipe(Effect.andThen(noContent)),
credentialUpdate: (ctx) =>
Effect.sync(() => config.onCredentialUpdate?.(ctx.params.credentialID, ctx.payload)).pipe(
Effect.andThen(noContent),
),
credentialRemove: () => noContent,
command: (ctx) =>
Effect.sync(() => ({
@@ -1398,6 +1435,8 @@ function currentProviders(catalog: MockProviderCatalog) {
.map((provider) => ({
id: provider.id,
name: provider.name,
canonical: provider.canonical,
integrationID: provider.integrationID,
package: provider.id,
activation: connected.has(provider.id) ? "enabled" : "auto",
}))
@@ -1471,7 +1510,7 @@ export function currentSession(session: MockSession, fallbackDirectory?: string)
parentID: session.parentID,
projectID: session.projectID ?? "project",
agent: session.agent ?? "build",
model: session.model ?? { id: "mock-model", providerID: "mock-provider" },
model: session.model,
cost: session.cost ?? 0,
tokens: session.tokens ?? { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
...decodeSessionOutcome(session),
@@ -1529,7 +1568,14 @@ const decodePromptPayload = Schema.decodeUnknownOption(
}),
)
const decodeProvider = Schema.decodeUnknownOption(Schema.Struct({ id: Schema.String, name: Schema.String }))
const decodeProvider = Schema.decodeUnknownOption(
Schema.Struct({
id: Schema.String,
name: Schema.String,
canonical: lenient(Schema.String),
integrationID: lenient(Schema.String),
}),
)
const decodeModelProvider = Schema.decodeUnknownOption(
Schema.Struct({ id: Schema.String, models: Schema.Record(Schema.String, Schema.Unknown) }),
+65
View File
@@ -0,0 +1,65 @@
import { stat } from "node:fs/promises"
import path from "node:path"
import { parseArgs } from "node:util"
// Serves the e2e build with vite preview's routing rules. vite preview checks the case of every requested
// path with a synchronous directory read on case-insensitive file systems (Windows, macOS), and the
// 3000-file _assets directory makes that the bottleneck for every page load across all workers.
const options = parseArgs({ options: { host: { type: "string" }, port: { type: "string" } } }).values
const dist = path.resolve(import.meta.dirname, "../../dist")
// Sent as text like vite's index.html middleware, so a media Range request that falls back gets a plain 200.
const index = await Bun.file(path.join(dist, "index.html")).text()
Bun.serve({
hostname: options.host,
port: Number(options.port),
async fetch(request) {
const pathname = decode(new URL(request.url).pathname)
if (pathname === undefined) return new Response(null, { status: 404 })
const target = path.resolve(dist, `.${pathname}`)
// Like vite's existsSync, a name the file system rejects (too long, NUL) is treated as missing.
const stats = target.startsWith(dist + path.sep) ? await stat(target).catch(() => undefined) : undefined
if (stats?.isFile()) {
const file = Bun.file(target)
return new Response(file, {
// Bun names .aac audio/x-aac, and only keeps the type on HEAD responses when it is set explicitly.
headers: { "content-type": path.extname(target) === ".aac" ? "audio/aac" : file.type },
})
}
if (fallback(request, pathname))
return new Response(index, { headers: { "content-type": "text/html;charset=utf-8" } })
return new Response(null, { status: 404 })
},
})
function decode(pathname: string) {
try {
return decodeURIComponent(pathname)
} catch {
return undefined
}
}
// Mirrors vite's htmlFallbackMiddleware: only page loads get index.html, so a missing script or a fetch
// asking for JSON still sees a 404.
function fallback(request: Request, pathname: string) {
if (request.method !== "GET" && request.method !== "HEAD") return false
if (pathname === "/favicon.ico") return false
// vite's index.html middleware never answers a script load with the page, so a missing chunk stays a 404.
if (request.headers.get("sec-fetch-dest") === "script") return false
const accept = request.headers.get("accept")
return !accept || accept.includes("text/html") || accept.includes("*/*")
}
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode/app",
"version": "2.0.27",
"version": "2.0.30",
"description": "",
"type": "module",
"exports": {
@@ -19,9 +19,9 @@
"build": "vite build",
"serve": "vite preview",
"test": "bun run test:unit && bun run test:browser",
"test:unit": "bun test --conditions=solid --only-failures --preload ./happydom.ts ./src",
"test:browser": "bun test --conditions=browser --preload ./happydom.ts ./test-browser",
"test:unit:watch": "bun test --conditions=solid --watch --preload ./happydom.ts ./src",
"test:unit": "bun test --conditions=solid --only-failures --isolate --preload ./happydom.ts ./src",
"test:browser": "bun test --conditions=browser --isolate --preload ./happydom.ts ./test-browser",
"test:unit:watch": "bun test --conditions=solid --watch --isolate --preload ./happydom.ts ./src",
"test:e2e": "playwright test",
"test:e2e:built": "PLAYWRIGHT_BUILD=1 playwright test",
"test:e2e:local": "playwright test",
+20 -3
View File
@@ -10,7 +10,7 @@ if (url.protocol !== "http:") throw new Error("E2E fixtures require an http:// a
const built = !!process.env.CI || process.env.PLAYWRIGHT_BUILD === "1"
// Production connects to its own origin, so fixture URLs must match the preview server.
// Production connects to its own origin, so fixture URLs must match the static server.
if (built) {
process.env.PLAYWRIGHT_SERVER_HOST = url.hostname
process.env.PLAYWRIGHT_SERVER_PORT = url.port || "80"
@@ -21,11 +21,13 @@ const serverHost = process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"
const serverPort = process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"
const command = built
? `bun run build && bun run serve -- --host 127.0.0.1 --port ${port} --strictPort`
? `bun run build && bun e2e/utils/serve.ts --host 127.0.0.1 --port ${port}`
: `bun run dev -- --host 127.0.0.1 --port ${port} --strictPort`
const workers = Number(process.env.PLAYWRIGHT_WORKERS ?? (process.env.CI ? 5 : 0)) || undefined
const touchScroll = /mobile-timeline-scroll\.spec\.ts/
export default defineConfig({
testDir: "./e2e",
testIgnore: [
@@ -59,12 +61,27 @@ export default defineConfig({
baseURL,
trace: "on-first-retry",
screenshot: "only-on-failure",
video: "retain-on-failure",
// CI retries failures, so the retry records the video; local runs have no retries.
video: process.env.CI ? "on-first-retry" : "retain-on-failure",
// The PWA worker precaches the whole build in every test; e2e/service-worker covers it.
serviceWorkers: "block",
},
// The touch-scroll project exists only for scheduling: in the chromium project, mobile-timeline-scroll
// is one long serial group that ends up running alone on a single worker. Projects queue in
// declaration order, so this one runs the file's tests after every chromium group, spread across all
// workers. `--project chromium`, UI mode and the VS Code extension's default first-project selection
// therefore skip the file.
projects: [
{
name: "chromium",
use: { ...devices["Desktop Chrome"] },
grepInvert: touchScroll,
},
{
name: "chromium-touch-scroll",
use: { ...devices["Desktop Chrome"] },
grep: touchScroll,
fullyParallel: true,
},
],
})
Loaded 100 of 1092 files, more files were not shown because too many files have changed in this diff. Show more