From 62add15f4cc420a82593f65765b07f686b93c06b Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:04:11 +0000 Subject: [PATCH 1/6] Archive the kernel holo app/ builds (blake3:f1c50fb2) Built and proved by the locked SDK in the kernel pin workflow, from 3144154615f8c90397e6d3386c290cc1d7121d29. --- studio/KERNEL_REV | 4 +- studio/shell/kernel/guest.wasm | Bin 171547 -> 173398 bytes studio/shell/kernel/kernel.holo | Bin 657131 -> 663589 bytes studio/shell/kernel/kernel.json | 84 ++++++++++++++++++++++++++++++-- 4 files changed, 82 insertions(+), 6 deletions(-) diff --git a/studio/KERNEL_REV b/studio/KERNEL_REV index cf553775..a625797b 100644 --- a/studio/KERNEL_REV +++ b/studio/KERNEL_REV @@ -1,2 +1,2 @@ -https://raw.githubusercontent.com/UOR-Foundation/foundry/5f532f2352a8ca5c14c9d8aa1a1ddc9c311dcd66/studio/shell/kernel/kernel.holo -blake3:9735d1bc7ae4dda36feb6c0da4ec53c4e1ec0157eccadd466992974b6f78c156 +https://raw.githubusercontent.com/UOR-Foundation/foundry/3144154615f8c90397e6d3386c290cc1d7121d29/studio/shell/kernel/kernel.holo +blake3:f1c50fb298367ed10e324ff9ccfa755bfc11603611be5e186b4abaf39a04da89 diff --git a/studio/shell/kernel/guest.wasm b/studio/shell/kernel/guest.wasm index 70cb7d3ff75ee7ad51cf2efb03513843eac66110..3e89c4d0aaf2526caa02cddb712a298db1abfd7f 100644 GIT binary patch delta 4600 zcmb7H3vg7`8NT1Sdw1`?k_#pwF^G3#fkefi74cD&yBM@}1aVqhiLIFGD6uG|6dy%4 zJfaXNpqp?Kl2$-Q9neTv>lH^7rivJGP(}@q2#H}uBmp6*sEG7GckkWZK36#`hPngpVaoZ6J41=aaeda~Q15&2PY>QX zWbARs5o;$aqLeiOWdAW|Tx-fhi^R>Cr zTx~&eXRz4GwRd7o+HYl4#=Kb<$>@xY8uV+1MX{>9dNB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(_X~Jxc8~OXaI0iYhOFaSI zwEis=qet$23t@w5-^Y9WVkr9nkMIkEUOJBD7?9)sf*X;Sc#AqMBWyZD!ma*%#*lpI z1XKKvAa!+P8Uu`Ua}MKPa}qxl_`6*95w27C%yYRs^)bI$I9Pa^FFrf(?Zti!Q)wT@ z@~)~czRT{%IL^7DAK!7Z_rWvR!*8I{vslSy_gUP+=KgaiB;y>eve&n#*5yf;eES?C z8EB>32CxRL@`C|1x^kM5U$B7sPGz?kO>)67zP(Xg7(*TF#XQnT?J1n=sP!Y$K88iGYT0kNMC#@!NHNQe)B(AM+dQBu#^cj99 zBZ)MUPmGFQ%ETX8H|^dazII1^7I9(`62_IVx}4wTqJ-s`EQ(A~!9_$Om?8q~GQ%b( z`M9-1DkBg!`c;j}X<938@n@Q1qGJLDH;P;?Gi#HWc3Fnk$_v8EOP1>5Qfbvjas326 z-YxgbheOsO$4o_9<`~PkCETkZyh_;u>rD8@ohAiBL)J|pI*5z|y(2sq;> z_~0j-L^129D&pO&_S7y@m0@C>wwtQkMP4!|<=yvr?TE)=HIbekU2XZnpTqr`Ehln4o>1iVJGN^p2hm*xI>P-jnaC7*jn?7@El_jYAt diff --git a/studio/shell/kernel/kernel.holo b/studio/shell/kernel/kernel.holo index 78c00b0955a1834a86f6122696e2bc915437e6bb..fda75bfd2890930a9378373fb4c4b737db1b612e 100644 GIT binary patch delta 8232 zcmds4dvp|4ny;^_yVFT`C!GO8A}XCI5-@?P>Utt#Itt^?xQZUfagIl!s;gQafgl7u z=wc@*B7zRshU<%291SQhfvlD|gW~Rh8ea^9iZ2F4d@Ld_6&b+U?^bmuAtAV~{@Gns|Hvq(Bn5MFp_%tdz65Rw9Ksn5L!o1$u@1W^!pF)qg~(XfP+B1(pt zvIWi5MN5q*bs=sgk=W35HB-p-%{!4RZ~!G4fmQ! z6^+wv)j)qF+$9JiW>myDiJGiwqF@Md5rbrDlBwGmV^u)7o9(I7#@A1-7$(ge!HjEY zm@;kH(4ph%>*_Oq@E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)%a0>%R=aQp|pfU`~6{0Jmh( z?1G|Mz_OKXsTtyCrLq0}P>fIk%i1GfNL!<9TLBKHSM9=mQZVD`mP|J3od;8#)d923 zoz#zA*;ac)+_W6_h3~`qWvcMM2j(cEr}Noq9o{Z0Xy;W#KP_PUw!8OnZ#GPSay1Z2 zUayI$WdN(D@;`(Eon+*rv}8BVqw_z+-Dyid_GfO>K=yP;Af7K`OCS)bs}w3`kNMFz z^rI5C1cv@xa=0ToxC=RUA97EZvUm7n2a|o5iMRTyVv*;gEp5w_uuO|ZqOGnyoUMvd zd^h_K=soY<%`Wsh>E!WjJv!s=8_)g(^-8twKs;I%3luTf`$>;}OWVfKN={qJn09F@Lt1T8g z2y{NM*x>c!9EB>c_n)j3`Q07ldYBP)$Q}IE}H9AY$5u>1)V3tXazk# zi+u!MXsc@3`-7Q_+TNep-b=FklIS8gYaV;u6U-M`bWCQXJS&DqX82+#3TlnMg5byu zKYcYb5*zGi%3=Z73B`gj^c8&5rZHt8LUDX^hA)oW^ur@Ff;1~DQiKBZx~#}R6r^TW zgc}h^>wpZ6%m@Gy(}|SMblLs3C3xLqTHYg)duK8)NyAJL6D>gTZGl^X6chI;OkRu` z0i+unk;-I)C{`5%rF3v}yQh&|6+Q0xJ=H*Bb*lR zm5<`RI=v52B|9P)hmziczi_xHzTG#paA3D9w%xK%o>O zPK)ONVooPwr>RRe0?89_@X4N${t!Qp5v;!KT(KUF7#if?*wQP~t4*at_|io}K9rV< z0E)hsayq^iK|CNR(cgQ5==SzltVLch!nCztB!}LU6X||;C@qfiLvdd|Y6A&D@{YFa zCu0}jE;b@ms=F#VJBl*KpDeDayjTp!R z4Vs`QOyAw+NP8_^0co1WTyl;y! z-#b470$z{@=|d^By1d9}i1RCXk-TbE8lB4WsA~fBNd7lW6?Ood<5Je3af=Gw)CL{0F7X BKlcCt diff --git a/studio/shell/kernel/kernel.json b/studio/shell/kernel/kernel.json index 61e39233..a718b9a7 100644 --- a/studio/shell/kernel/kernel.json +++ b/studio/shell/kernel/kernel.json @@ -1,12 +1,12 @@ { "spec": "hologram-forge/kernel/1", "application": "Forge kernel", - "source": "https://raw.githubusercontent.com/UOR-Foundation/foundry/5f532f2352a8ca5c14c9d8aa1a1ddc9c311dcd66/studio/shell/kernel/kernel.holo", - "digest": "blake3:9735d1bc7ae4dda36feb6c0da4ec53c4e1ec0157eccadd466992974b6f78c156", + "source": "https://raw.githubusercontent.com/UOR-Foundation/foundry/3144154615f8c90397e6d3386c290cc1d7121d29/studio/shell/kernel/kernel.holo", + "digest": "blake3:f1c50fb298367ed10e324ff9ccfa755bfc11603611be5e186b4abaf39a04da89", "guest": { "path": "kernel/guest.wasm", - "sha256": "e99c9e85bc4af6a1feffae955b2100b0ab88dac12624f8c8ceabf731685a4bbb", - "bytes": 171547 + "sha256": "bfd8947b93c43bd5941b73dc69c48e7cd06571e5b771b3a20448b876463c52e6", + "bytes": 173398 }, "limits": { "request": 32776, @@ -62,6 +62,82 @@ "cnVsZSAwMTAwMDAwMDAyMDAwMDAwMDAwMDAwMDAxODAwMDAwMDAwMDAwMDAwMDEwMDAwMDAwMTAwMDAwMDAyMDAwMDAwMDEwMDAwMDAwMDAwMDAwMDAxMDAwMDAwMDQwMDAwMDAwMTAwMDAwMDAxMDAwMDAwMDIwMDAwMDAwMDAwMDAwMDAyMDAwMDAwMDMwMDAwMDAwNTAwMDAwMDAxMDAwMDAwMDAwMDAwMDA=", "bWFsZm9ybWVkUnVsZVJlcXVlc3Q=" ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAxMDAwMDAwMDEwMDAwMDAwMTAwMDAwMA==", + "b2s=" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDAwMDAwMDAwMTAwMDAwMDAxMDAwMDAwMDEwMDAwMDAwMTAwMDAwMA==", + "d29ya3NwYWNlRGV2aWNlUmVtb3ZlZA==" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDAwMDAwMDAwMDAwMDA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AyMDAwMDAwMDMwMDAwMDAwNDAwMDAwMDA1MDAwMDAwMDYwMDAwMDAwNzAwMDAwMDA4MDAwMDAwMDEwMDAwMDAwMjAwMDAwMDAzMDAwMDAwMDQwMDAwMDAwNTAwMDAwMDA2MDAwMDAwMDcwMDAwMDAwODAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMA==" From 991e1b77a57bd94cf784a3214c0ee2e00851700a Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:04:12 +0000 Subject: [PATCH 2/6] KERNEL_REV names the commit that archives the kernel holo --- studio/KERNEL_REV | 2 +- studio/shell/kernel/kernel.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/studio/KERNEL_REV b/studio/KERNEL_REV index a625797b..692f3506 100644 --- a/studio/KERNEL_REV +++ b/studio/KERNEL_REV @@ -1,2 +1,2 @@ -https://raw.githubusercontent.com/UOR-Foundation/foundry/3144154615f8c90397e6d3386c290cc1d7121d29/studio/shell/kernel/kernel.holo +https://raw.githubusercontent.com/UOR-Foundation/foundry/62add15f4cc420a82593f65765b07f686b93c06b/studio/shell/kernel/kernel.holo blake3:f1c50fb298367ed10e324ff9ccfa755bfc11603611be5e186b4abaf39a04da89 diff --git a/studio/shell/kernel/kernel.json b/studio/shell/kernel/kernel.json index a718b9a7..df05305d 100644 --- a/studio/shell/kernel/kernel.json +++ b/studio/shell/kernel/kernel.json @@ -1,7 +1,7 @@ { "spec": "hologram-forge/kernel/1", "application": "Forge kernel", - "source": "https://raw.githubusercontent.com/UOR-Foundation/foundry/3144154615f8c90397e6d3386c290cc1d7121d29/studio/shell/kernel/kernel.holo", + "source": "https://raw.githubusercontent.com/UOR-Foundation/foundry/62add15f4cc420a82593f65765b07f686b93c06b/studio/shell/kernel/kernel.holo", "digest": "blake3:f1c50fb298367ed10e324ff9ccfa755bfc11603611be5e186b4abaf39a04da89", "guest": { "path": "kernel/guest.wasm", From 3594415faa94ecfc557c4d7a55d426e1ced5f66d Mon Sep 17 00:00:00 2001 From: humuhumu33 <68450279+humuhumu33@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:23:49 +0000 Subject: [PATCH 3/6] Studio keeps a visitor's work sealed to their Prism ID (FA-93) Every record of the visitor's work is sealed with Hologram's seal_bytes as it is stored and opened as it is read, under the workspace key the Prism frame keeps for this origin (UOR-Foundation/template FR-04), which only a device of their Prism ID opens. The cipher is synchronous, so the one database handle the host hands its writers seals inside their own transactions and no writer changed. Foundry's Prism kernel decides every step: open, the one move of the work kept before, and each read and store. A removed device's work, previews and covers are cleared. The visitor hears one sentence when something changed, each a statement of the experience module. Studio bundles the frame frame.lock pins (now UOR-Foundation/template@975f95c), so it opens offline and asks no network, and runs the kernel guest built from this model (the pin of #233, merged here so its commit stays reachable). Upstream Dyad's own tests, which Foundry never ran or typechecked, are removed. Co-Authored-By: Claude Opus 5.5 --- CONFORMANCE.md | 1 + app/product.json | 5 +- app/src/Features.lex.tex | 9 +- .../tests/in_tab_kernel_verdict.rs | 24 +- features/suites/private-workspace.feature | 11 + frame.lock | 20 +- frame/frame.css | 6 +- frame/frame.mjs | 20 +- frame/panels.css | 122 +- frame/panels.mjs | 159 ++- identity/PROTOCOL.md | 12 + identity/README.md | 7 + identity/test.mjs | 17 +- model/ids.toml | 6 + site/app.mjs | 2 - studio/KERNEL_REV | 4 +- .../experience/src/FoundryExperience.lex.tex | 5 + studio/shell/host.js | 2 +- studio/shell/inference.js | 132 +- studio/shell/kernel/guest.wasm | Bin 171547 -> 173398 bytes studio/shell/kernel/kernel.holo | Bin 657131 -> 663589 bytes studio/shell/kernel/kernel.json | 84 +- .../tools/atomic_chat_preferences_browser.mjs | 2 +- .../tools/canonical_build_closure_browser.mjs | 2 +- studio/tools/durable_build_work_browser.mjs | 2 +- .../tools/durable_event_delivery_browser.mjs | 2 +- .../tools/durable_theme_library_browser.mjs | 4 +- .../tools/durable_version_preview_browser.mjs | 4 +- studio/tools/home_card_keyboard.test.mjs | 11 +- studio/tools/in_tab_kernel_verdict.test.mjs | 19 +- studio/tools/preview_permissions_browser.mjs | 2 +- .../read_only_chat_execution_browser.mjs | 2 +- studio/tools/shell_ui.test.mjs | 7 + .../stateful_application_journeys_browser.mjs | 2 +- studio/tools/storage_request_browser.mjs | 65 +- studio/vendor/dyad/VENDORED.md | 3 + .../dyad/hologram.screens/AppSidebar.tsx | 45 +- studio/vendor/dyad/src/__tests__/README.md | 68 - .../src/__tests__/app_upgrade_utils.test.ts | 207 --- .../dyad/src/__tests__/codebase.test.ts | 499 ------- .../src/__tests__/dyad_auth_bootstrap.test.ts | 544 -------- .../dyad/src/__tests__/dyad_logs.test.ts | 195 --- .../__tests__/dyad_recorder_client.test.ts | 1205 ----------------- .../vendor/dyad/src/__tests__/evals/README.md | 378 ------ .../src/__tests__/evals/chat_history.eval.ts | 432 ------ .../src/__tests__/evals/compaction.eval.ts | 319 ----- .../__tests__/evals/fixtures/UserProfile.tsx | 354 ----- .../evals/fixtures/UserProfileFull.tsx | 713 ---------- .../src/__tests__/evals/fixtures/analytics.ts | 337 ----- .../__tests__/evals/fixtures/cache_manager.ts | 327 ----- .../evals/fixtures/chat_history/AUTHORING.md | 198 --- .../chat_history/conflict_superseded.json | 391 ------ .../fixtures/chat_history/cross_app.json | 493 ------- .../fixtures/chat_history/exact_recall.json | 410 ------ .../chat_history/multi_chat_synthesis.json | 466 ------- .../evals/fixtures/chat_history/no_match.json | 410 ------ .../chat_history/prompt_injection.json | 421 ------ .../fixtures/chat_history/vague_decision.json | 568 -------- .../evals/fixtures/compaction/.gitignore | 5 - .../evals/fixtures/compaction/AUTHORING.md | 98 -- .../compaction/debug-spiral.stats.json | 14 - .../compaction/error-recovery.stats.json | 14 - .../compaction/feature-marathon.stats.json | 14 - .../evals/fixtures/compaction/generate.mjs | 600 -------- .../fixtures/compaction/pivot.stats.json | 14 - .../compaction/polyglot-context.stats.json | 14 - .../preferences-and-constraints.stats.json | 14 - .../compaction/refactor-plan.stats.json | 14 - .../compaction/specs/debug-spiral.spec.json | 210 --- .../compaction/specs/error-recovery.spec.json | 214 --- .../specs/feature-marathon.spec.json | 208 --- .../fixtures/compaction/specs/pivot.spec.json | 222 --- .../specs/polyglot-context.spec.json | 207 --- .../preferences-and-constraints.spec.json | 217 --- .../compaction/specs/refactor-plan.spec.json | 210 --- .../compaction/specs/tool-noise.spec.json | 213 --- .../fixtures/compaction/tool-noise.stats.json | 14 - .../__tests__/evals/fixtures/config_reader.ts | 332 ----- .../__tests__/evals/fixtures/contact_book.ts | 211 --- .../__tests__/evals/fixtures/event_handler.ts | 355 ----- .../__tests__/evals/fixtures/fetch_client.ts | 337 ----- .../__tests__/evals/fixtures/order_math.ts | 314 ----- .../evals/fixtures/order_processor.ts | 339 ----- .../__tests__/evals/fixtures/permissions.ts | 136 -- .../evals/fixtures/report_builders.ts | 418 ------ .../evals/fixtures/route_handlers.ts | 329 ----- .../__tests__/evals/fixtures/stat_utils.ts | 162 --- .../__tests__/evals/fixtures/user_handler.ts | 338 ----- .../__tests__/evals/fixtures/user_service.ts | 360 ----- .../evals/helpers/chat_history_harness.ts | 1066 --------------- .../evals/helpers/compaction_harness.ts | 486 ------- .../__tests__/evals/helpers/eval_recorder.ts | 485 ------- .../__tests__/evals/helpers/get_eval_model.ts | 255 ---- .../evals/helpers/legacy_search_replace.ts | 409 ------ .../evals/helpers/newline_probe.spec.ts | 185 --- .../__tests__/evals/helpers/newline_probe.ts | 308 ----- .../src/__tests__/evals/helpers/prompts.ts | 167 --- .../__tests__/evals/helpers/unified_diff.ts | 195 --- .../__tests__/evals/plumbing_check.eval.ts | 83 -- .../__tests__/evals/recorded_calls.spec.ts | 205 --- .../luna/add-error-handling/01.txt | 12 - .../luna/add-error-handling/02.txt | 52 - .../luna/add-error-handling/03.txt | 41 - .../luna/add-zod-validation/01.txt | 27 - .../luna/add-zod-validation/02.txt | 37 - .../evals/recorded_calls/manifest.json | 50 - .../sol/add-zod-validation/01.txt | 16 - .../sol/add-zod-validation/02.txt | 34 - .../sol/add-zod-validation/03.txt | 39 - .../sol/extract-a-helper-function/01.txt | 128 -- .../sol/refactor-giant-component/01.txt | 393 ------ .../sol/refactor-giant-component/02.txt | 109 -- .../sol/refactor-giant-component/03.txt | 158 --- .../sol/refactor-giant-component/04.txt | 125 -- .../sol/refactor-giant-component/05.txt | 125 -- .../sol/refactor-giant-component/06.txt | 50 - .../sol/refactor-giant-component/07.txt | 46 - .../sol/refactor-giant-component/08.txt | 35 - .../sol/refactor-giant-component/09.txt | 49 - .../sol/refactor-giant-component/10.txt | 51 - .../sol/refactor-giant-component/11.txt | 16 - .../sol/refactor-giant-component/12.txt | 61 - .../dyad/src/__tests__/evals/tool_use.eval.ts | 1103 --------------- ...generate_release_provenance_script.test.ts | 127 -- .../fixtures/chat-tab-session.real.json | 6 - .../invalidation.test.tsx | 111 -- .../golden_single_window/lifecycle.test.tsx | 87 -- ...mutation_invalidation.integration.test.tsx | 108 -- .../notifications.test.tsx | 216 --- .../runtime_delivery.test.tsx | 248 ---- .../golden_single_window/tab_session.test.tsx | 149 -- .../__tests__/legacy_fixture_adapter.test.ts | 125 -- .../src/__tests__/packaging_cleanup.test.ts | 390 ------ .../vendor/dyad/src/__tests__/ports.test.ts | 53 - .../prepare_release_tag_script.test.ts | 148 -- .../process_memory_diagnostics.test.ts | 179 --- .../__tests__/proxy_server_cookies.test.ts | 258 ---- .../src/__tests__/proxy_server_csp.test.ts | 204 --- .../src/__tests__/proxy_server_port.test.ts | 136 -- .../release_version_utils_script.test.ts | 19 - .../src/__tests__/release_workflow.test.ts | 26 - .../dyad/src/__tests__/renderer_html.test.ts | 12 - .../__tests__/stable_aria_snapshot.test.ts | 168 --- .../verify_release_assets_script.test.ts | 85 -- .../dyad/src/__tests__/xmlEscape.test.ts | 122 -- .../chat_tab_session_storage.test.ts | 493 ------- studio/vendor/dyad/vite.shell.config.mts | 25 +- verification/private-workspace.md | 62 +- 148 files changed, 671 insertions(+), 25389 deletions(-) delete mode 100644 studio/vendor/dyad/src/__tests__/README.md delete mode 100644 studio/vendor/dyad/src/__tests__/app_upgrade_utils.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/codebase.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/dyad_auth_bootstrap.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/dyad_logs.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/dyad_recorder_client.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/README.md delete mode 100644 studio/vendor/dyad/src/__tests__/evals/chat_history.eval.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/compaction.eval.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/UserProfile.tsx delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/UserProfileFull.tsx delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/analytics.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/cache_manager.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/chat_history/AUTHORING.md delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/chat_history/conflict_superseded.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/chat_history/cross_app.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/chat_history/exact_recall.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/chat_history/multi_chat_synthesis.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/chat_history/no_match.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/chat_history/prompt_injection.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/chat_history/vague_decision.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/.gitignore delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/AUTHORING.md delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/debug-spiral.stats.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/error-recovery.stats.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/feature-marathon.stats.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/generate.mjs delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/pivot.stats.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/polyglot-context.stats.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/preferences-and-constraints.stats.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/refactor-plan.stats.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/specs/debug-spiral.spec.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/specs/error-recovery.spec.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/specs/feature-marathon.spec.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/specs/pivot.spec.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/specs/polyglot-context.spec.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/specs/preferences-and-constraints.spec.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/specs/refactor-plan.spec.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/specs/tool-noise.spec.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/compaction/tool-noise.stats.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/config_reader.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/contact_book.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/event_handler.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/fetch_client.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/order_math.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/order_processor.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/permissions.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/report_builders.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/route_handlers.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/stat_utils.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/user_handler.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/fixtures/user_service.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/helpers/chat_history_harness.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/helpers/compaction_harness.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/helpers/eval_recorder.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/helpers/get_eval_model.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/helpers/legacy_search_replace.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/helpers/newline_probe.spec.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/helpers/newline_probe.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/helpers/prompts.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/helpers/unified_diff.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/plumbing_check.eval.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls.spec.ts delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/luna/add-error-handling/01.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/luna/add-error-handling/02.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/luna/add-error-handling/03.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/luna/add-zod-validation/01.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/luna/add-zod-validation/02.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/manifest.json delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/add-zod-validation/01.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/add-zod-validation/02.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/add-zod-validation/03.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/extract-a-helper-function/01.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/refactor-giant-component/01.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/refactor-giant-component/02.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/refactor-giant-component/03.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/refactor-giant-component/04.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/refactor-giant-component/05.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/refactor-giant-component/06.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/refactor-giant-component/07.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/refactor-giant-component/08.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/refactor-giant-component/09.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/refactor-giant-component/10.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/refactor-giant-component/11.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/recorded_calls/sol/refactor-giant-component/12.txt delete mode 100644 studio/vendor/dyad/src/__tests__/evals/tool_use.eval.ts delete mode 100644 studio/vendor/dyad/src/__tests__/generate_release_provenance_script.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/golden_single_window/fixtures/chat-tab-session.real.json delete mode 100644 studio/vendor/dyad/src/__tests__/golden_single_window/invalidation.test.tsx delete mode 100644 studio/vendor/dyad/src/__tests__/golden_single_window/lifecycle.test.tsx delete mode 100644 studio/vendor/dyad/src/__tests__/golden_single_window/mutation_invalidation.integration.test.tsx delete mode 100644 studio/vendor/dyad/src/__tests__/golden_single_window/notifications.test.tsx delete mode 100644 studio/vendor/dyad/src/__tests__/golden_single_window/runtime_delivery.test.tsx delete mode 100644 studio/vendor/dyad/src/__tests__/golden_single_window/tab_session.test.tsx delete mode 100644 studio/vendor/dyad/src/__tests__/legacy_fixture_adapter.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/packaging_cleanup.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/ports.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/prepare_release_tag_script.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/process_memory_diagnostics.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/proxy_server_cookies.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/proxy_server_csp.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/proxy_server_port.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/release_version_utils_script.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/release_workflow.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/renderer_html.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/stable_aria_snapshot.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/verify_release_assets_script.test.ts delete mode 100644 studio/vendor/dyad/src/__tests__/xmlEscape.test.ts delete mode 100644 studio/vendor/dyad/src/window_infrastructure/chat_tab_session_storage.test.ts diff --git a/CONFORMANCE.md b/CONFORMANCE.md index 1c67ddda..cc3b29a2 100644 --- a/CONFORMANCE.md +++ b/CONFORMANCE.md @@ -416,6 +416,7 @@ model does not sanction. | ID | Level | Statement | | --- | --- | --- | | `FA-91` | `build` | A private workspace opens only for the Prism id that owns it, on a device with a live session and its current boundary key; a record is read only when authentic and in place and stored only sealed; the workspace kept before an id moves in once; and Foundry's Prism kernel names every refusal | +| `FA-93` | `build` | Studio keeps a visitor's work sealed to their Prism ID: each record is sealed as it is stored and opened as it is read, only as Foundry's Prism kernel answers; the work kept before moves in once; a removed device's work is cleared; and the visitor is told each outcome in one sentence | ## product-model diff --git a/app/product.json b/app/product.json index 7d697719..982c149d 100644 --- a/app/product.json +++ b/app/product.json @@ -900,10 +900,11 @@ }, { "name": "Prism id", - "text": "The frame keeps one Prism id per visitor, stitch's, made on first touch with no sign-in; a session verifies only for its app, an active device and its time, and linking, removal and recovery are quiet panel actions over stitch's relay; the kernel opens a private workspace only for that id and names every refusal.", + "text": "The frame keeps one Prism id per visitor, stitch's, made on first touch with no sign-in; a session verifies only for its app, an active device and its time, and linking, removal and recovery are quiet panel actions over stitch's relay; the kernel opens a private workspace only for that id and names every refusal, and Studio keeps the visitor's work sealed to it.", "ids": [ "FA-88", - "FA-91" + "FA-91", + "FA-93" ], "calls": [ "FoundrySpecification::prismIdBoundary", diff --git a/app/src/Features.lex.tex b/app/src/Features.lex.tex index 58991325..d67dbfc0 100644 --- a/app/src/Features.lex.tex +++ b/app/src/Features.lex.tex @@ -1375,6 +1375,13 @@ body: "crates/conformance/tests/in_tab_kernel_verdict.rs::private_workspace_fa_91" } +definition{ + name: testFA93, + parameters: [], + result: String, + body: "crates/conformance/tests/in_tab_kernel_verdict.rs::private_workspace_fa_93" +} + definition{ name: testFA61, parameters: [], @@ -1680,7 +1687,7 @@ name: featurePrismId, parameters: [], result: Foundation.Arch::Feature, - body: (record Foundation.Arch::Feature {statement := "Prism id (FA-88, FA-91): The frame keeps one Prism id per visitor, stitch's, made on first touch with no sign-in; a session verifies only for its app, an active device and its time, and linking, removal and recovery are quiet panel actions over stitch's relay; the kernel opens a private workspace only for that id and names every refusal.", calls := (cons "FoundrySpecification::prismIdBoundary" (cons "Workspace::dispatchWorkspace" (nil String))), acceptance := (cons "Features::acceptWorkspaceProofsWorkspaceWordsOwnerOpens" (cons "Features::acceptWorkspaceProofsWorkspaceWordsAnotherIdRefused" (cons "Features::acceptWorkspaceProofsWorkspaceWordsTamperedRecordRefused" (cons "Features::testFA88" (cons "Features::testFA91" (nil String))))))}) + body: (record Foundation.Arch::Feature {statement := "Prism id (FA-88, FA-91, FA-93): The frame keeps one Prism id per visitor, stitch's, made on first touch with no sign-in; a session verifies only for its app, an active device and its time, and linking, removal and recovery are quiet panel actions over stitch's relay; the kernel opens a private workspace only for that id and names every refusal, and Studio keeps the visitor's work sealed to it.", calls := (cons "FoundrySpecification::prismIdBoundary" (cons "Workspace::dispatchWorkspace" (nil String))), acceptance := (cons "Features::acceptWorkspaceProofsWorkspaceWordsOwnerOpens" (cons "Features::acceptWorkspaceProofsWorkspaceWordsAnotherIdRefused" (cons "Features::acceptWorkspaceProofsWorkspaceWordsTamperedRecordRefused" (cons "Features::testFA88" (cons "Features::testFA91" (cons "Features::testFA93" (nil String)))))))}) } definition{ diff --git a/crates/conformance/tests/in_tab_kernel_verdict.rs b/crates/conformance/tests/in_tab_kernel_verdict.rs index 37396fe9..11452e21 100644 --- a/crates/conformance/tests/in_tab_kernel_verdict.rs +++ b/crates/conformance/tests/in_tab_kernel_verdict.rs @@ -23,8 +23,8 @@ fn in_tab_kernel_verdict_fa_86() { ); // A run that skipped, filtered or lost a test is not the oracle. for required in [ - "# tests 7", - "# pass 7", + "# tests 8", + "# pass 8", "# fail 0", "# cancelled 0", "# skipped 0", @@ -69,3 +69,23 @@ fn private_workspace_fa_91() { ); assert!(theorems >= 19 && kernel.contains("(workspaceAcceptance))))")); } + +/// `FA-93`: Studio keeps a visitor's work sealed to their Prism ID: each record is sealed as it is stored and opened as it is read, only as Foundry's Prism kernel answers; the work kept before moves in once; a removed device's work is cleared; and the visitor is told each outcome in one sentence +/// +/// Here, every request Studio's sealed store makes, asked of the guest Studio pins; the sealing itself runs in +/// Chromium in Studio CI (`studio/tools/storage_request_browser.mjs`), where the shell is built. +#[test] +fn private_workspace_fa_93() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../.."); + let output = Command::new("node") + .args(["--test", "--test-reporter=tap"]) + .arg(root.join("studio/tools/in_tab_kernel_verdict.test.mjs")) + .output() + .expect("the locked SDK supplies Node"); + let report = String::from_utf8_lossy(&output.stdout); + let name = "the pinned guest answers every workspace request Studio makes, as Studio acts on it (FA-93)"; + assert!( + output.status.success() && report.lines().any(|l| l.starts_with("ok ") && l.ends_with(name)), + "{report}" + ); +} diff --git a/features/suites/private-workspace.feature b/features/suites/private-workspace.feature index 06b97ff4..64e1885f 100644 --- a/features/suites/private-workspace.feature +++ b/features/suites/private-workspace.feature @@ -7,3 +7,14 @@ Feature: private-workspace Then it answers ok only for the owning id on a device with a live session and the current boundary key, for an authentic record in its place, for a sealed record within quota, for a first move, and for a removal after the sealed copy is committed And every other request is refused by name, a removed device first, and a wrong version, a trailing word or an unknown kind is malformedWorkspaceRequest And each answer is a theorem Lean proves by evaluation and an acceptance vector the compiled guest replays + + @FA-93 @build + Scenario: Studio keeps a visitor's work sealed to their Prism ID: each record is sealed as it is stored and opened as it is read, only as Foundry's Prism kernel answers; the work kept before moves in once; a removed device's work is cleared; and the visitor is told each outcome in one sentence + Given Studio's device store, the workspace key the Prism frame keeps for this origin, and the kernel guest Studio pins + When Studio opens over work kept before the workspace, reads and stores records, meets a record altered, copied or planted in the clear, and opens on a device removed from the visitor's Prism ID + Then the work kept before is sealed in place in one transaction, opens as it was written, and the visitor is told so once + And every record stored afterwards is sealed with seal_bytes, except the grants and published .holo bytes the service worker reads + And an altered or planted record is refused as recordTampered and a copied one as recordMisplaced, and neither is returned + And on a removed device everything kept where work belongs is cleared before a new key is made, so nothing left behind enters the new workspace + And the sentence the visitor reads for each answer is a statement of the experience module + diff --git a/frame.lock b/frame.lock index d904eed7..3ff8eab5 100644 --- a/frame.lock +++ b/frame.lock @@ -2,8 +2,8 @@ "spec": "prism/frame-lock/1", "source": { "repository": "UOR-Foundation/template", - "commit": "0851bb41138041f0f75118135fd8a342109c2d73", - "raw": "https://raw.githubusercontent.com/UOR-Foundation/template/0851bb41138041f0f75118135fd8a342109c2d73/" + "commit": "975f95cc4be0380a5c9ae01f71555e4df1e0e230", + "raw": "https://raw.githubusercontent.com/UOR-Foundation/template/975f95cc4be0380a5c9ae01f71555e4df1e0e230/" }, "files": [ { @@ -116,19 +116,19 @@ }, { "path": "frame/frame.css", - "sha256": "c7470fdcbdb0ca9c6e2a634b6ec4ba9f1ed87c39b737f91e082b8c6466ab91f4" + "sha256": "ac8c9cfe2f1e7fe0c7c3725c840e0296fae76314521860d7840ce66876f65869" }, { "path": "frame/frame.mjs", - "sha256": "208994058dcc6c70a91d590c345cb4956eda3532096f298f0a21f809f11672c1" + "sha256": "e9c02c8355cf3fb6dea3801e7ea5fa84adab0a117198ed39418ce3ea83930156" }, { "path": "frame/panels.css", - "sha256": "9b6bcd85303139ddaac9b2cbde7b7d3ef61d34da336874774073124b2560d8ce" + "sha256": "c6faa6a4ddf50444ca887a60e18530390ed52adf38a9d69fb257d3ed7254eb7d" }, { "path": "frame/panels.mjs", - "sha256": "f2db1617f0a6d14e4447c54bafc7aeb45c7cb152b0f5a0b27b5615f8ce8d7b92" + "sha256": "4eb0dea50cd91a1dce08a459b80b96a5c34d89eec85fedfdf168c5644f7b92a9" }, { "path": "frame/publish.mjs", @@ -152,11 +152,11 @@ }, { "path": "identity/PROTOCOL.md", - "sha256": "1e3a042a4a100683e0df5bc8210c367785e844feb63cd561d591979733e7ff82" + "sha256": "a66215423f8bf70ffbb52e2d9a96f04cb8baa922d2c5adf999be14a491dc382b" }, { "path": "identity/README.md", - "sha256": "351d9387fbc8fac0123f13a2e03e03aba8a4c0aed8e38f6040973bec4246fef1" + "sha256": "8a22ec0478abadd3e3522a288c80da1dabea462b8485c6169941ebc3003c2a28" }, { "path": "identity/dev.mjs", @@ -176,7 +176,7 @@ }, { "path": "identity/test.mjs", - "sha256": "21cb6924014c80f378abf5d07720a203c7e62aa99ffd38e05f6d8376153317f9" + "sha256": "fd771e403d0391846fe8e666c2026d01026d47c78de709ac21171b82737f1cf1" }, { "path": "lighthouserc.json", @@ -184,7 +184,7 @@ }, { "path": "site/app.mjs", - "sha256": "b5b30e78ab9b693fd6d29b89b9d2b74542340542864e99e4533a9ced2d987ee0" + "sha256": "65a3d1e3fcc6ed9ddfcbf85477c99a41a94a98502e62de90e7dcce3f860b0ace" }, { "path": "site/guest-worker.mjs", diff --git a/frame/frame.css b/frame/frame.css index b233c1c3..70efba8a 100644 --- a/frame/frame.css +++ b/frame/frame.css @@ -47,9 +47,9 @@ * edge is the bar's bottom edge. */ --chrome: var(--sidebar, var(--muted)); /* The address: on the light chrome a white field, on the dark one barely - * off the chrome, its hairline drawing it. */ + * off the chrome, its hairline drawing it at 3:1 or more (WCAG 1.4.11). */ --field: light-dark(var(--card), color-mix(in oklab, var(--chrome), var(--foreground) 3%)); - --field-border: var(--border); + --field-border: var(--muted-foreground); --gutter: 0.5rem; --window-radius: 0.75rem; --frame-height: calc(var(--safe-top) + var(--bar-control) + 0.875rem); @@ -230,7 +230,7 @@ svg.gh, svg.fill { fill: currentColor; stroke: none; } * full text colour: white on the dark chrome, near-black on the light, as * Hologram OS draws it. A touch larger than the line icons, so its dots * stay distinct. */ -#home { color: var(--foreground); } +#home { color: var(--foreground); } #home:focus-visible { outline: var(--ring-width) solid var(--ring); outline-offset: var(--ring-offset); border-radius: var(--radius-control); } #home svg.mark { width: 1.25rem; height: 1.25rem; shape-rendering: geometricPrecision; } .ghost.icon:hover { color: var(--foreground); } .ghost.icon:hover::before { background: color-mix(in oklab, var(--chrome), var(--foreground) 7%); } diff --git a/frame/frame.mjs b/frame/frame.mjs index 211002f8..8c524666 100644 --- a/frame/frame.mjs +++ b/frame/frame.mjs @@ -131,12 +131,14 @@ const firstMove = () => // which publish.mjs writes here. // It is fetched after the first move, checked against that hash as the page // checks the frame, and imported; a failure is tried again the next time. +// Unpublished (a checkout, or an app that bundles its locked copy of the +// frame), it is imported from beside this file, as panels.mjs imports Prism id. const PANELS = "/*PANELS*/"; let panelsModule = null; let panelsSheet = null; const loadPanels = () => (panelsModule ??= (async () => { - if (!/^[0-9a-f]{64}$/.test(PANELS)) throw new Error("this frame was published without its panels"); + if (!/^[0-9a-f]{64}$/.test(PANELS)) return import("./panels.mjs"); const bytes = await (await fetch(new URL(`${PANELS}/prism-panels.mjs`, FRAME_HOST))).arrayBuffer(); const hex = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), (b) => b.toString(16).padStart(2, "0")).join(""); if (hex !== PANELS) throw new Error("the panels module is not the one this frame names"); @@ -187,7 +189,7 @@ const markup = (e) => ` - +
@@ -846,6 +848,13 @@ class PrismFrame extends Element { return { signature: b64u(signature), delegation: saved.delegation }; } + // This app's workspace key: 32 bytes only a device of the visitor's Prism + // id opens (panels.mjs, openWorkspace). { replace: true } starts a new one. + workspaceKey(options) { + if (!this.accountsReady) return Promise.reject(Object.assign(new Error("A Prism ID cannot work here"), { name: "IdentityError", code: "unsupported" })); + return this.accountsReady().then((accounts) => accounts.workspace(options)); + } + // The Prism id icon, after full screen: a line drawing until the id is // ready, filled once it is. The id is made, and this app's session signed, // with nothing to click and nothing in the way, by the panels module @@ -857,7 +866,7 @@ class PrismFrame extends Element { const button = this.$("account"); const panel = this.$("account-panel"); this.accountWatch?.abort(); - this.accountReady = null; + this.accountReady = this.accountsReady = null; let wired = false; if (typeof panel.showPopover !== "function" || !window.isSecureContext || !globalThis.crypto?.subtle || !globalThis.indexedDB) { button.hidden = true; @@ -865,7 +874,7 @@ class PrismFrame extends Element { } const paint = () => { const saved = accountChannel.session; - const label = "Prism id"; + const label = "Prism ID"; button.classList.toggle("signed-in", Boolean(saved)); button.setAttribute("aria-label", label); button.title = label; @@ -891,6 +900,7 @@ class PrismFrame extends Element { } return this.accountReady; }; + this.accountsReady = ready; const reach = () => ready().then((accounts) => accounts.reach(), () => {}); for (const type of ["pointerenter", "focus", "touchstart"]) button.addEventListener(type, reach, { passive: true }); // First use: the visitor's first touch, click or key anywhere makes the id. @@ -1357,7 +1367,7 @@ class PrismFrame extends Element { event.preventDefault(); if (list.hidden) render(); select(active + (event.key === "ArrowDown" ? 1 : -1)); - } else if (event.key === "Escape") { + } else if (event.key === "Tab" && !event.shiftKey) { close(); } else if (event.key === "Escape") { event.preventDefault(); if (input.value !== shown) { input.value = shown; diff --git a/frame/panels.css b/frame/panels.css index 98005af1..02e05877 100644 --- a/frame/panels.css +++ b/frame/panels.css @@ -2,37 +2,37 @@ * suggestions and the theme (its modes, the Unsplash search and the photos). * Loaded with frame/panels.mjs after the visitor's first move, never with the * page; a panel opened before then waits for them. */ -/* The theme panel: three modes side by side, then three photos to set - * behind the page, then the photographer's credit. It opens under the theme - * button (the script sets --theme-top and --theme-right) as share does. */ -.theme-panel { +/* The popovers' common surface and titles. */ +.theme-panel, .trust-panel, .share-panel { position: fixed; - inset: var(--theme-top, 3rem) var(--theme-right, 1rem) auto auto; - width: min(20rem, 100vw - 2rem); - max-height: calc(100vh - var(--theme-top, 3rem) - 1rem); margin: 0; - padding: var(--space-3); overflow: auto; border: var(--border-width) solid var(--border); border-radius: var(--radius); background: var(--popover); color: var(--popover-foreground); box-shadow: var(--shadow-overlay); + transition: opacity var(--duration) var(--ease), transform var(--duration) var(--ease), overlay var(--duration) allow-discrete, display var(--duration) allow-discrete; +} +.theme-panel:not(:popover-open), .trust-panel:not(:popover-open), .share-panel:not(:popover-open) { opacity: 0; transform: translateY(-0.25rem) scale(0.98); } +:host([dark]) :is(.theme-panel, .trust-panel, .share-panel, .account-panel) { box-shadow: none; border-color: var(--border-strong); } +/* The theme panel: three modes side by side, then three photos to set + * behind the page, then the photographer's credit. It opens under the theme + * button (the script sets --theme-top and --theme-right) as share does. */ +.theme-panel { + inset: var(--theme-top, 3rem) var(--theme-right, 1rem) auto auto; + width: min(20rem, 100vw - 2rem); + max-height: calc(100vh - var(--theme-top, 3rem) - 1rem); + padding: var(--space-3); font-size: var(--text-14); scrollbar-width: thin; scrollbar-color: var(--border-strong) transparent; transform-origin: top right; - transition: opacity var(--duration) var(--ease), transform var(--duration) var(--ease), overlay var(--duration) allow-discrete, display var(--duration) allow-discrete; } -.theme-panel:not(:popover-open) { opacity: 0; transform: translateY(-0.25rem) scale(0.98); } -:host([dark]) .theme-panel { box-shadow: none; border-color: var(--border-strong); } +.theme-title, .share-title, .trust-title { font-family: var(--font-display); font-weight: 600; font-size: var(--text-16); letter-spacing: var(--tracking-display); } .theme-title { margin: 0 0 var(--space-3); padding: 0 var(--space-1); - font-family: var(--font-display); - font-weight: 600; - font-size: var(--text-16); - letter-spacing: var(--tracking-display); } /* The modes: one slim segmented switch, as a system setting draws it. The * mode in use is a raised chip inside a sunken track; small, fine icons. */ @@ -243,25 +243,14 @@ * opens under the shield (the script sets --trust-top and --trust-left), * lifts in over one beat and closes on Escape or a click outside. */ .trust-panel { - position: fixed; inset: var(--trust-top, 3rem) auto auto var(--trust-left, 1rem); width: min(22rem, 100vw - 2rem); max-height: calc(100vh - var(--trust-top, 3rem) - 1rem); - margin: 0; padding: var(--space-2); - overflow: auto; - border: var(--border-width) solid var(--border); - border-radius: var(--radius); - background: var(--popover); - color: var(--popover-foreground); - box-shadow: var(--shadow-overlay); font-size: var(--text-14); line-height: 1.45; transform-origin: top left; - transition: opacity var(--duration) var(--ease), transform var(--duration) var(--ease), overlay var(--duration) allow-discrete, display var(--duration) allow-discrete; } -.trust-panel:not(:popover-open) { opacity: 0; transform: translateY(-0.25rem) scale(0.98); } -:host([dark]) .trust-panel { box-shadow: none; border-color: var(--border-strong); } .trust-panel p { margin: 0; } .trust-head { @@ -272,7 +261,6 @@ border-bottom: var(--border-width) solid var(--border); } .trust-words { min-width: 0; } -.trust-title { font-family: var(--font-display); font-size: var(--text-16); font-weight: 600; letter-spacing: var(--tracking-display); } .check { display: flex; gap: var(--space-3); padding: var(--space-2); } .check .mark { flex: none; display: grid; place-items: center; width: 1.25rem; height: 1.3125rem; } .check .mark svg { width: 1rem; height: 1rem; fill: none; stroke: currentColor; stroke-width: 1.75; } @@ -327,29 +315,14 @@ * a click outside, and gives focus back to the button. Light ground: the * overlay shadow; dark ground: no shadow, a stronger hairline. */ .share-panel { - position: fixed; inset: var(--share-top, 4rem) var(--share-right, 1rem) auto auto; width: min(23rem, 100vw - 2rem); max-height: calc(100vh - var(--share-top, 4rem) - 1rem); - margin: 0; padding: var(--space-4); - overflow: auto; - border: var(--border-width) solid var(--border); - border-radius: var(--radius); - background: var(--popover); - color: var(--popover-foreground); - box-shadow: var(--shadow-overlay); transform-origin: top right; - transition: opacity var(--duration) var(--ease), transform var(--duration) var(--ease), overlay var(--duration) allow-discrete, display var(--duration) allow-discrete; } -.share-panel:not(:popover-open) { opacity: 0; transform: translateY(-0.25rem) scale(0.98); } -:host([dark]) .share-panel { box-shadow: none; border-color: var(--border-strong); } .share-title { margin: 0 0 var(--space-3); - font-family: var(--font-display); - font-weight: 600; - font-size: var(--text-16); - letter-spacing: var(--tracking-display); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; @@ -410,24 +383,7 @@ * the golden ratio (1.618): the width is 1.618 x 16rem, the padding 1.618rem, * the title 1.618 x the body text, the gaps 0.618, 1 and 1.618rem, and the * backdrop dims by 0.382. Outside, Escape or the close button dismisses it. */ -.account-panel { - position: fixed; - inset: 0; - width: min(25.888rem, 100vw - 2rem); - height: fit-content; - max-height: calc(100dvh - 2rem); - margin: auto; - padding: 1.618rem; - overflow: auto; - border: var(--border-width) solid var(--border); - border-radius: calc(var(--radius) * 1.618); - background: var(--popover); - color: var(--popover-foreground); - box-shadow: var(--shadow-overlay); - font-size: var(--text-14); - line-height: 1.5; - transition: opacity var(--duration) var(--ease), transform var(--duration) var(--ease), overlay var(--duration) allow-discrete, display var(--duration) allow-discrete; -} +.account-panel { position: fixed; inset: 0; width: min(25.888rem, 100vw - 2rem); height: fit-content; max-height: calc(100dvh - 2rem); margin: auto; padding: 1.618rem; overflow: auto; border: var(--border-width) solid var(--border); border-radius: calc(var(--radius) * 1.618); background: var(--popover); color: var(--popover-foreground); box-shadow: var(--shadow-overlay); font-size: var(--text-14); line-height: 1.5; transition: opacity var(--duration) var(--ease), transform var(--duration) var(--ease), overlay var(--duration) allow-discrete, display var(--duration) allow-discrete; } .account-panel:not(:popover-open) { opacity: 0; transform: scale(0.98); } @starting-style { .account-panel:popover-open { opacity: 0; transform: scale(0.98); } @@ -437,37 +393,41 @@ -webkit-backdrop-filter: blur(1rem); backdrop-filter: blur(1rem); } -:host([dark]) .account-panel { box-shadow: none; border-color: var(--border-strong); } .account-panel p, .account-panel h2 { margin: 0; } -.account-close { - position: absolute; - top: 1rem; - right: 1rem; - display: grid; - place-items: center; - width: 2rem; - height: 2rem; - min-height: 0; - padding: 0; - border: var(--border-width) solid var(--border); - border-radius: var(--radius-control); - background: none; - color: var(--muted-foreground); - cursor: pointer; -} +.account-close { position: absolute; top: 1rem; right: 1rem; display: grid; place-items: center; width: 2rem; height: 2rem; min-height: 0; padding: 0; border: 0; border-radius: var(--radius-control); background: none; color: var(--muted-foreground); cursor: pointer; } .account-close:hover { background: var(--accent); color: var(--foreground); } .account-close svg { fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; } -.account-title { padding-right: 2.618rem; font-family: var(--font-display); font-weight: 600; font-size: 1.618rem; line-height: 1.236; letter-spacing: var(--tracking-display); } -.account-sub { margin: 0.618rem 0 1.618rem !important; color: var(--muted-foreground); font-size: 1rem; } +.account-title { padding-right: 2.618rem; font-family: var(--font-display); font-weight: 600; font-size: 1.382rem; line-height: 1.236; letter-spacing: var(--tracking-display); } +.account-sub { margin: 0.382rem 0 1rem !important; color: var(--muted-foreground); font-size: var(--text-14); } .account-in { display: grid; gap: 0.382rem; } .account-id { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); margin-bottom: 0.618rem !important; padding: 0.618rem 1rem; border: var(--border-width) solid var(--border); border-radius: var(--radius-control); background: var(--background); } .account-id code { font-family: var(--font-mono); color: var(--muted-foreground); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .account-qr { display: block; width: min(100%, 14rem); aspect-ratio: 1; margin: 0 auto 0.618rem; background: #fff; border-radius: var(--radius-control); } .account-qr path { fill: #000; } .account-panel .text { padding: 0; border: 0; background: none; color: var(--foreground); font-weight: 500; text-decoration: underline; text-decoration-color: var(--border-strong); text-underline-offset: 0.2em; cursor: pointer; } -.account-panel .row { justify-content: flex-start; width: 100%; min-height: 2.618rem; padding: 0 1rem; border: 0; border-radius: var(--radius-control); background: none; color: var(--foreground); font-size: 1rem; text-align: start; cursor: pointer; } +/* The id itself, then the one thing worth doing now, then every choice grouped by why you would make it: + * each row says what it does, and in a muted line, why. Icons are outlines at the text colour. */ +.account-panel .glyph { flex: none; width: 1.125rem; height: 1.125rem; fill: none; stroke: currentColor; stroke-width: 1.75; stroke-linecap: round; stroke-linejoin: round; } +.account-card { display: flex; align-items: center; gap: 0.75rem; padding: 0.75rem; border: var(--border-width) solid var(--border); border-radius: calc(var(--radius) * 1.236); background: var(--background); } +.account-panel .account-avatar { width: 2.5rem; height: 2.5rem; padding: 0.5rem; border-radius: 50%; background: var(--accent); stroke-width: 1.5; } +.account-who { display: grid; flex: 1; min-width: 0; gap: 0.125rem; } +.account-who code { font-family: var(--font-mono); font-size: var(--text-14); color: var(--foreground); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.account-panel small { display: flex; align-items: center; gap: 0.25rem; color: var(--muted-foreground); font-size: 0.75rem; line-height: 1.4; } +.account-who small .glyph { width: 0.75rem; height: 0.75rem; } +.account-icon { display: grid; place-items: center; width: 2rem; height: 2rem; min-height: 0; padding: 0; border: 0; border-radius: var(--radius-control); background: none; color: var(--muted-foreground); cursor: pointer; } +.account-icon:hover { background: var(--accent); color: var(--foreground); } +.account-kit { display: flex; gap: 0.75rem; margin-top: 0.382rem; padding: 0.875rem; border: var(--border-width) solid var(--border-strong); border-radius: calc(var(--radius) * 1.236); } +.account-kit > span { display: grid; gap: 0.25rem; flex: 1; } +.account-kit small { display: block; margin-bottom: 0.5rem; } +.account-kit .primary { min-height: 2.25rem; font-size: var(--text-14); } +.account-group { margin: 1rem 0 0.125rem !important; padding: 0 0.625rem; color: var(--muted-foreground); font-size: 0.75rem; font-weight: 500; } +.account-panel .row { display: flex; align-items: center; justify-content: flex-start; gap: 0.75rem; width: 100%; min-height: 2.618rem; padding: 0.5rem 0.625rem; border: 0; border-radius: var(--radius-control); background: none; color: var(--foreground); font: inherit; text-align: start; cursor: pointer; transition: background var(--duration) var(--ease); } +.account-panel .row > span { display: grid; flex: 1; min-width: 0; } +.account-panel .row b { font-weight: 500; } +.account-panel .row > .glyph:first-child { color: var(--muted-foreground); } +.account-panel .row .chevron { width: 1rem; height: 1rem; color: var(--muted-foreground); opacity: 0.618; } .account-panel .row:hover { background: var(--accent); } -.account-panel .row:focus-visible, .account-panel .text:focus-visible, .account-close:focus-visible { outline: var(--ring-width) solid var(--ring); outline-offset: var(--ring-offset); } +.account-panel .row:focus-visible, .account-panel .text:focus-visible, .account-close:focus-visible, .account-icon:focus-visible { outline: var(--ring-width) solid var(--ring); outline-offset: var(--ring-offset); } .account-panel .primary { width: 100%; min-height: 2.618rem; font-size: 1rem; } .account-panel .account-in > p { margin-bottom: 0.618rem; color: var(--muted-foreground); } .account-panel .account-in > p b { color: var(--foreground); font-weight: 600; } diff --git a/frame/panels.mjs b/frame/panels.mjs index 5197171b..00b4d57b 100644 --- a/frame/panels.mjs +++ b/frame/panels.mjs @@ -450,7 +450,7 @@ function deviceStore(mode, work) { }); } export const loadDevice = () => deviceStore("readonly", (s) => s.get("self")).catch(() => null); -const saveDevice = (held) => deviceStore("readwrite", (s) => s.put(held, "self")); +const saveDevice = (held, workspace) => deviceStore("readwrite", (s) => (workspace && s.put(workspace, "workspace"), s.put(held, "self"))); const forgetDevice = () => deviceStore("readwrite", (s) => s.delete("self")); const loadKit = () => deviceStore("readonly", (s) => s.get("kit")).catch(() => null); const saveKit = (kit) => deviceStore("readwrite", (s) => s.put(kit, "kit")); @@ -461,6 +461,21 @@ const saveGuarding = (list) => deviceStore("readwrite", (s) => s.put(list, "guar // The recovery device this device gave a guardian, so the panel stops offering one. const loadGuarded = () => deviceStore("readonly", (s) => s.get("guarded")).catch(() => null); const saveGuarded = (recovery) => deviceStore("readwrite", (s) => s.put(recovery, "guarded")); +// An app's workspace key: 32 random bytes sealed under the id's private +// boundary key, so only a device of the id that made it opens it. The app +// seals its own records with the key; the frame keeps only the sealed key. +const loadWorkspace = () => deviceStore("readonly", (s) => s.get("workspace")).catch(() => null); +export async function openWorkspace(Prism, held, kept) { + if (kept && kept.prism !== held.prism) deny("removed", "This device was removed from the Prism ID that keeps this work"); + const value = kept ? await Prism.openPrivate(held, kept.sealed) : { key: Prism.toBase64Url(crypto.getRandomValues(new Uint8Array(32))) }; + const boundary = await Prism.currentBoundary(held).catch(() => (kept ? null : deny("stale-key", "This device is waiting for your Prism ID's newest key"))); + const record = boundary && kept?.sealed.key !== boundary.keyId ? { prism: held.prism, sealed: (await Prism.sealPrivate(held, value)).sealed } : null; + return { key: Prism.fromBase64Url(value.key), record }; +} +// Joining or recovering an id carries what the id this browser had kept; a +// removed device makes a new id and carries nothing, so its work stays locked. +export const carryWorkspace = async (Prism, kept, from, to) => + kept && from && kept.prism === from.prism ? { prism: to.prism, sealed: (await Prism.sealPrivate(to, await Prism.openPrivate(from, kept.sealed))).sealed } : null; // The bus to the id's other devices: stitch's relay (the frame's // PRISM_RELAY), which the page's connect-src must name; the page build reads @@ -542,12 +557,7 @@ function awaitOn(Prism, topic, kind, accept = () => true, ms = WAIT_MS) { const stop = () => (clearTimeout(timer), unsubscribe()); const found = new Promise((done, failed) => { unsubscribe = bus(Prism).subscribe(topic, (bytes) => { - let message; - try { - message = parse(bytes); - } catch { - return; - } + const message = parse(bytes); if (message?.kind === kind && accept(message)) done(message); }); timer = setTimeout(() => failed(new IdentityError("wait", "The other device did not answer in time. Try again")), ms); @@ -566,49 +576,65 @@ function drawQr(svg, { size, modules }) { } const json = (value) => new TextEncoder().encode(JSON.stringify(value)); -const parse = (bytes) => JSON.parse(new TextDecoder().decode(bytes)); +// A relay message as JSON, or null when it is not. +const parse = (bytes) => { + try { + return JSON.parse(new TextDecoder().decode(bytes)); + } catch { + return null; + } +}; const short = (id) => `${id.slice(0, 15)}…${id.slice(-4)}`; const sentence = (text) => (text ? text[0].toUpperCase() + text.slice(1) + (/[.!?]$/.test(text) ? "" : ".") : text); const KIND_LABEL = { browser: "Browser", native: "App", mobile: "Phone", embedded: "Device", recovery: "Recovery kit" }; +// Lucide's outline icons, drawn at the text colour, so the panel reads as the kit does everywhere else. +const glyph = (d, cls = "") => ``; +const [USER, LOCK, COPY, SHIELD, CHEVRON, CHECK, BACK] = ['', '', '', '', '', '', '']; +const [LAPTOP, PLUS, LOGIN, USERS, BUOY, HEART, KEY] = ['', '', '', '', '', '', '']; +// One choice: what it does, and in a line, why you would want it. +const row = (id, icon, what, why, hidden = false) => ``; + const ACCOUNT_PANEL = ` - + - + `; const TITLES = { - held: ["Prism id", "Every Prism app knows you by it. There is nothing to sign in to."], - kit: ["Prism id", "Save your recovery kit: if you lose every device, it brings your id back. Anyone holding it can take your id, so keep it offline."], - offer: ["Add a device or app", ""], - join: ["Use your Prism id here", ""], - recover: ["Use a recovery kit", ""], - devices: ["Devices", "Removing one stops it signing the next time it syncs."], - guard: ["Add a guardian", "Your new kit then needs them too: a lost or copied kit alone cannot bring your id back."], + held: ["Prism ID", "Every Prism app knows you by this ID. There is no password to remember and no account to make."], + offer: ["Add a device", ""], + join: ["Use an ID you already have", ""], + recover: ["Recover with a kit", ""], + devices: ["Your devices", "A device you remove can no longer act as you once it syncs."], + guard: ["Add a guardian", "Your new kit then needs them too, so a lost or copied kit alone cannot bring your ID back."], guardian: ["Be someone's guardian", ""], help: ["Help someone recover", ""], }; @@ -659,6 +684,7 @@ export function accounts(frame, core) { let link = null; let guarding = []; let guarded = false; + let working = false; const say = (words) => { frame.$("bar-status").textContent = words; @@ -671,18 +697,19 @@ export function accounts(frame, core) { function paint() { core.paint(); for (const name of ["held", "offer", "join", "recover", "devices", "guard", "guardian", "help"]) $(`view-${name}`).hidden = name !== view; - const [title, sub] = TITLES[view === "held" && kit ? "kit" : view]; + const [title, sub] = TITLES[view]; $("title").textContent = title; $("sub").textContent = sub; $("sub").hidden = !sub; - $("kit-save").hidden = !kit; + $("kit").hidden = !kit; for (const name of ["link", "devices", "guardian"]) $(name).hidden = !held; // A kit of one paper share can gain a guardian; one that has one cannot change it without them. $("guard").hidden = !held || guarded; $("help").hidden = !held || !guarding.length; $("back").hidden = view === "held"; - $("id").textContent = held ? short(held.prism) : "Making your Prism id"; + $("id").textContent = held ? short(held.prism) : "Making your Prism ID"; $("id").title = held?.prism ?? ""; + $("held").textContent = working ? "Your ID and your work, sealed on your devices" : "Held only on your devices"; } const show = (next) => { view = next; @@ -712,9 +739,9 @@ export function accounts(frame, core) { frame.$("account").classList.remove("busy"); } }; - const keep = async (Prism, next) => { + const keep = async (Prism, next, workspace) => { held = next; - await saveDevice(held); + await saveDevice(held, workspace); await share(Prism, held); }; @@ -807,12 +834,8 @@ export function accounts(frame, core) { const endLink = () => { link?.stop?.(); link = null; - $("ask").hidden = true; - $("help-check").hidden = true; + for (const id of ["ask", "help-check", "confirm", "accept", "join-code"]) $(id).hidden = true; $("code").value = ""; - $("confirm").hidden = true; - $("accept").hidden = true; - $("join-code").hidden = true; }; $("link").addEventListener("click", () => run(async (Prism) => { @@ -822,16 +845,10 @@ export function accounts(frame, core) { const topic = await Prism.rendezvousTopic(pending.offer.secret); link = { pending, topic, request: null }; link.stop = bus(Prism).subscribe(topic, (bytes) => { - let request; - try { - request = parse(bytes); - } catch { - return; - } + const request = parse(bytes); if (request?.kind !== Prism.KIND.request || !link || link.request) return; link.request = request; - $("confirm").hidden = false; - $("accept").hidden = false; + $("confirm").hidden = $("accept").hidden = false; $("code").focus(); }); $("offer").textContent = uri; @@ -864,12 +881,7 @@ export function accounts(frame, core) { const joined = new Promise((done, failed) => { link = { topic }; link.stop = bus(Prism).subscribe(topic, (bytes) => { - let response; - try { - response = parse(bytes); - } catch { - return; - } + const response = parse(bytes); if (response?.kind !== Prism.KIND.response) return; Prism.completeLink(device, offer, response).then(done, failed); }); @@ -880,7 +892,8 @@ export function accounts(frame, core) { $("join-code").hidden = false; panel.classList.remove("busy"); try { - await keep(Prism, await joined); + const next = await joined; + await keep(Prism, next, await carryWorkspace(Prism, await loadWorkspace(), held, next)); } finally { endLink(); } @@ -889,7 +902,7 @@ export function accounts(frame, core) { await forgetKit(); await session(Prism); show("held"); - say("This app uses your Prism id"); + say("This app uses your Prism ID"); }), ); @@ -935,13 +948,13 @@ export function accounts(frame, core) { const state = await Prism.resolvePrism(synced.prism, log).catch((error) => (error?.code === "fork" ? used() : Promise.reject(error))); const newer = state.active.filter((id) => state.roles[id] === "recovery" && id !== recovered.shares[0].recovery); if (newer.length || !(await Prism.canSign(synced.prism, log, synced.device.id))) used(); - await keep(Prism, synced); + await keep(Prism, synced, await carryWorkspace(Prism, await loadWorkspace(), held, synced)); await holdKit(recovered.shares[0]); await store("readwrite", (s) => s.delete("current")).catch(() => {}); accountChannel.session = null; await session(Prism); show("held"); - say("Prism id recovered"); + say("Prism ID recovered"); }), ); @@ -1100,14 +1113,13 @@ export function accounts(frame, core) { endLink(); show("held"); }); + // An icon button confirms with a check and says so; a word button says it in place. const copy = async (button, text) => { - try { - await navigator.clipboard.writeText(text); - button.textContent = "Copied"; - } catch { - button.textContent = "Select it"; - } - setTimeout(() => (button.textContent = "Copy"), 1600); + const was = button.innerHTML; + const done = await navigator.clipboard.writeText(text).then(() => "Copied", () => "Select it"); + if (button.classList.contains("account-icon")) (button.innerHTML = glyph(CHECK)), say(done); + else button.textContent = done; + setTimeout(() => (button.innerHTML = was), 1600); }; $("copy").addEventListener("click", () => copy($("copy"), held?.prism ?? "")); @@ -1123,8 +1135,19 @@ export function accounts(frame, core) { } }); + // { replace: true } starts a new key, for an app whose device was removed. + const workspace = async ({ replace = false } = {}) => { + const Prism = await prismId(); + await quietly(); + if (!held) deny("unsupported", "There is no Prism ID here yet"); + const { key, record } = await openWorkspace(Prism, held, replace ? null : await loadWorkspace()); + if (record) await saveDevice(held, record); + working = true; + paint(); + return key; + }; reach(); - return { reach }; + return { reach, workspace }; } // The theme panel's contents, which the frame puts in its empty panel. diff --git a/identity/PROTOCOL.md b/identity/PROTOCOL.md index e5b0d243..674b7c3e 100644 --- a/identity/PROTOCOL.md +++ b/identity/PROTOCOL.md @@ -136,6 +136,18 @@ topic derived from the prism id alone. `verifySession` passes the relay to a session from a device removed elsewhere is refused even when that device never synced. Making the session and recovery check the same merged log. +## An app's workspace key + +`frame.workspaceKey()` answers 32 bytes an app seals its own records with. The +frame makes them at random on first use, seals them with `sealPrivate` and +keeps `{prism, sealed}` in this origin's `prism-id` store under `workspace`; +the app never stores the key. A later call opens it with `openPrivate`, and +reseals it when the id's boundary key has rotated. Joining an id or recovering +one carries the key from the id this browser had (`carryWorkspace`), in the +same write that keeps the device. A key kept by another id is refused as +`removed`: this device was removed and made a new id. `{replace: true}` makes a +new key, for an app that starts again. + ## Not yet (stitch's to define, its docs/prism-id.md "Open") - Whoever holds a used paper kit (no guardian) can still sign a second diff --git a/identity/README.md b/identity/README.md index c32fbeaf..7ee0989b 100644 --- a/identity/README.md +++ b/identity/README.md @@ -48,6 +48,13 @@ share once. A lost or copied kit alone then brings nothing back. Add the guardian before saving the first kit, and no kit that works alone ever leaves the browser. +## Your work, sealed to your id + +An app can keep a visitor's work sealed to their id: the frame hands it a +key that only the id's devices open, and carries it when this app joins the +id from another device or recovers it. A device removed from the id cannot +open the work it kept. See PROTOCOL.md, "An app's workspace key". + ## Devices **Devices** lists the id's devices. **Remove** is stitch's `revokeDevice`, diff --git a/identity/test.mjs b/identity/test.mjs index a1df1008..62d68e0b 100644 --- a/identity/test.mjs +++ b/identity/test.mjs @@ -146,6 +146,9 @@ describe("the flow in Chromium", () => { let kitPath = null; const account = (p) => p.locator("prism-frame").evaluate((frame) => frame.account); + // The app's workspace key as bytes, or the refusal's code (FR-04). + const workspaceKey = (p, options) => p.locator("prism-frame").evaluate((frame, o) => frame.workspaceKey(o).then((key) => [...key], (error) => error.code), options); + let secondKey = null; const ready = (p) => p.locator("#account.signed-in").waitFor({ timeout: 15000 }); const newContext = async () => { const made = await browser.newContext({ acceptDownloads: true }); @@ -173,7 +176,7 @@ describe("the flow in Chromium", () => { test("the icon sits after full screen, and nothing asks to sign in", async () => { const order = await first.locator("prism-frame").evaluate((frame) => [...frame.shadowRoot.querySelector(".end").querySelectorAll("button")].map((b) => b.id)); assert.deepEqual(order.slice(-2), ["fullscreen", "account"]); - assert.equal(await first.locator("#account").getAttribute("aria-label"), "Prism id"); + assert.equal(await first.locator("#account").getAttribute("aria-label"), "Prism ID"); assert.equal(await first.locator("#account-panel").evaluate((panel) => panel.matches(":popover-open")), false); assert.equal(await account(first), null); }); @@ -186,8 +189,12 @@ describe("the flow in Chromium", () => { assert.equal(relay.requests, asked); assert.equal(await first.locator("#account-panel").evaluate((panel) => panel.matches(":popover-open")), false); firstId = (await account(first)).id; + const key = await workspaceKey(first); + assert.equal(key.length, 32); + assert.deepEqual(await workspaceKey(first), key); await first.locator("#account").click(); - assert.equal(await first.locator("#account-title").textContent(), "Prism id"); + assert.equal(await first.locator("#account-held").textContent(), "Your ID and your work, sealed on your devices"); + assert.equal(await first.locator("#account-title").textContent(), "Prism ID"); assert.equal(await first.getByText(/sign in/i).count(), 0); assert.equal(relay.requests, asked); const [download] = await Promise.all([first.waitForEvent("download"), first.locator("#account-kit-save").click()]); @@ -236,6 +243,7 @@ describe("the flow in Chromium", () => { }); test("another app joins the same id: a link, then the six-digit code", async () => { + secondKey = await workspaceKey(second); await second.locator("#account").click(); await second.locator("#account-join").click(); // On the first app: a link offer. @@ -258,6 +266,8 @@ describe("the flow in Chromium", () => { await first.locator("#account-accept").click(); await second.waitForFunction((id) => document.querySelector("prism-frame").account?.id === id, firstId, { timeout: 15000 }); assert.notEqual((await account(second)).key, (await account(first)).key); + // The work the second app kept under the id it had now opens under the joined id. + assert.deepEqual(await workspaceKey(second), secondKey); }); test("a removed app hears it on its next load and stops signing for the id", async () => { @@ -275,6 +285,9 @@ describe("the flow in Chromium", () => { await second.reload(); await second.mouse.click(5, 200); await second.waitForFunction((id) => { const a = document.querySelector("prism-frame").account; return a && a.id !== id; }, firstId, { timeout: 15000 }); + // A removed device keeps its work locked, and may start again with a new key. + assert.equal(await workspaceKey(second), "removed"); + assert.notDeepEqual(await workspaceKey(second, { replace: true }), secondKey); }); test("every device lost: the recovery kit brings the id back, and the kit is replaced", async () => { diff --git a/model/ids.toml b/model/ids.toml index 5867c30b..cbc5434d 100644 --- a/model/ids.toml +++ b/model/ids.toml @@ -873,3 +873,9 @@ id = "FA-92" level = "build" suite = "theater" statement = "Theater, right after Library in the sidebar, plays Prism apps one after another on a stage beside an up next rail, under the build preview's own sandbox, with the floor's catalogue, covers and bookmarks, and its look is the experience spec's five Theater statements" + +[[id]] +id = "FA-93" +level = "build" +suite = "private-workspace" +statement = "Studio keeps a visitor's work sealed to their Prism ID: each record is sealed as it is stored and opened as it is read, only as Foundry's Prism kernel answers; the work kept before moves in once; a removed device's work is cleared; and the visitor is told each outcome in one sentence" diff --git a/site/app.mjs b/site/app.mjs index c3438025..d05479b2 100644 --- a/site/app.mjs +++ b/site/app.mjs @@ -236,8 +236,6 @@ function spec() { addEventListener("hashchange", () => set(location.hash === "#spec")); addEventListener("keydown", (event) => { if (event.key === "Escape" && root.classList.contains("spec-open")) set(false); - const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName ?? ""); - if (event.key === "." && !typing && !event.metaKey && !event.ctrlKey && !event.altKey) set(!root.classList.contains("spec-open")); }); if (location.hash === "#spec") set(true, false); } diff --git a/studio/KERNEL_REV b/studio/KERNEL_REV index cf553775..692f3506 100644 --- a/studio/KERNEL_REV +++ b/studio/KERNEL_REV @@ -1,2 +1,2 @@ -https://raw.githubusercontent.com/UOR-Foundation/foundry/5f532f2352a8ca5c14c9d8aa1a1ddc9c311dcd66/studio/shell/kernel/kernel.holo -blake3:9735d1bc7ae4dda36feb6c0da4ec53c4e1ec0157eccadd466992974b6f78c156 +https://raw.githubusercontent.com/UOR-Foundation/foundry/62add15f4cc420a82593f65765b07f686b93c06b/studio/shell/kernel/kernel.holo +blake3:f1c50fb298367ed10e324ff9ccfa755bfc11603611be5e186b4abaf39a04da89 diff --git a/studio/experience/src/FoundryExperience.lex.tex b/studio/experience/src/FoundryExperience.lex.tex index 78fcc17a..bc4aacf3 100644 --- a/studio/experience/src/FoundryExperience.lex.tex +++ b/studio/experience/src/FoundryExperience.lex.tex @@ -127,6 +127,11 @@ parameters: [], result: String, body: "Theater answers the keys a viewer already knows, whenever the focus is not in a field or inside the app: f for full screen, t for wide view, and Shift with N for the next app. The address names the app on the stage, so a refresh or a shared link opens the same app." +definition{ + name: workspaceWords, + parameters: [], + result: String, + body: "A visitor's work is sealed to their Prism ID with no step of theirs, and Foundry speaks only when something changed, in one sentence that says why and what follows. After the one move: Your work is now sealed to your Prism ID. Only your devices can open it. On a removed device: This device was removed from your Prism ID, so the work it kept stays closed. You start fresh here. When the browser is full: Your browser's storage is full, so this was not saved. Remove an app you no longer need, then try again. When a record was altered: Some of your work was changed outside Foundry, so it was left closed. While the newest key has not arrived: This device is waiting for your Prism ID's newest key. Open Foundry on one of your other devices, then try again. Otherwise: Foundry could not reach your Prism ID, so your work stays closed for now. The Prism ID panel says it in one line: Your ID and your work, sealed on your devices." } \end{semanticmodule} \end{lexlean} diff --git a/studio/shell/host.js b/studio/shell/host.js index b6b1ca11..c8272851 100644 --- a/studio/shell/host.js +++ b/studio/shell/host.js @@ -90,7 +90,7 @@ const enc = new TextEncoder(), dec = new TextDecoder(); let core = null; const coreReady = inference.coreReady().then((c) => (core = c)); const kappa = inference.kappa; -const dbReady = inference.db(); +const dbReady = inference.workspace(); // The Prism R4 decision is read once, while the studio starts, so a first turn does not wait to fetch it. r4Spec().catch(() => {}); async function tx(store, mode, fn) { return storageRequest(await dbReady, store, mode, fn); } diff --git a/studio/shell/inference.js b/studio/shell/inference.js index b6909342..e4a5983c 100644 --- a/studio/shell/inference.js +++ b/studio/shell/inference.js @@ -1,4 +1,4 @@ -import {readUserSettings,replaceUserSettings,changeUserSettings} from "./settings-transactions.mjs"; +import {readUserSettings,replaceUserSettings} from "./settings-transactions.mjs"; // The page's adapters to the verified core, shared by the builder's host (host.js) and holo.html: core.wasm // through its JSON ABI, the view, addresses from the holospaces wasm, and the device store. Foundry's // language model is its reader in the kernel guest (host.js); no engine, weights or server are here. @@ -37,14 +37,9 @@ export let VIEW = null; export async function viewReady() { if (VIEW) return VIEW; const inline = document.getElementById("view"); VIEW = inline ? JSON.parse(inline.textContent) : (await coreReady()).run({ op: "view" }); return VIEW; } // ---- BLAKE3 addresses from the holospaces wasm (the same κ every daemon computes) -let kappaFn = null; -export async function kappaReady() { - if (kappaFn) return kappaFn; - const mod = await import(new URL("q/pkg/holospaces_web.js", BASE).href); - if (typeof mod.default === "function") { try { await mod.default(); } catch (e) {} } - kappaFn = (bytes) => String(mod.kappa(bytes)); - return kappaFn; -} +let holospaces = null; +const holospacesReady = () => (holospaces ??= import(new URL("q/pkg/holospaces_web.js", BASE).href).then(async (mod) => { if (typeof mod.default === "function") { try { await mod.default(); } catch (e) {} } return mod; })); +export async function kappaReady() { const mod = await holospacesReady(); return (bytes) => String(mod.kappa(bytes)); } export async function kappa(bytes) { return (await kappaReady())(bytes); } // ---- the device store: one database for the builder and the seals. Seals are rows keyed by κ, @@ -65,5 +60,120 @@ export function db() { }); } // ---- settings: the renderer's own record -export function settingsGet() { return readUserSettings(db()); } -export function settingsPut(s) { return replaceUserSettings(db(),s); } +export function settingsGet() { return readUserSettings(workspace()); } +export function settingsPut(s) { return replaceUserSettings(workspace(),s); } + +// ---- Prism ID: the Prism frame (frame/, locked by frame.lock; the renderer's build bundles it as +// assets/prism-frame.js) keeps the visitor's Prism ID. One frame serves the page. Its panel is a centred +// popover, so the element stays off screen, and it is told Studio's theme first, since a frame sets the page's. +export const prismFrame = (globalThis.__prismFrame ??= () => (globalThis.__prismFrameLoad ??= import(new URL("assets/prism-frame.js", BASE).href).then(() => { + localStorage.setItem("prism-theme", document.documentElement.classList.contains("dark") ? "dark" : "light"); + const frame = Object.assign(document.createElement("prism-frame"), { style: "position:fixed;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)" }); + return document.body.appendChild(frame); +}))); + +// ---- the visitor's work, sealed to their Prism ID (FA-93, verification/private-workspace.md). Each record +// is sealed with Hologram's seal_bytes under the workspace key the Prism frame keeps for this origin, which +// only a device of the visitor's Prism ID opens. seal_bytes is synchronous, so a record is sealed inside its +// own transaction and no writer changes. Foundry's Prism kernel (app/src/Workspace.lex.tex) decides whether +// the workspace opens, the one move of the work kept before it, and each read and store: it answers every +// case once, as the workspace opens. Left plain: what the service worker reads (the grants and published +// .holo bytes, public and addressed by their content) and the audit it writes. +const SEALED = new Set(["settings", "apps", "chats", "files", "objects", "refs", "versions"]); +const plainPlace = (store, key) => !SEALED.has(store) || (store === "refs" && /^(capabilities|holo):/.test(key)); +const isSealed = (value) => value?.sealedWork instanceof Uint8Array; +const word = (n) => [0, 8, 16, 24].map((shift) => ((n >>> shift) & 255).toString(16).padStart(2, "0")).join(""); +export const workspaceRequest = (...words) => "workspace " + [1, ...words].map(word).join(""); +const decide = (...words) => globalThis.__forgeKernel.ask(workspaceRequest(...words)); +// The facts the kernel opens on, from the frame's answer for the key: this device was removed, the session is +// live, the ID owns the workspace, the device holds the current key. +export const openFacts = (code) => [+(code === "removed"), +(!code || code === "removed" || code === "stale-key"), 1, +(code !== "stale-key")]; +const refusal = (code) => Object.assign(new Error(code), { code }); +// What the visitor is told, by the kernel's answer. The renderer says it (hologram.screens/AppSidebar.tsx), +// including what was told before it mounted. +export const tell = (answer) => { (globalThis.__workspaceTold ??= []).push(answer); window.dispatchEvent(new CustomEvent("foundry:workspace", { detail: answer })); }; +const base64 = (bytes) => { let text = ""; for (let i = 0; i < bytes.length; i += 32768) text += String.fromCharCode(...bytes.subarray(i, i + 32768)); return btoa(text); }; +const encode = (value) => enc.encode(JSON.stringify(value, function (name, v) { const raw = this[name]; return raw instanceof Uint8Array ? { $bytes: base64(raw) } : raw instanceof Date ? { $date: v } : v; })); +const decode = (bytes) => JSON.parse(new TextDecoder().decode(bytes), (name, v) => (v?.$bytes !== undefined ? Uint8Array.from(atob(v.$bytes), (c) => c.charCodeAt(0)) : v?.$date !== undefined ? new Date(v.$date) : v)); +const wrap = (target, own) => new Proxy(target, { get: (t, p) => (p in own ? own[p] : typeof t[p] === "function" ? t[p].bind(t) : t[p]), set: (t, p, v) => ((t[p] = v), true) }); +let workspaceOpen = null; +export const workspace = () => (workspaceOpen ??= openWorkspace()); +async function openWorkspace() { + const [mod, handle, frame] = await Promise.all([holospacesReady(), db(), prismFrame()]); + let secret = null, code = null; + try { secret = await frame.workspaceKey(); } catch (error) { code = error?.code ?? "unavailable"; } + let opened = await decide(0, ...openFacts(code)); + // A published .holo is public and checked by its address: the one plain record a sealed store may hold. + const published = (store, key, value) => store === "objects" && value instanceof Uint8Array && String(mod.kappa(value)) === key; + // A removed device's work is sealed under a key it no longer holds: it is cleared, with anything else kept + // where work belongs, so nothing left behind enters the new workspace, and the device starts again. + if (opened === "workspaceDeviceRemoved") { + await everyRecord(handle, "readwrite", (store, cursor) => plainPlace(store, cursor.key) || published(store, cursor.key, cursor.value) || cursor.delete()); + // The pictures of that work go too: built previews and covers, which the worker serves without the ID. + await Promise.all(["previews", "covers"].map((name) => caches.delete(name))); + secret = await frame.workspaceKey({ replace: true }); + tell(opened); + opened = await decide(0, ...openFacts(null)); + } + if (opened !== "ok") { tell(opened); throw refusal(opened); } + const reads = {}, stores = {}; + for (const a of [0, 1]) { stores[a] = await decide(2, 1, 1, a); for (const b of [0, 1]) reads[`${a}${b}`] = await decide(1, 1, a, b); } + const estimate = await navigator.storage?.estimate?.().catch(() => null); + let usage = estimate?.usage ?? 0; + const quota = estimate?.quota ?? Infinity; + navigator.storage?.persist?.().catch(() => {}); + const place = (store, key) => JSON.stringify([store, key]); + const seal = (store, key, value) => { + if (plainPlace(store, key)) return value; + const bytes = encode([place(store, key), value]); + const answer = stores[+(usage + bytes.length < quota)]; + if (answer !== "ok") { tell(answer); throw refusal(answer); } + usage += bytes.length; + return { sealedWork: mod.seal_bytes(secret, bytes) }; + }; + const open = (store, key, value) => { + if (value === undefined || plainPlace(store, key) || published(store, key, value)) return value; + let authentic = 0, bound = 0, kept; + try { const [where, inner] = decode(mod.open_bytes(secret, value.sealedWork)); [authentic, bound, kept] = [1, +(where === place(store, key)), inner]; } catch {} + const answer = reads[`${authentic}${bound}`]; + if (answer === "ok") return kept; + tell(answer); + }; + // The one move: every record kept before the workspace is sealed in place, in one transaction, so its plain + // copy is gone exactly when the sealed copy commits. A published .holo's own bytes stay as they are. + const moved = (await readOne(handle, "refs", "workspace:moved")) !== undefined; + if ((await decide(3, 1, +moved)) === "ok") { + const holos = new Set((await readKeys(handle, "refs")).filter((k) => typeof k === "string" && k.startsWith("holo:")).map((k) => k.slice(5))); + let count = 0; + await everyRecord(handle, "readwrite", (store, cursor) => { + if (isSealed(cursor.value) || plainPlace(store, cursor.key) || (store === "objects" && holos.has(cursor.key))) return; + cursor.update(seal(store, cursor.key, cursor.value)); + count += 1; + }, (tx) => tx.objectStore("refs").put(seal("refs", "workspace:moved", true), "workspace:moved")); + if (count) tell("workspaceMoved"); + } + const request = (req, read) => wrap(req, { get result() { return read(req.result); } }); + const objectStore = (name, s) => wrap(s, { + get: (key) => request(s.get(key), (v) => open(name, key, v)), + put: (v, key) => s.put(seal(name, key, v), key), + add: (v, key) => s.add(seal(name, key, v), key), + getAll: (range, count) => { const keys = s.getAllKeys(range, count); return request(s.getAll(range, count), (vs) => vs.map((v, i) => open(name, keys.result[i], v)).filter((v) => v !== undefined)); }, + openCursor: (range, direction) => request(s.openCursor(range, direction), (c) => c && wrap(c, { get value() { return open(name, c.key, c.value); }, update: (v) => c.update(seal(name, c.key, v)) })), + }); + return wrap(handle, { transaction: (...args) => { const tx = handle.transaction(...args); return wrap(tx, { objectStore: (name) => objectStore(name, tx.objectStore(name)) }); } }); +} +// One transaction over every sealed store, visiting each record; `last` adds a write before it commits. +function everyRecord(handle, mode, visit, last) { + return new Promise((done, fail) => { + const tx = handle.transaction([...SEALED], mode); + let left = SEALED.size; + for (const store of SEALED) { + const walk = tx.objectStore(store).openCursor(); + walk.onsuccess = () => { const cursor = walk.result; if (cursor) { visit(store, cursor); cursor.continue(); } else if (!--left && last) last(tx); }; + } + tx.oncomplete = () => done(); + tx.onerror = tx.onabort = () => fail(tx.error ?? refusal("storageTransactionFailed")); + }); +} +const readOne = (handle, store, key) => new Promise((done, fail) => { const r = handle.transaction(store).objectStore(store).get(key); r.onsuccess = () => done(r.result); r.onerror = () => fail(r.error); }); +const readKeys = (handle, store) => new Promise((done, fail) => { const r = handle.transaction(store).objectStore(store).getAllKeys(); r.onsuccess = () => done(r.result); r.onerror = () => fail(r.error); }); diff --git a/studio/shell/kernel/guest.wasm b/studio/shell/kernel/guest.wasm index 70cb7d3ff75ee7ad51cf2efb03513843eac66110..3e89c4d0aaf2526caa02cddb712a298db1abfd7f 100644 GIT binary patch delta 4600 zcmb7H3vg7`8NT1Sdw1`?k_#pwF^G3#fkefi74cD&yBM@}1aVqhiLIFGD6uG|6dy%4 zJfaXNpqp?Kl2$-Q9neTv>lH^7rivJGP(}@q2#H}uBmp6*sEG7GckkWZK36#`hPngpVaoZ6J41=aaeda~Q15&2PY>QX zWbARs5o;$aqLeiOWdAW|Tx-fhi^R>Cr zTx~&eXRz4GwRd7o+HYl4#=Kb<$>@xY8uV+1MX{>9dNB+ee4#?aq|lX|$x$`oz9>TVGk)wxN^O zQo!#w1`*C63nyZ+cuD_&bhVU2=Dj5$}4K#Gpjz`(ABT9>NhfpI5S1;wjIf!u}3%( z5MYltog_!jj)cc=L^22pH9uy3ZnZ(Qy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^)bI$I9Pa^FFrf(?Zti!Q)wT@ z@~)~czRT{%IL^7DAK!7Z_rWvR!*8I{vslSy_gUP+=KgaiB;y>eve&n#*5yf;eES?C z8EB>32CxRL@`C|1x^kM5U$B7sPGz?kO>)67zP(Xg7(*TF#XQnT?J1n=sP!Y$K88iGYT0kNMC#@!NHNQe)B(AM+dQBu#^cj99 zBZ)MUPmGFQ%ETX8H|^dazII1^7I9(`62_IVx}4wTqJ-s`EQ(A~!9_$Om?8q~GQ%b( z`M9-1DkBg!`c;j}X<938@n@Q1qGJLDH;P;?Gi#HWc3Fnk$_v8EOP1>5Qfbvjas326 z-YxgbheOsO$4o_9<`~PkCETkZyh_;u>rD8@ohAiBL)J|pI*5z|y(2sq;> z_~0j-L^129D&pO&_S7y@m0@C>wwtQkMP4!|<=yvr?TE)=HIbekU2XZnpTqr`Ehln4o>1iVJGN^p2hm*xI>P-jnaC7*jn?7@El_jYAt diff --git a/studio/shell/kernel/kernel.holo b/studio/shell/kernel/kernel.holo index 78c00b0955a1834a86f6122696e2bc915437e6bb..fda75bfd2890930a9378373fb4c4b737db1b612e 100644 GIT binary patch delta 8232 zcmds4dvp|4ny;^_yVFT`C!GO8A}XCI5-@?P>Utt#Itt^?xQZUfagIl!s;gQafgl7u z=wc@*B7zRshU<%291SQhfvlD|gW~Rh8ea^9iZ2F4d@Ld_6&b+U?^bmuAtAV~{@Gns|Hvq(Bn5MFp_%tdz65Rw9Ksn5L!o1$u@1W^!pF)qg~(XfP+B1(pt zvIWi5MN5q*bs=sgk=W35HB-p-%{!4RZ~!G4fmQ! z6^+wv)j)qF+$9JiW>myDiJGiwqF@Md5rbrDlBwGmV^u)7o9(I7#@A1-7$(ge!HjEY zm@;kH(4ph%>*_Oq@E!cA(rA6tUkBI7mAasx}a;Bqj_(pt8S~9XiS-6U~J7g zW1<}&_7lb2jZ9GEab25v{Y;@fI@9Z?4oTHdpKKYKkAlO~nr!jBty}Swsab|;>zbvQ zdJ^*?>AYZwk|mp#jpC9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Z0Xy;W#KP_PUw!8OnZ#GPSay1Z2 zUayI$WdN(D@;`(Eon+*rv}8BVqw_z+-Dyid_GfO>K=yP;Af7K`OCS)bs}w3`kNMFz z^rI5C1cv@xa=0ToxC=RUA97EZvUm7n2a|o5iMRTyVv*;gEp5w_uuO|ZqOGnyoUMvd zd^h_K=soY<%`Wsh>E!WjJv!s=8_)g(^-8twKs;I%3luTf`$>;}OWVfKN={qJn09F@Lt1T8g z2y{NM*x>c!9EB>c_n)j3`Q07ldYBP)$Q}IE}H9AY$5u>1)V3tXazk# zi+u!MXsc@3`-7Q_+TNep-b=FklIS8gYaV;u6U-M`bWCQXJS&DqX82+#3TlnMg5byu zKYcYb5*zGi%3=Z73B`gj^c8&5rZHt8LUDX^hA)oW^ur@Ff;1~DQiKBZx~#}R6r^TW zgc}h^>wpZ6%m@Gy(}|SMblLs3C3xLqTHYg)duK8)NyAJL6D>gTZGl^X6chI;OkRu` z0i+unk;-I)C{`5%rF3v}yQh&|6+Q0xJ=H*Bb*lR zm5<`RI=v52B|9P)hmziczi_xHzTG#paA3D9w%xK%o>O zPK)ONVooPwr>RRe0?89_@X4N${t!Qp5v;!KT(KUF7#if?*wQP~t4*at_|io}K9rV< z0E)hsayq^iK|CNR(cgQ5==SzltVLch!nCztB!}LU6X||;C@qfiLvdd|Y6A&D@{YFa zCu0}jE;b@ms=F#VJBl*KpDeDayjTp!R z4Vs`QOyAw+NP8_^0co1WTyl;y! z-#b470$z{@=|d^By1d9}i1RCXk-TbE8lB4WsA~fBNd7lW6?Ood<5Je3af=Gw)CL{0F7X BKlcCt diff --git a/studio/shell/kernel/kernel.json b/studio/shell/kernel/kernel.json index 61e39233..df05305d 100644 --- a/studio/shell/kernel/kernel.json +++ b/studio/shell/kernel/kernel.json @@ -1,12 +1,12 @@ { "spec": "hologram-forge/kernel/1", "application": "Forge kernel", - "source": "https://raw.githubusercontent.com/UOR-Foundation/foundry/5f532f2352a8ca5c14c9d8aa1a1ddc9c311dcd66/studio/shell/kernel/kernel.holo", - "digest": "blake3:9735d1bc7ae4dda36feb6c0da4ec53c4e1ec0157eccadd466992974b6f78c156", + "source": "https://raw.githubusercontent.com/UOR-Foundation/foundry/62add15f4cc420a82593f65765b07f686b93c06b/studio/shell/kernel/kernel.holo", + "digest": "blake3:f1c50fb298367ed10e324ff9ccfa755bfc11603611be5e186b4abaf39a04da89", "guest": { "path": "kernel/guest.wasm", - "sha256": "e99c9e85bc4af6a1feffae955b2100b0ab88dac12624f8c8ceabf731685a4bbb", - "bytes": 171547 + "sha256": "bfd8947b93c43bd5941b73dc69c48e7cd06571e5b771b3a20448b876463c52e6", + "bytes": 173398 }, "limits": { "request": 32776, @@ -62,6 +62,82 @@ "cnVsZSAwMTAwMDAwMDAyMDAwMDAwMDAwMDAwMDAxODAwMDAwMDAwMDAwMDAwMDEwMDAwMDAwMTAwMDAwMDAyMDAwMDAwMDEwMDAwMDAwMDAwMDAwMDAxMDAwMDAwMDQwMDAwMDAwMTAwMDAwMDAxMDAwMDAwMDIwMDAwMDAwMDAwMDAwMDAyMDAwMDAwMDMwMDAwMDAwNTAwMDAwMDAxMDAwMDAwMDAwMDAwMDA=", "bWFsZm9ybWVkUnVsZVJlcXVlc3Q=" ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAxMDAwMDAwMDEwMDAwMDAwMTAwMDAwMA==", + "b2s=" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDAwMDAwMDAwMTAwMDAwMDAxMDAwMDAwMDEwMDAwMDAwMTAwMDAwMA==", + "d29ya3NwYWNlRGV2aWNlUmVtb3ZlZA==" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDEwMDAwMDAwMTAwMDAwMA==", + "d29ya3NwYWNlU2Vzc2lvbkV4cGlyZWQ=" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAxMDAwMDAwMDAwMDAwMDAwMTAwMDAwMA==", + "d29ya3NwYWNlTm90T3duZXI=" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAxMDAwMDAwMDEwMDAwMDAwMDAwMDAwMA==", + "d29ya3NwYWNlS2V5U3RhbGU=" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDEwMDAwMDAwMTAwMDAwMDAxMDAwMDAwMDEwMDAwMDA=", + "b2s=" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDEwMDAwMDAwMDAwMDAwMDAxMDAwMDAwMDEwMDAwMDA=", + "d29ya3NwYWNlQ2xvc2Vk" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDEwMDAwMDAwMTAwMDAwMDAwMDAwMDAwMDEwMDAwMDA=", + "cmVjb3JkVGFtcGVyZWQ=" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDEwMDAwMDAwMTAwMDAwMDAxMDAwMDAwMDAwMDAwMDA=", + "cmVjb3JkTWlzcGxhY2Vk" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDIwMDAwMDAwMTAwMDAwMDAxMDAwMDAwMDEwMDAwMDA=", + "b2s=" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDIwMDAwMDAwMTAwMDAwMDAwMDAwMDAwMDEwMDAwMDA=", + "cmVjb3JkVW5zZWFsZWQ=" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDIwMDAwMDAwMTAwMDAwMDAxMDAwMDAwMDAwMDAwMDA=", + "d29ya3NwYWNlUXVvdGFFeGNlZWRlZA==" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDMwMDAwMDAwMTAwMDAwMDAwMDAwMDAw", + "b2s=" + ], + [ + "d29ya3NwYWNlIDAxMDAwMDAwMDMwMDAwMDAwMTAwMDAwMDAxMDAwMDAw", + "d29ya3NwYWNlQWxyZWFkeU1vdmVk" + ], + [ + "d29ya3NwYWNl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AwMDAwMDcwMDAwMDAwODAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMA==" diff --git a/studio/tools/atomic_chat_preferences_browser.mjs b/studio/tools/atomic_chat_preferences_browser.mjs index 7ff8d32b..8ff910bd 100644 --- a/studio/tools/atomic_chat_preferences_browser.mjs +++ b/studio/tools/atomic_chat_preferences_browser.mjs @@ -39,7 +39,7 @@ try { await Promise.all([call(page,'update-chat',{chatId,title:'',chatMode:'ask'}),call(peer,'update-chat',{chatId,modelSelection})]); const row=await get(page,'chats',chatId);assert.equal(row.title,'');assert.equal(row.chatMode,'ask');assert.deepEqual(row.modelSelection,modelSelection); await Promise.all([call(page,'update-chat',{chatId,title:'Concurrent'}),peer.evaluate(async chatId=>{ - const {updateStoredChat}=await import('./project-lifecycle.mjs');const {db:open}=await import('./inference.js'); + const {updateStoredChat}=await import('./project-lifecycle.mjs');const {workspace:open}=await import('./inference.js'); const db=await open(); await updateStoredChat(db,chatId,{messages:[{id:1,role:'user',content:'preserved transcript',approvalState:null,commitHash:null,createdAt:new Date().toISOString()}]}); },chatId)]); diff --git a/studio/tools/canonical_build_closure_browser.mjs b/studio/tools/canonical_build_closure_browser.mjs index bf2556ee..1378e725 100644 --- a/studio/tools/canonical_build_closure_browser.mjs +++ b/studio/tools/canonical_build_closure_browser.mjs @@ -39,7 +39,7 @@ try { const versions = () => window.__host.get("versions", appId); const snapshot = async () => JSON.stringify(await Promise.all([get("prism/spec.json"), window.__host.all("files"), window.__host.get("refs", appId + ":main"), window.__host.get("refs", "prism:" + appId), versions()])); const module = "prism/" + lexlean.canonicalSource(fixture).name + ".lex.tex"; - const { db } = await import(new URL("inference.js",location.href)); + const { workspace: db } = await import(new URL("inference.js",location.href)); const { captureBuildSource } = await import(new URL("build-source.mjs",location.href)); const boundary = {derive:window.__host.kappa,readObject:key=>window.__host.get("objects",key),admit:(derived,expected)=>window.__host.core().run({op:"restore",derived,expected}).decision === "Accept"}; const canonical = await captureBuildSource(await db(),appId,boundary); diff --git a/studio/tools/durable_build_work_browser.mjs b/studio/tools/durable_build_work_browser.mjs index 6b6e7f1d..223c72e3 100644 --- a/studio/tools/durable_build_work_browser.mjs +++ b/studio/tools/durable_build_work_browser.mjs @@ -64,7 +64,7 @@ try { assert.equal((await journal()).records[1].state.phase,1); await start();await dialog().getByRole('button',{name:'Build this source'}).click();assert.ok((await outcome()).value?.html);state=await journal();assert.equal(state.records.length,2);assert.equal(state.records[1].attempts,2);assert.equal(state.records[1].state.phase,3);assert.notEqual(state.records[1].state.owner,interrupted.records[1].state.owner); const transactionReport=await page.evaluate(async appId=>{ - const {db}=await import(new URL('inference.js',location.href)),{captureProjectSource}=await import(new URL('project-edit.mjs',location.href)),{buildWorkStore}=await import(new URL('build-work.mjs',location.href));const database=await db(),captured=await captureProjectSource(database,appId),store=buildWorkStore(database,appId,captured),before=await store.read(); + const {workspace:db}=await import(new URL('inference.js',location.href)),{captureProjectSource}=await import(new URL('project-edit.mjs',location.href)),{buildWorkStore}=await import(new URL('build-work.mjs',location.href));const database=await db(),captured=await captureProjectSource(database,appId),store=buildWorkStore(database,appId,captured),before=await store.read(); const first=structuredClone(before);first.records[0].attempts++;const second=structuredClone(before);second.records[0].attempts+=2; const results=await Promise.allSettled([store.save(before,first),store.save(before,second)]);if(results.filter(r=>r.status==='fulfilled').length!==1||!results.some(r=>r.status==='rejected'&&r.reason.code==='buildWorkConflict'))throw Error('work comparison failed'); const originalTransaction=database.transaction,prior=await store.read();database.transaction=function(...args){const t=originalTransaction.apply(this,args);if(args[1]==='readwrite'){const originalStore=t.objectStore.bind(t);t.objectStore=name=>{const s=originalStore(name);if(name==='refs'){const put=s.put.bind(s);s.put=(value,key)=>{const q=put(value,key);if(key===`work:${appId}`)queueMicrotask(()=>{try{t.abort();}catch{}});return q;};}return s;};}return t;}; diff --git a/studio/tools/durable_event_delivery_browser.mjs b/studio/tools/durable_event_delivery_browser.mjs index 52d446a5..18885e73 100644 --- a/studio/tools/durable_event_delivery_browser.mjs +++ b/studio/tools/durable_event_delivery_browser.mjs @@ -57,7 +57,7 @@ try { const updated=structuredClone(context);updated.generation=4;updated.envelope.generation=4; check((await call("forge:event-configure",{appId,context:updated})).ok,"new generation cannot configure"); check((await call("forge:event-deliver",{appId,envelope:updated.envelope})).ok,"new generation cannot deliver"); - const {db}=await import(new URL("inference.js",location.href)); + const {workspace:db}=await import(new URL("inference.js",location.href)); const {updateEventJournal}=await import(new URL("event-delivery.mjs",location.href)); const database=await db(),guest=await window.ForgeKernel.load(path=>fetch(new URL(path,location.href))); let arrivals=0,release;const barrier=new Promise(resolve=>release=resolve); diff --git a/studio/tools/durable_theme_library_browser.mjs b/studio/tools/durable_theme_library_browser.mjs index 2de9df2d..d5b4ea7d 100644 --- a/studio/tools/durable_theme_library_browser.mjs +++ b/studio/tools/durable_theme_library_browser.mjs @@ -50,8 +50,8 @@ try { const late=await page.evaluate(async()=>{const put=IDBObjectStore.prototype.put;let injected=false;IDBObjectStore.prototype.put=function(value,key){const q=put.call(this,value,key);if(this.name==='settings'&&key==='foundry:themes:v1'){injected=true;q.addEventListener('success',()=>this.transaction.abort(),{once:true});}return q;};try{await window.electron.ipcRenderer.invoke('delete-custom-theme',{id:1});return {injected,refused:false};}catch(e){return {injected,refused:e.code==='themeStorageFailed'};}finally{IDBObjectStore.prototype.put=put;}});assert.deepEqual(late,{injected:true,refused:true});assert.deepEqual(await get(page,'settings',key),before);assert.equal(await call(peer,'get-app-theme',{appId:9901}),'custom:1'); const bad=structuredClone(before);bad.records[0].createdAt='invalid';await page.evaluate(({key,bad})=>window.__host.put('settings',key,bad),{key,bad});await assert.rejects(()=>call(peer,'get-custom-themes'));await assert.rejects(()=>call(peer,'get-app-theme',{appId:9901}));assert.deepEqual(await get(page,'settings',key),bad);await page.evaluate(({key,before})=>window.__host.put('settings',key,before),{key,before}); // The real transaction adapter captures before database readiness. - const capture=await page.evaluate(async base=>{const {createThemeLibrary}=await import(base+'theme-library.mjs'),{themesData}=await import(base+'builtin-themes.mjs'),inference=await import(base+'inference.js');let ready;const call=createThemeLibrary(new Promise(r=>ready=r),themesData),value={name:'Captured',prompt:'original'};const pending=call('create',value);value.prompt='changed';ready(await inference.db());return (await pending).prompt;},base);assert.equal(capture,'original'); - const captured=await page.evaluate(async base=>{const {createThemeLibrary}=await import(base+'theme-library.mjs'),{themesData}=await import(base+'builtin-themes.mjs'),inference=await import(base+'inference.js');return createThemeLibrary(await inference.db(),themesData)('resolve',{appId:9901});},base);assert.equal(captured,input.prompt); + const capture=await page.evaluate(async base=>{const {createThemeLibrary}=await import(base+'theme-library.mjs'),{themesData}=await import(base+'builtin-themes.mjs'),inference=await import(base+'inference.js');let ready;const call=createThemeLibrary(new Promise(r=>ready=r),themesData),value={name:'Captured',prompt:'original'};const pending=call('create',value);value.prompt='changed';ready(await inference.workspace());return (await pending).prompt;},base);assert.equal(capture,'original'); + const captured=await page.evaluate(async base=>{const {createThemeLibrary}=await import(base+'theme-library.mjs'),{themesData}=await import(base+'builtin-themes.mjs'),inference=await import(base+'inference.js');return createThemeLibrary(await inference.workspace(),themesData)('resolve',{appId:9901});},base);assert.equal(captured,input.prompt); await call(peer,'update-custom-theme',{id:1,prompt:'THEME-CHANGED'});assert.equal(captured,input.prompt); await page.evaluate(()=>window.__host.put('apps',9903,{id:9903,name:'Second',themeId:'custom:1'})); await call(page,'delete-custom-theme',{id:1});assert.equal(await call(peer,'get-app-theme',{appId:9901}),null);assert.equal(await call(peer,'get-app-theme',{appId:9903}),null);assert.equal((await call(peer,'get-custom-themes')).length,3); diff --git a/studio/tools/durable_version_preview_browser.mjs b/studio/tools/durable_version_preview_browser.mjs index 10db81fa..4a9dac1f 100644 --- a/studio/tools/durable_version_preview_browser.mjs +++ b/studio/tools/durable_version_preview_browser.mjs @@ -61,8 +61,8 @@ try { assert.equal((await get(peer,'refs',`preview:${appId}`)).state.active,0); // Simulate a separately committed, valid source while the owner previews history. // Recovery must preserve those bytes until an explicit accept/checkpoint decision. - const capture=tab=>tab.evaluate(async appId=>{const {db}=await import('./inference.js');const {captureProjectSource}=await import('./project-edit.mjs');return captureProjectSource(await db(),appId);},appId); - const replaceSource=(tab,source)=>tab.evaluate(async({appId,source})=>{const {db}=await import('./inference.js');const database=await db();await new Promise((resolve,reject)=>{const tx=database.transaction(['files','refs'],'readwrite');tx.oncomplete=resolve;tx.onabort=()=>reject(Error('fixture source transaction aborted'));const files=tx.objectStore('files');files.delete(IDBKeyRange.bound(appId+':',appId+':￿'));for(const [name,text] of source.files)files.put(text,appId+':'+name);tx.objectStore('refs').put(source.reference,appId+':main');});},{appId,source}); + const capture=tab=>tab.evaluate(async appId=>{const {workspace:db}=await import('./inference.js');const {captureProjectSource}=await import('./project-edit.mjs');return captureProjectSource(await db(),appId);},appId); + const replaceSource=(tab,source)=>tab.evaluate(async({appId,source})=>{const {workspace:db}=await import('./inference.js');const database=await db();await new Promise((resolve,reject)=>{const tx=database.transaction(['files','refs'],'readwrite');tx.oncomplete=resolve;tx.onabort=()=>reject(Error('fixture source transaction aborted'));const files=tx.objectStore('files');files.delete(IDBKeyRange.bound(appId+':',appId+':￿'));for(const [name,text] of source.files)files.put(text,appId+':'+name);tx.objectStore('refs').put(source.reference,appId+':main');});},{appId,source}); await call(peer,'edit-app-file',{appId,filePath:'recovery.txt',content:'external committed source'}); const external=await capture(peer); await call(peer,'edit-app-file',{appId,filePath:'recovery.txt',content:'owner original source'}); diff --git a/studio/tools/home_card_keyboard.test.mjs b/studio/tools/home_card_keyboard.test.mjs index 88dedd75..31d649ff 100644 --- a/studio/tools/home_card_keyboard.test.mjs +++ b/studio/tools/home_card_keyboard.test.mjs @@ -87,9 +87,14 @@ const compiled = ts.transpileModule(`${source}\nexport { Card, Keep };`, { }); assert.deepEqual(compiled.diagnostics, []); const module = { exports: {} }; -// The module also holds Theater (FA-92), whose hooks the card under test never calls. -const unusedImports = new Set(["@tanstack/react-router", "jotai", "@/atoms/chatAtoms", "@/hooks/useLoadApps", "@/hooks/useOpenApp", - "@/hooks/useRunApp", "@/hooks/useAppRun", "@/hooks/useAppThumbnails", "@/components/ui/button", "@/lib/utils", "@/lib/sortApps", "../../hologram.featured-apps.mjs"]); +const unusedImports = new Set([ + "@tanstack/react-router", + "@/hooks/useLoadApps", + "@/hooks/useOpenApp", + "@/hooks/useAppThumbnails", + "@/lib/sortApps", + "../../hologram.featured-apps.mjs", +]); vm.runInNewContext( compiled.outputText, { diff --git a/studio/tools/in_tab_kernel_verdict.test.mjs b/studio/tools/in_tab_kernel_verdict.test.mjs index 72814dc5..353940f3 100644 --- a/studio/tools/in_tab_kernel_verdict.test.mjs +++ b/studio/tools/in_tab_kernel_verdict.test.mjs @@ -87,20 +87,35 @@ test('the model, the protocol and the kernel name one authority, and the authore // The tests above speak to a stand-in. This one asks the guest the studio ships. A pin that lags the model (the // guest of an earlier build archived under a later source) answers `invalid` here and passed everything above. -test('the pinned guest, the bytes the studio runs, answers every vector of the corpus', async () => { +async function pinnedGuest() { const bytes = fs.readFileSync(new URL('../shell/kernel/guest.wasm', import.meta.url)), meta = JSON.parse(read('../shell/kernel/kernel.json')); // The file asked is the one the Kernel gate names, not another build beside it. assert.equal(createHash('sha256').update(bytes).digest('hex'), meta.guest.sha256); const module = await WebAssembly.compile(bytes); - const dispatch = async (request) => { + return async (request) => { const { memory, holo_alloc, holo_run } = (await WebAssembly.instantiate(module, {})).exports, at = holo_alloc(request.length); new Uint8Array(memory.buffer, at, request.length).set(request); const packed = BigInt.asUintN(64, BigInt(holo_run(at, request.length))); return new Uint8Array(memory.buffer, Number(packed >> 32n), Number(packed & 0xffffffffn)).slice(); }; +} +test('the pinned guest, the bytes the studio runs, answers every vector of the corpus', async () => { + const dispatch = await pinnedGuest(); let asked = 0; for (const v of vectors) { assert.equal(dec.decode(await dispatch(enc.encode(v.request))), v.response, v.name); asked++; } assert.equal(asked, 19); assert.deepEqual(await verdictWithGuest({ dispatch }, proved.input), { ok: true, code: 0, verdict: 'proved' }); assert.deepEqual(await verdictWithGuest({ dispatch }, { ...structuredClone(proved.input), leanAccepted: 0 }), { ok: true, code: 3, verdict: 'refused' }); }); + +// FA-93: every request Studio's sealed store makes, built by its own code, asked of the guest it pins, and the +// answer each case must have for Studio to do what it does (studio/shell/inference.js, openWorkspace). +test('the pinned guest answers every workspace request Studio makes, as Studio acts on it (FA-93)', async () => { + const { workspaceRequest, openFacts } = await import('../shell/inference.js'); + const dispatch = await pinnedGuest(); + const ask = async (...words) => dec.decode(await dispatch(enc.encode(workspaceRequest(...words)))); + assert.deepEqual(await Promise.all([null, 'removed', 'stale-key', 'unsupported'].map((code) => ask(0, ...openFacts(code)))), ['ok', 'workspaceDeviceRemoved', 'workspaceKeyStale', 'workspaceSessionExpired']); + assert.deepEqual(await Promise.all([[1, 1], [1, 0], [0, 1], [0, 0]].map(([authentic, bound]) => ask(1, 1, authentic, bound))), ['ok', 'recordMisplaced', 'recordTampered', 'recordTampered']); + assert.deepEqual(await Promise.all([1, 0].map((within) => ask(2, 1, 1, within))), ['ok', 'workspaceQuotaExceeded']); + assert.deepEqual(await Promise.all([0, 1].map((moved) => ask(3, 1, moved))), ['ok', 'workspaceAlreadyMoved']); +}); diff --git a/studio/tools/preview_permissions_browser.mjs b/studio/tools/preview_permissions_browser.mjs index a3b5cc43..bcf6e7f9 100644 --- a/studio/tools/preview_permissions_browser.mjs +++ b/studio/tools/preview_permissions_browser.mjs @@ -53,7 +53,7 @@ try { assert.equal(await page.locator("#permission-test-frame").getAttribute("src"),"about:blank"); const revoked=await page.evaluate(id=>window.__host.get("refs","capabilities:"+id),previewId);assert.equal(revoked.serve,false);assert.deepEqual(revoked.network.endpoints,[]); const stale=await page.evaluate(async({id,record})=>{ - const {commitPreviewPermission}=await import(new URL("preview-permissions.mjs",location.href));const {db}=await import(new URL("inference.js",location.href)); + const {commitPreviewPermission}=await import(new URL("preview-permissions.mjs",location.href));const {workspace:db}=await import(new URL("inference.js",location.href)); try {await commitPreviewPermission(await db(),id,{disclosure:{id,source:record.previewConsent.source,endpoints:record.network.endpoints},expires:Date.now()+10000},record);return "accepted";}catch(error){return error.code;} },{id:previewId,record:initial});assert.equal(stale,"previewPermissionChanged"); await permissions.getByRole("button",{name:"Close permissions"}).click(); diff --git a/studio/tools/read_only_chat_execution_browser.mjs b/studio/tools/read_only_chat_execution_browser.mjs index b9b23f0b..1aacb45d 100644 --- a/studio/tools/read_only_chat_execution_browser.mjs +++ b/studio/tools/read_only_chat_execution_browser.mjs @@ -38,7 +38,7 @@ try { await call(page,'set-user-settings',{selectedModel:DEVICE_MODEL}); await page.evaluate(({appId,spec})=>window.__prism.rulesAfterTurn(appId,''+JSON.stringify(spec)+''),{appId,spec:fixture('rsvp')}); const snapshot=()=>page.evaluate(async appId=>{ - const {captureProjectSource}=await import('./project-edit.mjs'),{db}=await import('./inference.js'); + const {captureProjectSource}=await import('./project-edit.mjs'),{workspace:db}=await import('./inference.js'); const source=await captureProjectSource(await db(),appId); return {source,rules:await window.__prism.rulesOf(appId),versions:await window.__host.get('versions',appId),preview:await window.__host.get('refs',`preview:${appId}`),run:await window.electron.ipcRenderer.invoke('distributed-machine:subscribe',{protocolVersion:1,machineId:'app_run',encodedKey:{appId}})}; },appId); diff --git a/studio/tools/shell_ui.test.mjs b/studio/tools/shell_ui.test.mjs index bbf28258..75a2ebbb 100644 --- a/studio/tools/shell_ui.test.mjs +++ b/studio/tools/shell_ui.test.mjs @@ -44,6 +44,13 @@ test("the look comes from the brand's tokens: no colour of its own, in any theme assert.ok(section.includes("@media (pointer: coarse)") && section.includes("prefers-reduced-motion")); }); +test("studio/experience: the workspace speaks the experience module's sentences (FA-93)", () => { + const spec = read("../experience/src/FoundryExperience.lex.tex"), sidebar = read("../vendor/dyad/hologram.screens/AppSidebar.tsx"); + const said = new Set([...sidebar.slice(sidebar.indexOf("const WORKSPACE_SAID"), sidebar.indexOf("function sayWorkspace")).matchAll(/[:=] "([^"]+)"/g)].map((m) => m[1])); + assert.equal(said.size, 6, "the sidebar says other than the six sentences"); + for (const words of said) assert.ok(spec.includes(words), words); +}); + test("studio/experience: centred popups, golden measures, tools on Settings, a quiet Home", () => { // The preferences are a LexLean module of their own, outside the kernel's proof inputs. const spec = read("../experience/src/FoundryExperience.lex.tex"); diff --git a/studio/tools/stateful_application_journeys_browser.mjs b/studio/tools/stateful_application_journeys_browser.mjs index 408e8e78..ee8a4ab6 100644 --- a/studio/tools/stateful_application_journeys_browser.mjs +++ b/studio/tools/stateful_application_journeys_browser.mjs @@ -58,7 +58,7 @@ try { let code;try{await run({});}catch(error){code=error.code;}check(code==='interactionStateStale','changed graph reused stale state'); check((await run({reset:true})).output.state===0,'explicit reset failed'); try{await call('edit-app-file',{appId,filePath:'prism/Application.lex.tex',content:'tampered'});throw Error('canonical write succeeded');}catch(error){check(error.code==='interactionApplicationMismatch','canonical authority was writable');} - const {db,kappa}=await import(new URL('inference.js',location.href)),database=await db(); + const {workspace:db,kappa}=await import(new URL('inference.js',location.href)),database=await db(); const {runStoredInteraction}=await import(new URL('interaction-state.mjs',location.href)); const guest=await window.ForgeKernel.load(path=>fetch(new URL(path,location.href))),model=await (await fetch(new URL('interaction-model.lex.tex',location.href))).text(); let arrivals=0,release;const barrier=new Promise(resolve=>release=resolve),delayed={dispatch:async bytes=>{if(++arrivals===2)release();await barrier;return guest.dispatch(bytes);}}; diff --git a/studio/tools/storage_request_browser.mjs b/studio/tools/storage_request_browser.mjs index c8cdd0d9..0704233d 100644 --- a/studio/tools/storage_request_browser.mjs +++ b/studio/tools/storage_request_browser.mjs @@ -1,12 +1,21 @@ -// Real IndexedDB rollback after a successful request, plus committed recovery. +// Real IndexedDB rollback after a successful request, plus committed recovery. Then the visitor's work sealed to +// their Prism ID (FA-93): the shell itself, with the kernel guest it pins, Hologram's cipher and the locked Prism +// frame its build bundles, served from studio/shell. import assert from "node:assert/strict"; import fs from "node:fs"; import http from "node:http"; import { chromium } from "../vendor/dyad/node_modules/playwright-core/index.mjs"; const source = fs.readFileSync(new URL("../shell/storage-request.mjs", import.meta.url)); +const shell = new URL("../shell/", import.meta.url); +const types = { js: "text/javascript", mjs: "text/javascript", json: "application/json", wasm: "application/wasm" }; const server = http.createServer((request, response) => { + const path = request.url.split("?")[0]; + if (path.startsWith("/shell/") && !path.includes("..") && fs.existsSync(new URL(path.slice(7), shell))) { + response.setHeader("content-type", types[path.split(".").pop()] ?? "application/octet-stream"); + return response.end(fs.readFileSync(new URL(path.slice(7), shell))); + } response.setHeader("content-type", request.url === "/storage.mjs" ? "text/javascript" : "text/html"); - response.end(request.url === "/storage.mjs" ? source : "Storage commit acceptance"); + response.end(request.url === "/storage.mjs" ? source : "Storage commit acceptance"); }); await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); const executablePath = process.env.CHROME_BIN || ["/usr/bin/chromium", "/usr/bin/google-chrome"].find(p => fs.existsSync(p)); @@ -53,6 +62,58 @@ try { }); assert.deepEqual(report, { afterRequestAbort: "refused-and-rolled-back", synchronousFailure: "rolled-back", recovery: "committed-and-reopened", deletion: "committed", closedDatabase: "refused" }); console.log(JSON.stringify(report)); + + // FA-93. The page loads the kernel as the shell does, then the shell's own inference.js; each import with its + // own query is a fresh page load's module. + const sealed = await page.evaluate(async () => { + const check = (v, message) => { if (!v) throw Error(message); }; + await new Promise((resolve, reject) => { const s = Object.assign(document.createElement("script"), { src: "/shell/kernel.js", onload: resolve, onerror: reject }); document.head.append(s); }); + const kernel = await self.ForgeKernel.load((path) => fetch("/shell/" + path)); + window.__forgeKernel = { ask: (line) => kernel.ask(line) }; + const load = (n) => import(`/shell/inference.js?load=${n}`); + const told = () => window.__workspaceTold.splice(0); + const tx = (db, store, mode, work) => new Promise((resolve, reject) => { const t = db.transaction(store, mode); const r = work(t.objectStore(store)); t.oncomplete = () => resolve(r?.result); t.onerror = () => reject(t.error); }); + const plain = await (await load(0)).db(); + const at = new Date("2026-11-16T00:00:00Z"); + const prompts = { profile: "foundry/prompts/1", nextId: 2, records: [{ id: 1, title: "Kept before", description: null, content: "plain", slug: null, createdAt: at, updatedAt: at }] }; + await tx(plain, "settings", "readwrite", (s) => s.put(prompts, "foundry:prompts:v1")); + await tx(plain, "files", "readwrite", (s) => s.put("kept before", "7:README.md")); + await tx(plain, "refs", "readwrite", (s) => s.put({ serve: true }, "capabilities:7")); + // The one move: sealed in place, opening as it was written, told once. + let ws = await (await load(1)).workspace(); + check(told().join() === "workspaceMoved", "the move was not told once"); + const opened = await tx(ws, "settings", "readonly", (s) => s.get("foundry:prompts:v1")); + check(opened.records[0].title === "Kept before" && opened.records[0].createdAt instanceof Date && +opened.records[0].createdAt === +at, "the moved record does not open as written"); + check(await tx(ws, "files", "readonly", (s) => s.get("7:README.md")) === "kept before", "the moved file does not open"); + const rawFile = await tx(plain, "files", "readonly", (s) => s.get("7:README.md")); + check(rawFile.sealedWork instanceof Uint8Array && !new TextDecoder().decode(rawFile.sealedWork).includes("kept before"), "the file is kept in the clear"); + check((await tx(plain, "refs", "readonly", (s) => s.get("capabilities:7"))).serve === true, "the worker's grant was sealed"); + // A record stored afterwards is sealed; altered, copied and planted records are refused and never returned. + await tx(ws, "files", "readwrite", (s) => s.put("written now", "7:new.md")); + check((await tx(plain, "files", "readonly", (s) => s.get("7:new.md"))).sealedWork instanceof Uint8Array, "a new record is kept in the clear"); + const altered = new Uint8Array(rawFile.sealedWork); altered[altered.length - 1] ^= 1; + await tx(plain, "files", "readwrite", (s) => { s.put({ sealedWork: altered }, "7:altered.md"); s.put(rawFile, "7:copied.md"); return s.put("planted", "7:planted.md"); }); + told(); + for (const key of ["7:altered.md", "7:copied.md", "7:planted.md"]) check(await tx(ws, "files", "readonly", (s) => s.get(key)) === undefined, key + " was returned"); + check(told().join() === "recordTampered,recordMisplaced,recordTampered", "a refused record was not told by the kernel's answer"); + check((await tx(ws, "files", "readonly", (s) => s.getAll())).sort().join() === "kept before,written now", "getAll returned a refused record"); + told(); + // A device removed from the Prism ID: its key is another ID's. Everything kept where work belongs is cleared. + const id = await new Promise((resolve) => { const q = indexedDB.open("prism-id"); q.onsuccess = () => resolve(q.result); }); + const key = await tx(id, "prism", "readonly", (s) => s.get("workspace")); + await tx(id, "prism", "readwrite", (s) => s.put({ ...key, prism: "sha256:" + "0".repeat(64) }, "workspace")); + await (await caches.open("previews")).put("/shell/p/7/index.html", new Response("a built app")); + ws = await (await load(2)).workspace(); + check(told().join() === "workspaceDeviceRemoved", "the removal was not told, or something left behind moved in"); + check((await tx(plain, "files", "readonly", (s) => s.getAllKeys())).length === 0 && (await tx(plain, "settings", "readonly", (s) => s.getAllKeys())).length === 0, "the removed device's work was kept"); + check((await tx(plain, "refs", "readonly", (s) => s.get("capabilities:7"))).serve === true, "the worker's grant was cleared"); + check(!(await caches.has("previews")), "the removed device's built previews were kept"); + await tx(ws, "files", "readwrite", (s) => s.put("fresh", "8:README.md")); + check(await tx(ws, "files", "readonly", (s) => s.get("8:README.md")) === "fresh", "the fresh workspace does not open"); + return { moved: "sealed-in-place", stored: "sealed", altered: "recordTampered", copied: "recordMisplaced", planted: "recordTampered", removed: "cleared-and-fresh" }; + }); + assert.deepEqual(sealed, { moved: "sealed-in-place", stored: "sealed", altered: "recordTampered", copied: "recordMisplaced", planted: "recordTampered", removed: "cleared-and-fresh" }); + console.log(JSON.stringify(sealed)); } finally { if (browser) await browser.close(); await new Promise(resolve => server.close(resolve)); diff --git a/studio/vendor/dyad/VENDORED.md b/studio/vendor/dyad/VENDORED.md index 7fc1e90c..abab42c2 100644 --- a/studio/vendor/dyad/VENDORED.md +++ b/studio/vendor/dyad/VENDORED.md @@ -7,6 +7,9 @@ NOTICE, README.md, AGENTS.md. Removed: `src/pro/` (Functional Source License 1.1; not reused). Everything kept is Apache 2.0 per LICENSE. +Removed: `src/__tests__/` (upstream's own unit tests and eval fixtures) and `src/window_infrastructure/chat_tab_session_storage.test.ts`, which read its fixtures. Foundry never runs them, and its +typecheck (`tsconfig.hologram.json`, `tsconfig.hologram.dyad.json`) already excluded them. + Changes to reused files are listed here, one line each, so upstream can be tracked: - `hologram.contracts.ts` (ours) also publishes imported input schemas as `window.__inputContracts`; the browser host validates and copies command inputs before effects, and returns typed refusals rather than synthesizing successful output. diff --git a/studio/vendor/dyad/hologram.screens/AppSidebar.tsx b/studio/vendor/dyad/hologram.screens/AppSidebar.tsx index 12afd6e9..8b4a4877 100644 --- a/studio/vendor/dyad/hologram.screens/AppSidebar.tsx +++ b/studio/vendor/dyad/hologram.screens/AppSidebar.tsx @@ -26,6 +26,7 @@ import { import { Link, useLocation, useNavigate, useRouter } from "@tanstack/react-router"; import { useAtomValue, useSetAtom } from "jotai"; import { Fragment, useEffect, useMemo, useState } from "react"; +import { toast } from "sonner"; import { selectedAppIdAtom } from "@/atoms/appAtoms"; import { selectedChatIdAtom } from "@/atoms/chatAtoms"; @@ -87,24 +88,28 @@ function PrismMark({ className }: { className?: string }) { ); } -// Prism ID is the Prism frame's own panel, so Foundry keeps the one id every Prism app keeps. The frame is -// fetched on the first reach for it and run only if its bytes match its pointer's SHA-256, as an app page -// runs it (site/app.mjs). It stays off screen: its panel is a centred popover in the top layer. -const FRAME_HOST = "https://uor-foundation.github.io/template/frame/"; -let prismFrame: Promise | null = null; -async function loadPrismFrame() { - const pointer = await (await fetch(new URL("current.json", FRAME_HOST), { cache: "no-cache" })).json(); - const bytes = await (await fetch(new URL(pointer.module, FRAME_HOST))).arrayBuffer(); - const digest = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), (b) => b.toString(16).padStart(2, "0")).join(""); - if (!/^[0-9a-f]{64}$/.test(pointer.sha256 ?? "") || digest !== pointer.sha256) throw Object.assign(new Error("prismFrameUnverified"), { code: "prismFrameUnverified" }); - await import(/* @vite-ignore */ URL.createObjectURL(new Blob([bytes], { type: "text/javascript" }))); - const frame = document.createElement("prism-frame"); - frame.style.cssText = "position:fixed;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)"; - return document.body.appendChild(frame); -} +// Prism ID is the Prism frame's own panel, so Foundry keeps the one ID every Prism app keeps. The shell runs +// the frame its lock pins (shell/inference.js, prismFrame); its panel is a centred popover in the top layer. +declare global { interface Window { __prismFrame?: () => Promise; __workspaceTold?: string[] } } function openPrismId() { - prismFrame ??= loadPrismFrame().catch((error) => { prismFrame = null; throw error; }); - prismFrame.then((frame) => frame.shadowRoot?.getElementById("account-panel")?.showPopover(), (error) => console.warn(`Prism id: ${error.code ?? error}`)); + window.__prismFrame?.().then((frame) => frame.shadowRoot?.getElementById("account-panel")?.showPopover(), (error) => console.warn(`Prism ID: ${error}`)); +} +// What the visitor is told about their work, by the kernel's answer (shell/inference.js, tell). Each sentence +// is a statement of studio/experience/src/FoundryExperience.lex.tex. +const WORKSPACE_SAID: Record = { + workspaceMoved: "Your work is now sealed to your Prism ID. Only your devices can open it.", + workspaceDeviceRemoved: "This device was removed from your Prism ID, so the work it kept stays closed. You start fresh here.", + workspaceQuotaExceeded: "Your browser's storage is full, so this was not saved. Remove an app you no longer need, then try again.", + recordTampered: "Some of your work was changed outside Foundry, so it was left closed.", + recordMisplaced: "Some of your work was changed outside Foundry, so it was left closed.", + workspaceKeyStale: "This device is waiting for your Prism ID's newest key. Open Foundry on one of your other devices, then try again.", +}; +const WORKSPACE_CLOSED = "Foundry could not reach your Prism ID, so your work stays closed for now."; +function sayWorkspace(answer: string) { + const words = WORKSPACE_SAID[answer]; + if (answer === "workspaceMoved" || answer === "workspaceDeviceRemoved") toast(words, { id: answer }); + else if (words && answer !== "workspaceKeyStale") toast.error(words, { id: answer }); + else toast.error(words ?? WORKSPACE_CLOSED, { id: answer, duration: Infinity, action: { label: "Try again", onClick: () => location.reload() } }); } type Nav = { title: string; to: string; icon: LucideIcon; exact?: boolean }; @@ -159,6 +164,12 @@ export function AppSidebar() { const { isMobile, setOpenMobile } = useSidebar(); const href = useLocation({ select: (l) => l.href }); useEffect(() => { if (isMobile) setOpenMobile(false); }, [href, isMobile, setOpenMobile]); + useEffect(() => { + (window.__workspaceTold ?? []).forEach(sayWorkspace); + const said = (event: Event) => sayWorkspace((event as CustomEvent).detail); + window.addEventListener("foundry:workspace", said); + return () => window.removeEventListener("foundry:workspace", said); + }, []); // A tooltip names an item of the collapsed rail. In the Sheet it is never shown, but the kit still opens it // when the Sheet focuses its first item, and the first Escape then closed that invisible tooltip, not the // Sheet. On a phone the items carry none. diff --git a/studio/vendor/dyad/src/__tests__/README.md b/studio/vendor/dyad/src/__tests__/README.md deleted file mode 100644 index 544c1256..00000000 --- a/studio/vendor/dyad/src/__tests__/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# Test Documentation - -Prefer co-locating new unit tests next to the implementation file they cover -instead of adding them to this directory. - -This directory is reserved for tests that do not currently have a runnable -co-located home under the root Vitest include pattern (`src/**/*.{test,spec}.{ts,tsx}`) -and for eval assets under `evals/`. - -## Testing Setup - -We use [Vitest](https://vitest.dev/) as our testing framework, which is designed to work well with Vite and modern JavaScript. - -### Test Commands - -Add these commands to your `package.json`: - -```json -"test": "vitest run", -"test:watch": "vitest", -"test:ui": "vitest --ui" -``` - -- `npm run test` - Run tests once -- `npm run test:watch` - Run tests in watch mode (rerun when files change) -- `npm run test:ui` - Run tests with UI reporter - -## Mocking Guidelines - -### Mocking fs module - -When mocking the `node:fs` module, use a default export in the mock: - -```typescript -vi.mock("node:fs", async () => { - return { - default: { - mkdirSync: vi.fn(), - writeFileSync: vi.fn(), - // Add other fs methods as needed - }, - }; -}); -``` - -### Testing IPC Handlers - -When testing IPC handlers, mock the Electron IPC system: - -```typescript -vi.mock("electron", () => ({ - ipcMain: { - handle: vi.fn(), - on: vi.fn(), - }, -})); -``` - -## Adding New Tests - -1. Create a new file with the `.test.ts` or `.spec.ts` extension next to the implementation when possible -2. Import the functions you want to test -3. Mock any dependencies using `vi.mock()` -4. Write your test cases using `describe()` and `it()` - -## Example - -See `chat_stream_handlers.test.ts` for an example of testing IPC handlers with proper mocking. diff --git a/studio/vendor/dyad/src/__tests__/app_upgrade_utils.test.ts b/studio/vendor/dyad/src/__tests__/app_upgrade_utils.test.ts deleted file mode 100644 index 455f7d3b..00000000 --- a/studio/vendor/dyad/src/__tests__/app_upgrade_utils.test.ts +++ /dev/null @@ -1,207 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import fs from "node:fs"; -import { - isComponentTaggerUpgradeNeeded, - applyComponentTagger, -} from "../ipc/utils/app_upgrade_utils"; -import { simpleSpawn } from "../ipc/utils/simpleSpawn"; -import { gitAddAll, gitCommit } from "../ipc/utils/git_utils"; - -vi.mock( - "node:fs", - async (importOriginal: () => Promise) => { - const actual = await importOriginal(); - return { - ...actual, - promises: { - ...actual.promises, - readFile: vi.fn(), - writeFile: vi.fn(), - }, - existsSync: vi.fn(), - readFileSync: vi.fn(), - } as unknown as typeof import("node:fs"); - }, -); - -vi.mock("../ipc/utils/simpleSpawn", () => ({ - simpleSpawn: vi.fn().mockResolvedValue(undefined), -})); - -vi.mock("../ipc/utils/git_utils", () => ({ - gitAddAll: vi.fn().mockResolvedValue(undefined), - gitCommit: vi.fn().mockResolvedValue(undefined), -})); - -vi.mock("../ipc/utils/telemetry", () => ({ - sendTelemetryEvent: vi.fn(), -})); - -describe("isComponentTaggerUpgradeNeeded Heuristics", () => { - const mockPath = "/mock/app"; - - beforeEach(() => { - vi.clearAllMocks(); - }); - - it("should return false if the project is not a Vite app (no config file)", () => { - vi.spyOn(fs, "existsSync").mockReturnValue(false); - expect(isComponentTaggerUpgradeNeeded(mockPath)).toBe(false); - }); - - it("should return true for a React Vite app needing upgrade", () => { - vi.spyOn(fs, "existsSync").mockReturnValue(true); - vi.spyOn(fs, "readFileSync").mockReturnValue(` - import { defineConfig } from 'vite'; - import react from '@vitejs/plugin-react-swc'; - export default defineConfig({ plugins: [react()] }); - `); - expect(isComponentTaggerUpgradeNeeded(mockPath)).toBe(true); - }); - - it("should return false for a Vue Vite app (React heuristic filter)", () => { - vi.spyOn(fs, "existsSync").mockReturnValue(true); - vi.spyOn(fs, "readFileSync").mockReturnValue(` - import { defineConfig } from 'vite'; - import vue from '@vitejs/plugin-vue'; - export default defineConfig({ plugins: [vue()] }); - `); - expect(isComponentTaggerUpgradeNeeded(mockPath)).toBe(false); // Correctly filtered out - }); - - it("should return false if the React Vite app already has the tagger applied", () => { - vi.spyOn(fs, "existsSync").mockReturnValue(true); - vi.spyOn(fs, "readFileSync").mockReturnValue(` - import { defineConfig } from 'vite'; - import react from '@vitejs/plugin-react'; - import dyadComponentTagger from '@dyad-sh/react-vite-component-tagger'; - export default defineConfig({ plugins: [dyadComponentTagger(), react()] }); - `); - expect(isComponentTaggerUpgradeNeeded(mockPath)).toBe(false); - }); -}); - -describe("applyComponentTagger", () => { - const mockPath = "/mock/app"; - - beforeEach(() => { - vi.clearAllMocks(); - vi.spyOn(fs, "existsSync").mockReturnValue(true); - vi.spyOn(fs.promises, "readFile").mockResolvedValue(` - import { defineConfig } from 'vite'; - import react from '@vitejs/plugin-react'; - export default defineConfig({ plugins: [react()] }); - `); - }); - - it("inserts tagger import and adds to plugins", async () => { - let writtenContent = ""; - vi.spyOn(fs.promises, "writeFile").mockImplementation( - async (path, content) => { - if (typeof content === "string") { - writtenContent = content; - } - }, - ); - - await applyComponentTagger(mockPath); - expect(writtenContent).toContain( - "import dyadComponentTagger from '@dyad-sh/react-vite-component-tagger';", - ); - expect(writtenContent).toContain("plugins: [dyadComponentTagger(), "); - expect(gitAddAll).toHaveBeenCalled(); - expect(gitCommit).toHaveBeenCalled(); - }); - - it("targets the plugins array after defineConfig when multiple exist", async () => { - const originalContent = ` - // Some config or other tooling that has plugins - const otherConfig = { - plugins: [someTool()] - }; - - import { defineConfig } from 'vite'; - import react from '@vitejs/plugin-react'; - - export default defineConfig({ - plugins: [react()] - }); - `; - vi.spyOn(fs.promises, "readFile").mockResolvedValue(originalContent); - - let writtenContent = ""; - vi.spyOn(fs.promises, "writeFile").mockImplementation( - async (path, content) => { - if (typeof content === "string") { - writtenContent = content; - } - }, - ); - - await applyComponentTagger(mockPath); - - // The first plugins array (in otherConfig) should remain unchanged - expect(writtenContent).toContain("plugins: [someTool()]"); - // The main plugins array under defineConfig should get the component tagger - expect(writtenContent).toContain( - "plugins: [dyadComponentTagger(), react()]", - ); - }); - - it("rollback when install fails", async () => { - vi.mocked(simpleSpawn).mockRejectedValue(new Error("Install failed")); - const rollbackSpy = vi.spyOn(fs.promises, "writeFile"); - - await expect(applyComponentTagger(mockPath)).rejects.toThrow(); - expect(rollbackSpy).toHaveBeenCalledWith( - expect.any(String), - expect.stringContaining("plugins: [react()]"), - ); - }); - - it("skips dependency installation when installDependencies is false", async () => { - // Override the default readFile mock to return appropriate content per file - vi.spyOn(fs.promises, "readFile").mockImplementation(async (filePath) => { - if (String(filePath).includes("package.json")) { - return JSON.stringify({ devDependencies: {} }); - } - return ` - import { defineConfig } from 'vite'; - import react from '@vitejs/plugin-react'; - export default defineConfig({ plugins: [react()] }); - `; - }); - - const writtenFiles: Record = {}; - vi.spyOn(fs.promises, "writeFile").mockImplementation( - async (filePath, content) => { - if (typeof content === "string") { - writtenFiles[String(filePath)] = content; - } - }, - ); - - await applyComponentTagger(mockPath, { installDependencies: false }); - - // Check spawn was NOT called — no npm/pnpm install - expect(simpleSpawn).not.toHaveBeenCalled(); - - // Check vite config was modified - const viteWrite = Object.entries(writtenFiles).find(([k]) => - k.includes("vite.config"), - ); - expect(viteWrite).toBeDefined(); - expect(viteWrite![1]).toContain("dyadComponentTagger()"); - - // Check package.json was updated with the tagger dependency - const pkgWrite = Object.entries(writtenFiles).find(([k]) => - k.includes("package.json"), - ); - expect(pkgWrite).toBeDefined(); - expect(pkgWrite![1]).toContain("@dyad-sh/react-vite-component-tagger"); - - // Check git was still committed - expect(gitAddAll).toHaveBeenCalled(); - expect(gitCommit).toHaveBeenCalled(); - }); -}); diff --git a/studio/vendor/dyad/src/__tests__/codebase.test.ts b/studio/vendor/dyad/src/__tests__/codebase.test.ts deleted file mode 100644 index 5c2562b7..00000000 --- a/studio/vendor/dyad/src/__tests__/codebase.test.ts +++ /dev/null @@ -1,499 +0,0 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { extractCodebase, listCodebaseFileMetadata } from "@/utils/codebase"; -import { gitListFilesNative } from "@/ipc/utils/git_utils"; - -vi.mock("electron-log", () => ({ - default: { - scope: () => ({ - debug: vi.fn(), - error: vi.fn(), - info: vi.fn(), - log: vi.fn(), - warn: vi.fn(), - }), - }, -})); - -vi.mock("@/main/settings", () => ({ - readSettings: vi.fn(() => ({ - enableDyadPro: false, - enableProSmartFilesContextMode: false, - })), -})); - -vi.mock("@/ipc/utils/git_utils", () => ({ - gitListFilesNative: vi.fn(async () => { - throw new Error("Git unavailable in filesystem traversal tests"); - }), -})); - -afterEach(() => { - // Re-arm the default. A test that fails before consuming its - // mockResolvedValueOnce would otherwise leak that value into the next one - // and silently switch it to the native-Git branch. - vi.mocked(gitListFilesNative).mockReset(); - vi.mocked(gitListFilesNative).mockImplementation(async () => { - throw new Error("Git unavailable in filesystem traversal tests"); - }); -}); - -describe("extractCodebase", () => { - let appDir: string | undefined; - - afterEach(async () => { - if (appDir) { - await fs.promises.rm(appDir, { recursive: true, force: true }); - appDir = undefined; - } - vi.restoreAllMocks(); - }); - - it("includes shader source file contents", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.mkdir(path.join(appDir, "src", "shaders"), { - recursive: true, - }); - - await fs.promises.writeFile( - path.join(appDir, "src", "shaders", "scene.wgsl"), - "fn vertexMain() -> void {}", - ); - await fs.promises.writeFile( - path.join(appDir, "src", "shaders", "material.frag"), - "void main() { gl_FragColor = vec4(1.0); }", - ); - await fs.promises.writeFile( - path.join(appDir, "src", "notes.shader"), - "custom shader notes", - ); - - const result = await extractCodebase({ - appPath: appDir, - chatContext: { - contextPaths: [], - smartContextAutoIncludes: [], - }, - }); - - expect(result.files).toContainEqual({ - path: "src/shaders/scene.wgsl", - content: "fn vertexMain() -> void {}", - force: false, - }); - expect(result.files).toContainEqual({ - path: "src/shaders/material.frag", - content: "void main() { gl_FragColor = vec4(1.0); }", - force: false, - }); - expect(result.files).toContainEqual({ - path: "src/notes.shader", - content: "// File contents excluded from context", - force: false, - }); - }); - - it("excludes git metadata policy files from context", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - - await fs.promises.writeFile( - path.join(appDir, ".gitattributes"), - "* text=auto eol=lf\n", - ); - await fs.promises.writeFile(path.join(appDir, ".gitignore"), "dist\n"); - await fs.promises.writeFile(path.join(appDir, "src.ts"), "export {};\n"); - - const result = await extractCodebase({ - appPath: appDir, - chatContext: { - contextPaths: [], - smartContextAutoIncludes: [], - }, - }); - - expect(result.files.map((file) => file.path).sort()).toEqual([ - ".gitignore", - "src.ts", - ]); - expect(result.formattedOutput).not.toContain(".gitattributes"); - }); - - it("honors nested gitignore rules without a Git repository", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.mkdir(path.join(appDir, "src"), { recursive: true }); - await fs.promises.mkdir(path.join(appDir, "private"), { - recursive: true, - }); - await fs.promises.writeFile( - path.join(appDir, ".gitignore"), - "secret.json\nprivate/\n", - ); - await fs.promises.writeFile( - path.join(appDir, "src", ".gitignore"), - "ignored.ts\n", - ); - await fs.promises.writeFile( - path.join(appDir, "secret.json"), - '{"token":"secret"}', - ); - await fs.promises.writeFile( - path.join(appDir, "private", "credentials.ts"), - 'export const password = "secret";', - ); - await fs.promises.writeFile( - path.join(appDir, "src", "ignored.ts"), - 'export const ignored = "secret";', - ); - await fs.promises.writeFile( - path.join(appDir, "src", "visible.ts"), - "export const visible = true;", - ); - - const result = await extractCodebase({ - appPath: appDir, - chatContext: { - contextPaths: [], - smartContextAutoIncludes: [], - }, - }); - - expect(result.files.map((file) => file.path).sort()).toEqual([ - ".gitignore", - "src/.gitignore", - "src/visible.ts", - ]); - expect(result.formattedOutput).not.toContain('{"token":"secret"}'); - expect(result.formattedOutput).not.toContain( - 'export const password = "secret";', - ); - }); - - it("lists file metadata without reading file contents", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.writeFile(path.join(appDir, "a.ts"), "secret content"); - await fs.promises.writeFile(path.join(appDir, "b.ts"), "more content"); - const readFileSpy = vi.spyOn(fs.promises, "readFile"); - - const result = await listCodebaseFileMetadata({ - appPath: appDir, - chatContext: { - contextPaths: [], - smartContextAutoIncludes: [], - }, - }); - - expect(result.files.map((file) => file.path)).toEqual(["a.ts", "b.ts"]); - expect(result.totalFileCount).toBe(2); - expect(result.sizeStats).toEqual({ fileCount: 2, totalBytes: 26 }); - expect(readFileSpy).not.toHaveBeenCalled(); - }); -}); - -describe("extractCodebase size stats", () => { - let appDir: string | undefined; - - afterEach(async () => { - if (appDir) { - await fs.promises.rm(appDir, { recursive: true, force: true }); - appDir = undefined; - } - vi.restoreAllMocks(); - }); - - const noContext = { - contextPaths: [], - smartContextAutoIncludes: [], - }; - - /** Captures what the extraction reports, which is the only way it is read. */ - async function sizeOf( - dir: string, - chatContext: Parameters< - typeof extractCodebase - >[0]["chatContext"] = noContext, - ) { - let sizeStats: unknown; - await extractCodebase({ - appPath: dir, - chatContext, - onSizeStats: (stats) => { - sizeStats = stats; - }, - }); - return sizeStats; - } - - it("counts files and bytes, excluding gitignored files", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - // secret.json is dropped by the gitignore rule alone: nothing in - // EXCLUDED_DIRS or EXCLUDED_FILES would exclude it. - await fs.promises.writeFile( - path.join(appDir, ".gitignore"), - "secret.json\n", - ); - // 1000 bytes that must not be counted. - await fs.promises.writeFile( - path.join(appDir, "secret.json"), - "x".repeat(1000), - ); - await fs.promises.writeFile(path.join(appDir, "a.ts"), "aaaa\n"); - await fs.promises.writeFile(path.join(appDir, "b.ts"), "bb\n"); - - // .gitignore (12) + a.ts (5) + b.ts (3); secret.json excluded. - expect(await sizeOf(appDir)).toEqual({ fileCount: 3, totalBytes: 20 }); - }); - - it("counts files and bytes, excluding build output directories", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.mkdir(path.join(appDir, "dist")); - // dist is in EXCLUDED_DIRS, so it is dropped with no gitignore rule. - await fs.promises.writeFile( - path.join(appDir, "dist", "bundle.js"), - "x".repeat(1000), - ); - await fs.promises.writeFile(path.join(appDir, "a.ts"), "aaaa\n"); - - expect(await sizeOf(appDir)).toEqual({ fileCount: 1, totalBytes: 5 }); - }); - - it("counts files whose contents are withheld from the model", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - // .bin is outside ALLOWED_EXTENSIONS, so it reaches the model as a path - // with placeholder content. It is still part of the app, so it counts. - await fs.promises.writeFile( - path.join(appDir, "data.bin"), - "1\n2\n3\n4\n5\n", - ); - await fs.promises.writeFile(path.join(appDir, "a.ts"), "one\ntwo\n"); - - expect(await sizeOf(appDir)).toEqual({ fileCount: 2, totalBytes: 18 }); - }); - - it("counts an empty file toward the file count but not the byte total", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.writeFile(path.join(appDir, "a.ts"), "one\ntwo"); - await fs.promises.writeFile(path.join(appDir, "b.ts"), ""); - - expect(await sizeOf(appDir)).toEqual({ fileCount: 2, totalBytes: 7 }); - }); - - it("counts a conflicted file once, not once per index stage", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.writeFile(path.join(appDir, "f.ts"), "aaaa\n"); - await fs.promises.writeFile(path.join(appDir, "other.ts"), "bb\n"); - // During a merge conflict `git ls-files` prints the unmerged path once per - // index stage, so the same path arrives three times. Only one file exists - // on disk, so it must be counted once. - vi.mocked(gitListFilesNative).mockResolvedValueOnce([ - "f.ts", - "f.ts", - "f.ts", - "other.ts", - ]); - - expect(await sizeOf(appDir)).toEqual({ fileCount: 2, totalBytes: 8 }); - }); - - it("does not let an extraction emit a conflicted file more than once", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.writeFile(path.join(appDir, "f.ts"), "aaaa\n"); - await fs.promises.writeFile(path.join(appDir, "other.ts"), "bb\n"); - vi.mocked(gitListFilesNative).mockResolvedValueOnce([ - "f.ts", - "f.ts", - "f.ts", - "other.ts", - ]); - - const result = await extractCodebase({ - appPath: appDir, - chatContext: noContext, - }); - - expect(result.files.map((file) => file.path).sort()).toEqual([ - "f.ts", - "other.ts", - ]); - }); - - it("counts bytes on the native Git path too", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.writeFile(path.join(appDir, "a.ts"), "aaaa\n"); - await fs.promises.writeFile(path.join(appDir, "b.ts"), "bb\n"); - // The suite otherwise forces the traversal fallback; exercise the path - // that actually runs in production. - vi.mocked(gitListFilesNative).mockResolvedValueOnce(["a.ts", "b.ts"]); - - expect(await sizeOf(appDir)).toEqual({ fileCount: 2, totalBytes: 8 }); - }); - - it("reports the same size whichever way the prompt is assembled", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.mkdir(path.join(appDir, "src", "components", "ui"), { - recursive: true, - }); - // src/components/ui reaches the model as a placeholder, but it is still - // part of the app. Size comes from the filesystem, never from how the - // prompt happens to be built. - await fs.promises.writeFile( - path.join(appDir, "src", "components", "ui", "button.tsx"), - "a\nb\nc\nd\ne\n", - ); - await fs.promises.writeFile(path.join(appDir, "src", "app.tsx"), "one\n"); - - expect(await sizeOf(appDir)).toEqual({ fileCount: 2, totalBytes: 14 }); - }); - - it("reports the same size regardless of per-chat context filtering", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.mkdir(path.join(appDir, "src")); - await fs.promises.writeFile(path.join(appDir, "src", "keep.ts"), "keep\n"); - await fs.promises.writeFile( - path.join(appDir, "src", "other.ts"), - "other\nlines\nhere\n", - ); - - const unfiltered = await sizeOf(appDir); - const filtered = await sizeOf(appDir, { - contextPaths: [{ globPath: "src/keep.ts" }], - smartContextAutoIncludes: [], - }); - - // This is the property the whole metric rests on: two chats against the - // same app must report the same app size regardless of context config. - expect(filtered).toEqual(unfiltered); - }); - - it("reports the size before reading any file contents", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.writeFile(path.join(appDir, "a.ts"), "aaaa\n"); - await fs.promises.writeFile(path.join(appDir, "b.ts"), "bb\n"); - const readFileSpy = vi.spyOn(fs.promises, "readFile"); - let readsWhenReported = -1; - - await extractCodebase({ - appPath: appDir, - chatContext: noContext, - onSizeStats: () => { - readsWhenReported = readFileSpy.mock.calls.length; - }, - }); - - // A turn that dies reading a large codebase must still have reported its - // size, so the callback has to fire before any content is read. - expect(readsWhenReported).toBe(0); - expect(readFileSpy).toHaveBeenCalled(); - }); - - it("reports nothing when the app directory cannot be read", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.writeFile(path.join(appDir, "a.ts"), "aaaa\n"); - const onSizeStats = vi.fn(); - // The directory exists, so the existence check passes, but the walk finds - // nothing. A zero would land in the small-app bucket as a real reading. - vi.spyOn(fs.promises, "readdir").mockRejectedValue( - new Error("permission denied"), - ); - - await extractCodebase({ - appPath: appDir, - chatContext: noContext, - onSizeStats, - }); - - expect(onSizeStats).not.toHaveBeenCalled(); - }); - - it("reports nothing when part of the tree cannot be read", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.mkdir(path.join(appDir, "src")); - await fs.promises.writeFile(path.join(appDir, "a.ts"), "aaaa\n"); - await fs.promises.writeFile(path.join(appDir, "src", "b.ts"), "bb\n"); - const onSizeStats = vi.fn(); - // One unreadable file makes the count an undercount by an unknown amount, - // which is indistinguishable from a genuinely smaller app. - const realStat = fs.promises.stat; - vi.spyOn(fs.promises, "stat").mockImplementation( - async (target, ...rest) => { - if (String(target).endsWith("b.ts")) { - throw new Error("permission denied"); - } - return realStat(target, ...(rest as [])); - }, - ); - - const result = await extractCodebase({ - appPath: appDir, - chatContext: noContext, - onSizeStats, - }); - - expect(onSizeStats).not.toHaveBeenCalled(); - // Only the measurement is suppressed. The turn still gets everything the - // walk managed to read. - expect(result.files.map((file) => file.path)).toEqual(["a.ts"]); - }); - - it("still reports when a git-listed file is simply gone", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.writeFile(path.join(appDir, "a.ts"), "aaaa\n"); - // git ls-files --cached lists tracked files whose deletion has not been - // staged. The file is definitively gone, so excluding it is exact, not an - // undercount, and suppressing here would blind the metric to any app in - // that state until the deletion is committed. - vi.mocked(gitListFilesNative).mockResolvedValueOnce(["a.ts", "gone.ts"]); - const onSizeStats = vi.fn(); - - const result = await extractCodebase({ - appPath: appDir, - chatContext: noContext, - onSizeStats, - }); - - expect(onSizeStats).toHaveBeenCalledWith({ fileCount: 1, totalBytes: 5 }); - expect(result.files.map((file) => file.path)).toEqual(["a.ts"]); - }); - - it("reports nothing when a git-listed file cannot be read", async () => { - appDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codebase-")); - await fs.promises.writeFile(path.join(appDir, "a.ts"), "aaaa\n"); - await fs.promises.writeFile(path.join(appDir, "b.ts"), "bb\n"); - const onSizeStats = vi.fn(); - // A permission error is different: the file is there and we cannot see it, - // so the count is short by an unknown amount. - const realLstat = fs.promises.lstat; - vi.spyOn(fs.promises, "lstat").mockImplementation( - async (target, ...rest) => { - if (String(target).endsWith("b.ts")) { - const error = new Error("permission denied") as NodeJS.ErrnoException; - error.code = "EACCES"; - throw error; - } - return realLstat(target, ...(rest as [])); - }, - ); - vi.mocked(gitListFilesNative).mockResolvedValueOnce(["a.ts", "b.ts"]); - - await extractCodebase({ - appPath: appDir, - chatContext: noContext, - onSizeStats, - }); - - expect(onSizeStats).not.toHaveBeenCalled(); - }); - - it("is not called for a directory that does not exist", async () => { - const onSizeStats = vi.fn(); - - await extractCodebase({ - appPath: path.join(os.tmpdir(), "codebase-missing-dir"), - chatContext: noContext, - onSizeStats, - }); - - expect(onSizeStats).not.toHaveBeenCalled(); - }); -}); diff --git a/studio/vendor/dyad/src/__tests__/dyad_auth_bootstrap.test.ts b/studio/vendor/dyad/src/__tests__/dyad_auth_bootstrap.test.ts deleted file mode 100644 index ee6353af..00000000 --- a/studio/vendor/dyad/src/__tests__/dyad_auth_bootstrap.test.ts +++ /dev/null @@ -1,544 +0,0 @@ -import fs from "node:fs"; -import path from "node:path"; -import vm from "node:vm"; -import { describe, expect, it, vi } from "vitest"; - -const bootstrapSource = fs.readFileSync( - path.resolve(process.cwd(), "worker/dyad-auth-bootstrap.js"), - "utf8", -); - -function makeStorage(seed: Record = {}) { - const map = new Map(Object.entries(seed)); - return { - getItem: (k: string) => (map.has(k) ? map.get(k)! : null), - setItem: (k: string, v: string) => map.set(k, String(v)), - removeItem: (k: string) => map.delete(k), - }; -} - -function setup({ - readyState = "complete", - pending = null as Record | null, - preLocal = {} as Record, - pathname = "/", - authBootstrapToken = "proxy-session-token", - fetchImpl, -}: { - readyState?: string; - pending?: Record | null; - preLocal?: Record; - pathname?: string; - authBootstrapToken?: string; - fetchImpl?: (...args: any[]) => Promise; -} = {}) { - const posts: any[] = []; - const parent = { postMessage: (msg: any) => posts.push(msg) }; - let messageHandler: ((e: any) => void) | undefined; - const timers: Array<() => void> = []; - - const localStorage = makeStorage(preLocal); - const sessionStorage = makeStorage( - pending - ? { - // Markers written by login() carry a `startedAt`; default to a fresh - // one so verify tests aren't treated as stale. The stale-marker test - // overrides it with an old timestamp. - __dyad_auth_pending__: JSON.stringify({ - startedAt: Date.now(), - ...pending, - }), - } - : {}, - ); - let currentPathname = pathname; - const location = { - get href() { - return `http://localhost:42100${currentPathname}`; - }, - get pathname() { - return currentPathname; - }, - // The bootstrap reports the settled route as pathname + search + hash, the - // same shape the unauthenticated start's route hint uses. - get search() { - return ""; - }, - get hash() { - return ""; - }, - replace: vi.fn((target: string) => { - currentPathname = new URL(target, location.href).pathname; - }), - }; - const fetchMock = vi.fn( - fetchImpl ?? (async () => ({ ok: true, json: async () => ({}) })), - ); - - const win: any = { - parent, - localStorage, - addEventListener: (type: string, handler: any) => { - if (type === "message") messageHandler = handler; - }, - removeEventListener: () => {}, - }; - win.window = win; - - const document = { - readyState, - currentScript: { - dataset: { dyadAuthToken: authBootstrapToken }, - }, - addEventListener: () => {}, - }; - - vm.runInNewContext(bootstrapSource, { - window: win, - document, - localStorage, - sessionStorage, - location, - setTimeout: (callback: () => void) => { - timers.push(callback); - return timers.length; - }, - fetch: fetchMock, - URL, - atob, - TextDecoder, - Uint8Array, - console: { debug() {}, warn() {}, error() {}, log() {} }, - }); - - return { - posts, - parent, - replace: location.replace, - fetchMock, - localStorage, - sessionStorage, - setPathname: (nextPathname: string) => { - currentPathname = nextPathname; - }, - flushTimers: () => { - const pendingTimers = timers.splice(0); - for (const callback of pendingTimers) callback(); - }, - pendingTimerCount: () => timers.length, - /** - * The parent naming the attempt it's waiting on. A marker already in - * sessionStorage is verified only when `nonce` matches the one it carries — - * that's what tells this document's marker apart from one an earlier, - * abandoned attempt left behind. - */ - sendLogin: ( - auth: Record, - nonce = "attempt-1", - token = authBootstrapToken, - ) => - messageHandler?.({ - source: parent, - data: { type: "dyad-auth-login", auth, nonce, token }, - }), - }; -} - -/** The verify path re-reads `projectUrl`/`anonKey` to check the session. */ -const SUPABASE_AUTH = { - mode: "supabase-password", - email: "e@x.test", - password: "pw", - projectUrl: "https://ref123.supabase.co", - anonKey: "anon-key", -}; -const NEON_AUTH = { - mode: "neon-better-auth", - email: "e@x.test", - password: "pw", -}; - -describe("dyad auth bootstrap", () => { - it("seeds the supabase session into localStorage and lands on the homepage", async () => { - const h = setup(); - h.fetchMock.mockResolvedValue({ - ok: true, - json: async () => ({ - access_token: "a", - refresh_token: "r", - user: { id: "u" }, - }), - }); - - h.sendLogin({ - mode: "supabase-password", - email: "e@x.test", - password: "pw", - projectUrl: "https://ref123.supabase.co", - anonKey: "anon-key", - }); - - await vi.waitFor(() => expect(h.replace).toHaveBeenCalledWith("/")); - expect(h.fetchMock).toHaveBeenCalledWith( - "https://ref123.supabase.co/auth/v1/token?grant_type=password", - expect.objectContaining({ - method: "POST", - headers: expect.objectContaining({ apikey: "anon-key" }), - }), - ); - const stored = h.localStorage.getItem("sb-ref123-auth-token"); - expect(stored).toContain("access_token"); - const marker = JSON.parse( - h.sessionStorage.getItem("__dyad_auth_pending__")!, - ); - expect(marker).toMatchObject({ - mode: "supabase-password", - ref: "ref123", - homeRedirects: 0, - }); - expect(typeof marker.startedAt).toBe("number"); - }); - - it("signs in via the app's own Better Auth endpoint and lands on the homepage (Neon)", async () => { - const h = setup(); - h.fetchMock.mockResolvedValue({ ok: true }); - - h.sendLogin({ - mode: "neon-better-auth", - email: "e@x.test", - password: "pw", - }); - - await vi.waitFor(() => expect(h.replace).toHaveBeenCalledWith("/")); - expect(h.fetchMock).toHaveBeenCalledWith( - "/api/auth/sign-in/email", - expect.objectContaining({ method: "POST", credentials: "include" }), - ); - }); - - it("announces bootstrap-ready on a fresh (pre-login) load", () => { - const h = setup(); - expect(h.posts.some((p) => p.type === "dyad-auth-bootstrap-ready")).toBe( - true, - ); - }); - - it("ignores login messages from a framing parent without the proxy capability", () => { - const h = setup(); - - h.sendLogin(SUPABASE_AUTH, "attacker-attempt", "attacker-token"); - - expect(h.fetchMock).not.toHaveBeenCalled(); - expect(h.replace).not.toHaveBeenCalled(); - expect(h.localStorage.getItem("sb-ref123-auth-token")).toBeNull(); - expect(h.sessionStorage.getItem("__dyad_auth_pending__")).toBeNull(); - }); - - it("reports failure (and does not navigate) when sign-in fails", async () => { - const h = setup(); - h.fetchMock.mockResolvedValue({ ok: false, status: 401 }); - - h.sendLogin({ - mode: "neon-better-auth", - email: "e@x.test", - password: "pw", - }); - - await vi.waitFor(() => - expect( - h.posts.some((p) => p.type === "dyad-auth-ready" && p.ok === false), - ).toBe(true), - ); - expect(h.replace).not.toHaveBeenCalled(); - }); - - it("verifies a pending supabase session once the parent claims the attempt", async () => { - const h = setup({ - pending: { - mode: "supabase-password", - ref: "ref123", - nonce: "attempt-1", - }, - preLocal: { "sb-ref123-auth-token": '{"access_token":"a"}' }, - fetchImpl: async () => ({ ok: true, json: async () => ({ id: "u" }) }), - }); - - // Nothing happens on load alone — the marker is held until the parent says - // whose attempt it belongs to. - expect(h.pendingTimerCount()).toBe(0); - expect(h.posts).toContainEqual( - expect.objectContaining({ - type: "dyad-auth-bootstrap-ready", - pendingNonce: "attempt-1", - }), - ); - - h.sendLogin(SUPABASE_AUTH, "attempt-1"); - - await vi.waitFor(() => expect(h.pendingTimerCount()).toBe(1)); - expect( - h.posts.some((p) => p.type === "dyad-auth-ready" && p.ok === true), - ).toBe(false); - - h.flushTimers(); - - expect( - h.posts.some((p) => p.type === "dyad-auth-ready" && p.ok === true), - ).toBe(true); - expect(h.posts).toContainEqual( - expect.objectContaining({ - type: "replaceState", - payload: { newUrl: "http://localhost:42100/" }, - }), - ); - // Verified against Supabase itself, not against the value this script wrote - // — localStorage survives the reload, so re-reading it proves nothing. - expect(h.fetchMock).toHaveBeenCalledWith( - "https://ref123.supabase.co/auth/v1/user", - expect.objectContaining({ - headers: expect.objectContaining({ - apikey: "anon-key", - Authorization: "Bearer a", - }), - }), - ); - // The pending marker is consumed so a later reload doesn't re-verify. - expect(h.sessionStorage.getItem("__dyad_auth_pending__")).toBeNull(); - }); - - // Newer supabase-js re-saves the session under a `base64-` encoding once its - // own client reads the slot. That is still an authenticated app, so the token - // has to come back out rather than reading as "no session". - it("verifies a supabase session the app re-saved in base64 form", async () => { - const session = JSON.stringify({ access_token: "a", user: { id: "u" } }); - const h = setup({ - pending: { - mode: "supabase-password", - ref: "ref123", - nonce: "attempt-1", - }, - preLocal: { - "sb-ref123-auth-token": `base64-${Buffer.from(session, "utf8") - .toString("base64url") - .replace(/=+$/, "")}`, - }, - fetchImpl: async () => ({ ok: true, json: async () => ({ id: "u" }) }), - }); - - h.sendLogin(SUPABASE_AUTH, "attempt-1"); - - await vi.waitFor(() => expect(h.pendingTimerCount()).toBe(1)); - h.flushTimers(); - expect( - h.posts.some((p) => p.type === "dyad-auth-ready" && p.ok === true), - ).toBe(true); - }); - - // The seeded write always succeeds; only Supabase can say whether the app's - // client actually holds a session. Reporting `ok` here would record a - // signed-out flow into a spec whose `signIn` fixture claims otherwise. - it("fails supabase verification when the seeded session is rejected", async () => { - const h = setup({ - pending: { - mode: "supabase-password", - ref: "ref123", - nonce: "attempt-1", - }, - preLocal: { "sb-ref123-auth-token": '{"access_token":"a"}' }, - fetchImpl: async () => ({ - ok: false, - status: 401, - json: async () => ({}), - }), - }); - - h.sendLogin(SUPABASE_AUTH, "attempt-1"); - - await vi.waitFor(() => - expect( - h.posts.some((p) => p.type === "dyad-auth-ready" && p.ok === false), - ).toBe(true), - ); - expect(h.sessionStorage.getItem("__dyad_auth_pending__")).toBeNull(); - }); - - it("verifies a pending Neon session via get-session", async () => { - const h = setup({ - pending: { mode: "neon-better-auth", nonce: "attempt-1" }, - fetchImpl: async () => ({ - ok: true, - json: async () => ({ user: { id: "u" } }), - }), - }); - - h.sendLogin(NEON_AUTH, "attempt-1"); - - await vi.waitFor(() => expect(h.pendingTimerCount()).toBe(1)); - h.flushTimers(); - expect( - h.posts.some((p) => p.type === "dyad-auth-ready" && p.ok === true), - ).toBe(true); - expect(h.fetchMock).toHaveBeenCalledWith( - "/api/auth/get-session", - expect.objectContaining({ credentials: "include" }), - ); - }); - - it("returns to / when the app auth guard redirects during session startup", async () => { - const h = setup({ - pending: { - mode: "supabase-password", - ref: "ref123", - nonce: "attempt-1", - }, - preLocal: { "sb-ref123-auth-token": '{"access_token":"a"}' }, - fetchImpl: async () => ({ ok: true, json: async () => ({ id: "u" }) }), - }); - - h.sendLogin(SUPABASE_AUTH, "attempt-1"); - - await vi.waitFor(() => expect(h.pendingTimerCount()).toBe(1)); - // Simulate a protected-route effect moving the iframe after the bootstrap - // has verified storage but before it acknowledges authentication. - h.setPathname("/login"); - // The move itself only re-arms the settle window; it is the URL *resting* - // on a login route that identifies the guard race. - h.flushTimers(); - expect(h.replace).not.toHaveBeenCalled(); - h.flushTimers(); - - expect(h.replace).toHaveBeenCalledWith("/"); - expect( - h.posts.some((p) => p.type === "dyad-auth-ready" && p.ok === true), - ).toBe(false); - expect( - JSON.parse(h.sessionStorage.getItem("__dyad_auth_pending__")!), - ).toMatchObject({ - mode: "supabase-password", - ref: "ref123", - homeRedirects: 1, - }); - }); - - it("accepts a stable landing route as the post-login destination", async () => { - // An app that sends authenticated users from "/" to "/dashboard" has signed - // in successfully. Reporting failure here would leave the established - // session in place while the parent downgrades the draft to - // `authMode: "none"`, so the generated spec omits `signIn(page)` and - // replays the dashboard flow from a signed-out context. - const h = setup({ - pending: { - mode: "supabase-password", - ref: "ref123", - nonce: "attempt-1", - }, - preLocal: { "sb-ref123-auth-token": '{"access_token":"a"}' }, - fetchImpl: async () => ({ ok: true, json: async () => ({ id: "u" }) }), - }); - - h.sendLogin(SUPABASE_AUTH, "attempt-1"); - - await vi.waitFor(() => expect(h.pendingTimerCount()).toBe(1)); - h.setPathname("/dashboard"); - // First window sees the move and re-arms; the second finds it at rest. - h.flushTimers(); - h.flushTimers(); - - expect(h.replace).not.toHaveBeenCalled(); - // The settled route rides along, so the parent can open the spec on the page - // the capture actually ran against. - expect(h.posts).toContainEqual( - expect.objectContaining({ - type: "dyad-auth-ready", - ok: true, - path: "/dashboard", - }), - ); - // The toolbar follows the iframe to wherever the app actually landed. - expect(h.posts).toContainEqual({ - type: "replaceState", - payload: { newUrl: "http://localhost:42100/dashboard" }, - }); - expect(h.sessionStorage.getItem("__dyad_auth_pending__")).toBeNull(); - }); - - it("gives up when the app never comes to rest after sign-in", async () => { - const h = setup({ - pending: { mode: "neon-better-auth", nonce: "attempt-1" }, - fetchImpl: async () => ({ - ok: true, - json: async () => ({ user: { id: "u" } }), - }), - }); - - h.sendLogin(NEON_AUTH, "attempt-1"); - - await vi.waitFor(() => expect(h.pendingTimerCount()).toBe(1)); - // Moving on every window: the destination itself is the unstable thing, so - // extra settle windows never find it at rest. - for (const next of ["/a", "/b", "/c"]) { - h.setPathname(next); - h.flushTimers(); - } - - expect(h.replace).toHaveBeenCalledWith("/"); - expect( - JSON.parse(h.sessionStorage.getItem("__dyad_auth_pending__")!), - ).toMatchObject({ homeRedirects: 1 }); - }); - - it("signs in fresh when the marker belongs to an abandoned attempt", async () => { - // A prior attempt crashed or was cancelled inside the 15-second TTL, so its - // marker is still there and still "fresh". Verifying it would check cookies - // and localStorage that this recording's setup already cleared, report a - // phantom sign-in failure, and start the session signed out. - const h = setup({ - pending: { mode: "neon-better-auth", nonce: "attempt-0" }, - }); - h.fetchMock.mockResolvedValue({ ok: true }); - - expect(h.posts).toContainEqual( - expect.objectContaining({ - type: "dyad-auth-bootstrap-ready", - pendingNonce: "attempt-0", - }), - ); - - h.sendLogin(NEON_AUTH, "attempt-1"); - - await vi.waitFor(() => expect(h.replace).toHaveBeenCalledWith("/")); - expect(h.fetchMock).toHaveBeenCalledWith( - "/api/auth/sign-in/email", - expect.objectContaining({ method: "POST" }), - ); - expect( - h.posts.some((p) => p.type === "dyad-auth-ready" && p.ok === false), - ).toBe(false); - // The abandoned marker was replaced by this attempt's own. - expect( - JSON.parse(h.sessionStorage.getItem("__dyad_auth_pending__")!), - ).toMatchObject({ mode: "neon-better-auth", nonce: "attempt-1" }); - }); - - it("ignores a stale pending marker left by a previous session", () => { - const h = setup({ - pending: { - mode: "neon-better-auth", - homeRedirects: 0, - // Older than PENDING_TTL_MS (45s) — leftover from a prior session. - startedAt: Date.now() - 60_000, - }, - }); - - // Rather than verifying the (non-existent) session and reporting failure, - // the bootstrap drops the marker and announces readiness for a fresh login. - expect(h.posts.some((p) => p.type === "dyad-auth-bootstrap-ready")).toBe( - true, - ); - expect( - h.posts.some((p) => p.type === "dyad-auth-ready" && p.ok === false), - ).toBe(false); - expect(h.sessionStorage.getItem("__dyad_auth_pending__")).toBeNull(); - expect(h.fetchMock).not.toHaveBeenCalled(); - }); -}); diff --git a/studio/vendor/dyad/src/__tests__/dyad_logs.test.ts b/studio/vendor/dyad/src/__tests__/dyad_logs.test.ts deleted file mode 100644 index 0290a691..00000000 --- a/studio/vendor/dyad/src/__tests__/dyad_logs.test.ts +++ /dev/null @@ -1,195 +0,0 @@ -import { readFileSync } from "node:fs"; -import { resolve } from "node:path"; -import { runInNewContext } from "node:vm"; -import { describe, expect, it, vi } from "vitest"; - -interface PostedConsoleMessage { - type: string; - args: string[]; -} - -type ConsoleMethod = (...args: unknown[]) => void; - -const DYAD_LOGS_SCRIPT = readFileSync( - resolve(__dirname, "../../worker/dyad_logs.js"), - "utf8", -); - -function loadConsoleInterceptor() { - const messages: PostedConsoleMessage[] = []; - const originalLog = vi.fn(); - const scriptConsole: Record< - "log" | "warn" | "error" | "info" | "debug", - ConsoleMethod - > = { - log: originalLog, - warn: vi.fn(), - error: vi.fn(), - info: vi.fn(), - debug: vi.fn(), - }; - - runInNewContext(DYAD_LOGS_SCRIPT, { - console: scriptConsole, - window: { - parent: { - postMessage(message: PostedConsoleMessage) { - messages.push(message); - }, - }, - }, - }); - - return { messages, originalLog, scriptConsole }; -} - -describe("dyad console interception", () => { - it("bounds giant values and argument lists before posting to the parent", () => { - const { messages, originalLog, scriptConsole } = loadConsoleInterceptor(); - const args = Array.from( - { length: 25 }, - (_, index) => `${index}:${"x".repeat(20_000)}`, - ); - - scriptConsole.log(...args); - - expect(messages).toHaveLength(1); - expect(messages[0].type).toBe("console-log"); - expect(messages[0].args[0]).toContain("[console value truncated]"); - expect(messages[0].args.at(-1)).toMatch(/arguments omitted\]$/); - expect( - messages[0].args.every( - (arg) => Buffer.byteLength(arg, "utf8") <= 8 * 1024, - ), - ).toBe(true); - expect( - messages[0].args.reduce( - (total, arg) => total + Buffer.byteLength(arg, "utf8"), - 0, - ), - ).toBeLessThanOrEqual(64 * 1024); - expect(originalLog).toHaveBeenCalledWith(...args); - }); - - it("preserves up to 20 small arguments before adding an omission marker", () => { - const { messages, scriptConsole } = loadConsoleInterceptor(); - const args = Array.from({ length: 25 }, (_, index) => `arg-${index}`); - - scriptConsole.log(...args); - - expect(messages[0].args.slice(0, 20)).toEqual(args.slice(0, 20)); - expect(messages[0].args.at(-1)).toBe("… [5 arguments omitted]"); - }); - - it("bounds deep and circular object traversal", () => { - const { messages, scriptConsole } = loadConsoleInterceptor(); - const circular: Record = {}; - circular.self = circular; - let deep: Record = { value: "leaf" }; - for (let index = 0; index < 20; index++) { - deep = { child: deep }; - } - const hugeKey = `key-${"x".repeat(10_000)}`; - - scriptConsole.log(circular, deep, { [hugeKey]: "value" }); - - expect(messages).toHaveLength(1); - expect(messages[0].args[0]).toContain("[Circular]"); - expect(messages[0].args[1]).toContain("[Maximum log depth reached]"); - expect(messages[0].args[2]).toContain("[console value truncated]"); - }); - - it("preserves up to 50 object keys before marking additional keys", () => { - const { messages, scriptConsole } = loadConsoleInterceptor(); - const wideObject = Object.fromEntries( - Array.from({ length: 60 }, (_, index) => [`key-${index}`, index]), - ); - - scriptConsole.log(wideObject); - - const serialized = JSON.parse(messages[0].args[0]); - expect(serialized["key-49"]).toBe(49); - expect(serialized["key-50"]).toBeUndefined(); - expect(serialized.__dyad_truncated__).toBe("Additional keys omitted"); - }); - - it("honors toJSON while retaining the output byte limit", () => { - const { messages, scriptConsole } = loadConsoleInterceptor(); - const date = new Date("2026-07-10T00:00:00.000Z"); - const custom = { - toJSON: () => ({ value: "x".repeat(20_000) }), - }; - - scriptConsole.log(date, custom); - - expect(JSON.parse(messages[0].args[0])).toBe(date.toISOString()); - expect(messages[0].args[1]).toContain("[console value truncated]"); - expect(Buffer.byteLength(messages[0].args[1], "utf8")).toBeLessThanOrEqual( - 8 * 1024, - ); - }); - - it("applies the depth limit to chained toJSON results", () => { - const { messages, scriptConsole } = loadConsoleInterceptor(); - const createToJsonChain = (remainingDepth: number): unknown => ({ - toJSON: () => - remainingDepth === 0 ? "leaf" : createToJsonChain(remainingDepth - 1), - }); - - scriptConsole.log(createToJsonChain(20)); - - expect(messages[0].args[0]).toContain("[Maximum log depth reached]"); - }); - - it("preserves empty object keys without skipping later properties", () => { - const { messages, scriptConsole } = loadConsoleInterceptor(); - - scriptConsole.log({ "": "empty-key value", after: "later value" }); - - expect(JSON.parse(messages[0].args[0])).toEqual({ - "": "empty-key value", - after: "later value", - }); - }); - - it("marks arrays and objects when their inner byte budget is exhausted", () => { - const { messages, scriptConsole } = loadConsoleInterceptor(); - const hugeValue = "x".repeat(20_000); - - scriptConsole.log([hugeValue, hugeValue, "omitted array value"], { - first: hugeValue, - second: hugeValue, - third: "omitted object value", - }); - - expect(messages[0].args[0]).toContain("[console value truncated]"); - expect(messages[0].args[1]).toContain("[console value truncated]"); - }); - - it("stops reading nested values when the argument byte budget is exhausted", () => { - const { messages, scriptConsole } = loadConsoleInterceptor(); - let getterReads = 0; - const nested: Record = {}; - - for (let outer = 0; outer < 20; outer++) { - const child: Record = {}; - for (let inner = 0; inner < 20; inner++) { - Object.defineProperty(child, `value-${inner}`, { - enumerable: true, - get() { - getterReads++; - return "x".repeat(4 * 1024); - }, - }); - } - nested[`child-${outer}`] = child; - } - - scriptConsole.log(nested); - - expect(getterReads).toBeLessThan(10); - expect(Buffer.byteLength(messages[0].args[0], "utf8")).toBeLessThanOrEqual( - 8 * 1024, - ); - }); -}); diff --git a/studio/vendor/dyad/src/__tests__/dyad_recorder_client.test.ts b/studio/vendor/dyad/src/__tests__/dyad_recorder_client.test.ts deleted file mode 100644 index d8c9147a..00000000 --- a/studio/vendor/dyad/src/__tests__/dyad_recorder_client.test.ts +++ /dev/null @@ -1,1205 +0,0 @@ -import fs from "node:fs"; -import path from "node:path"; -import vm from "node:vm"; -import { Window } from "happy-dom"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -const recorderSource = fs.readFileSync( - path.resolve(process.cwd(), "worker/dyad-recorder-client.js"), - "utf8", -); - -const CLICK_DEBOUNCE_MS = 200; -const RECORDER_TOKEN = "proxy-session-token"; - -type AnyEl = any; - -/** - * Load the recorder client into a fresh vm context that shares a real - * happy-dom document (so selector generation and event dispatch exercise a real - * DOM), while `window` is a controllable mock that captures postMessage traffic - * and the registered message handler. - */ -function setup({ allowUntrusted = true }: { allowUntrusted?: boolean } = {}) { - const hw = new Window({ url: "https://preview.test/" }); - const doc: AnyEl = hw.document; - const removedAttributes: string[] = []; - Object.defineProperty(doc, "currentScript", { - configurable: true, - value: { - dataset: { dyadRecorderToken: RECORDER_TOKEN }, - removeAttribute: (name: string) => removedAttributes.push(name), - }, - }); - - const messages: any[] = []; - const actions: any[] = []; - const parent = { - postMessage: (msg: any) => { - messages.push(msg); - if (msg && msg.type === "dyad-recorder-action") actions.push(msg.action); - }, - }; - - let messageHandler: ((e: any) => void) | undefined; - const win: any = { - parent, - CSS: (hw as any).CSS, - MutationObserver: (hw as any).MutationObserver, - __DYAD_RECORDER_ALLOW_UNTRUSTED__: allowUntrusted, - addEventListener: (type: string, handler: any) => { - if (type === "message") messageHandler = handler; - }, - removeEventListener: () => {}, - }; - win.window = win; - - const sandbox: any = { - window: win, - document: doc, - MutationObserver: (hw as any).MutationObserver, - console: { debug() {}, warn() {}, error() {}, log() {} }, - setTimeout: (fn: any, ms?: number) => setTimeout(fn, ms), - clearTimeout: (id: any) => clearTimeout(id), - Date, - }; - - vm.runInNewContext(recorderSource, sandbox); - if (!messageHandler) { - throw new Error("recorder client did not register a message handler"); - } - // Ensure the "initialized" ping fires regardless of happy-dom readyState. - if (!messages.some((m) => m.type === "dyad-recorder-initialized")) { - doc.dispatchEvent(new hw.Event("DOMContentLoaded")); - } - - const setHtml = (html: string) => { - doc.body.innerHTML = html; - }; - const activate = (token = RECORDER_TOKEN) => - messageHandler!({ - source: parent, - data: { type: "activate-dyad-recorder", token }, - }); - const deactivate = () => - messageHandler!({ - source: parent, - data: { type: "deactivate-dyad-recorder", token: RECORDER_TOKEN }, - }); - const flush = (requestId: string) => - messageHandler!({ - source: parent, - data: { - type: "flush-dyad-recorder", - token: RECORDER_TOKEN, - requestId, - }, - }); - - const click = (el: AnyEl) => - el.dispatchEvent( - new hw.MouseEvent("click", { bubbles: true, cancelable: true }), - ); - const dblclick = (el: AnyEl) => - el.dispatchEvent(new hw.MouseEvent("dblclick", { bubbles: true })); - const typeInto = (el: AnyEl, value: string) => { - el.value = value; - el.dispatchEvent(new hw.Event("input", { bubbles: true })); - }; - const change = (el: AnyEl) => - el.dispatchEvent(new hw.Event("change", { bubbles: true })); - const keydown = (el: AnyEl, init: Record) => - el.dispatchEvent( - new hw.KeyboardEvent("keydown", { bubbles: true, ...init }), - ); - const mousemove = (el: AnyEl) => - el.dispatchEvent(new hw.MouseEvent("mousemove", { bubbles: true })); - const overlays = () => doc.querySelectorAll(".__dyad_recorder_overlay__"); - - return { - hw, - doc, - win, - messages, - actions, - setHtml, - activate, - deactivate, - flush, - click, - dblclick, - typeInto, - change, - keydown, - mousemove, - overlays, - removedAttributes, - settleClick: () => vi.advanceTimersByTime(CLICK_DEBOUNCE_MS), - }; -} - -beforeEach(() => { - vi.useFakeTimers(); -}); -afterEach(() => { - vi.useRealTimers(); -}); - -describe("dyad recorder client", () => { - it("refuses recorder activation without the proxy capability", () => { - const r = setup(); - r.setHtml(``); - r.activate("attacker-controlled-token"); - r.typeInto(r.doc.querySelector("input"), "private@example.com"); - - expect(r.actions).toEqual([]); - }); - - // The capability is what stops an unrelated page framing the preview and - // receiving every captured fill value. Left on the script tag it would sit in - // the document for any script the app loads — including CDN code in an - // AI-generated app — to lift with one `querySelector`. - it("takes the capability out of the DOM once it has read it", () => { - const r = setup(); - - expect(r.removedAttributes).toContain("data-dyad-recorder-token"); - // Still armed by the real token: the value was snapshotted, not lost. - r.setHtml(``); - r.activate(); - r.click(r.doc.querySelector("button")); - r.settleClick(); - expect(r.actions).toHaveLength(1); - }); - - it("reports a click immediately, leaving the dblclick merge to the renderer", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - const btn = r.doc.querySelector("button"); - r.click(btn); - // Nothing is stalled waiting for a possible double-click: a click that - // navigates unloads this document long before any debounce would fire, and - // the click would be lost with it. `collapseActions` folds the leading - // clicks into the dblclick during review instead. - expect(r.actions).toHaveLength(1); - - r.dblclick(btn); - r.settleClick(); - - const locator = { - kind: "role", - value: "button", - name: "Open", - exact: true, - }; - expect(r.actions).toEqual([ - { kind: "click", locator }, - { kind: "dblclick", locator }, - ]); - }); - - it("acknowledges a flush after actions already sent to the parent", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - r.click(r.doc.querySelector("button")); - r.flush("flush-1"); - - expect(r.messages.slice(-2)).toEqual([ - expect.objectContaining({ type: "dyad-recorder-action" }), - { type: "dyad-recorder-flushed", requestId: "flush-1" }, - ]); - }); - - it("records two different controls clicked in quick succession", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - const [first, second] = r.doc.querySelectorAll("button"); - r.click(first); - r.click(second); - - expect(r.actions.map((a: any) => a.locator.name)).toEqual([ - "First", - "Second", - ]); - }); - - it("records a label-activated button only once against the control", () => { - const r = setup(); - r.setHtml( - `` + - ``, - ); - r.activate(); - - // Browsers deliver the pointer click to the label, then dispatch their own - // trusted activation click on the associated button. - r.click(r.doc.querySelector("label")); - r.click(r.doc.querySelector("button")); - - expect(r.actions).toEqual([ - { - kind: "click", - locator: { - kind: "role", - value: "button", - name: "Send order", - exact: true, - }, - }, - ]); - }); - - it("retargets a double-clicked label to the same control locator", () => { - const r = setup(); - r.setHtml( - `` + - ``, - ); - r.activate(); - const label = r.doc.querySelector("label"); - const button = r.doc.querySelector("button"); - - r.click(label); - r.click(button); - r.dblclick(label); - - expect(r.actions.map((action: any) => action.kind)).toEqual([ - "click", - "dblclick", - ]); - expect(r.actions[1].locator).toEqual(r.actions[0].locator); - }); - - it("uses the spinbutton role for a number input", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - r.typeInto(r.doc.querySelector("input"), "3"); - - expect(r.actions).toEqual([ - { - kind: "fill", - locator: { - kind: "role", - value: "spinbutton", - name: "Quantity", - exact: true, - }, - value: "3", - }, - ]); - }); - - it("takes the first supported token from a fallback role list", () => { - const r = setup(); - // Valid ARIA: the browser resolves the first token it knows, so this is a - // switch. Emitting `getByRole("switch checkbox")` would match nothing. - r.setHtml(`
on
`); - r.activate(); - r.click(r.doc.querySelector("[role]")); - - expect(r.actions).toEqual([ - { - kind: "click", - locator: { kind: "role", value: "switch", name: "Wifi", exact: true }, - }, - ]); - }); - - it("skips unknown role tokens instead of emitting them", () => { - const r = setup(); - r.setHtml(`
S
`); - r.activate(); - r.click(r.doc.querySelector("[role]")); - - expect(r.actions).toEqual([ - { - kind: "click", - locator: { kind: "role", value: "menuitem", name: "Save", exact: true }, - }, - ]); - }); - - it("falls back to the implicit role when no token is a real role", () => { - const r = setup(); - // Browsers ignore an unrecognised `role` wholesale, leaving the native one. - r.setHtml(``); - r.activate(); - r.click(r.doc.querySelector("button")); - - expect(r.actions).toEqual([ - { - kind: "click", - locator: { kind: "role", value: "button", name: "Save", exact: true }, - }, - ]); - }); - - it("does not retarget to a wrapper whose live role is presentational", () => { - const r = setup(); - // `role="presentation button"` resolves to `presentation` — the wrapper is - // not a button, it just mentions one. Retargeting to it would record the - // click against the wrapper and leave the real target's handler unexercised - // on replay. - r.setHtml( - `
Save
`, - ); - r.activate(); - r.click(r.doc.querySelector("[data-testid='save']")); - r.settleClick(); - - expect(r.actions).toEqual([ - { kind: "click", locator: { kind: "testid", value: "save" } }, - ]); - }); - - it("still retargets to a wrapper whose live role is interactive", () => { - const r = setup(); - // Here `button` is the first supported token, so the wrapper really is a - // button and the click belongs to it rather than to the label inside. - r.setHtml( - `
Save
`, - ); - r.activate(); - r.click(r.doc.querySelector("span")); - r.settleClick(); - - expect(r.actions).toEqual([ - { - kind: "click", - locator: { kind: "role", value: "button", name: "Save", exact: true }, - }, - ]); - }); - - it("records a page-level shortcut without a locator", () => { - const r = setup(); - r.setHtml(`

nothing focused

`); - r.activate(); - r.keydown(r.doc.body, { key: "Escape" }); - - expect(r.actions).toEqual([{ kind: "press", key: "Escape" }]); - }); - - it("records Space activation for custom interactive roles", () => { - const r = setup(); - r.setHtml( - `
`, - ); - r.activate(); - r.keydown(r.doc.querySelector("[role=switch]"), { key: " " }); - - expect(r.actions).toEqual([ - { - kind: "press", - key: " ", - locator: { - kind: "role", - value: "switch", - name: "Notifications", - exact: true, - }, - }, - ]); - }); - - it("records Space on an anchor-based ARIA button", () => { - // An anchor is a native interactive tag, but it activates on Enter only — - // nothing synthesizes a click for Space. The app's own keydown handler is - // the whole interaction, so a press left unrecorded here means replay - // silently omits it. - const r = setup(); - r.setHtml(`Save`); - r.activate(); - r.keydown(r.doc.querySelector("a"), { key: " " }); - - expect(r.actions).toEqual([ - { - kind: "press", - key: " ", - locator: { - kind: "role", - value: "button", - name: "Save", - exact: true, - }, - }, - ]); - }); - - it("still ignores Space on controls the browser acts on itself", () => { - // The other half of the same rule: these produce a click, a toggle or a - // typed character the recorder already captures, so recording the press - // too would replay the action twice. - const r = setup(); - r.setHtml( - `` + - `` + - `` + - `Next`, - ); - r.activate(); - for (const selector of ["button", "input", "textarea", "a"] as const) { - r.keydown(r.doc.querySelector(selector), { key: " " }); - } - - expect(r.actions).toEqual([]); - }); - - it("falls back to a body selector rather than an empty one", () => { - const r = setup(); - r.setHtml(`

background

`); - r.activate(); - r.click(r.doc.body); - - expect(r.actions).toEqual([ - { kind: "click", locator: { kind: "css", value: "body" } }, - ]); - }); - - it("redacts a password field revealed before the recorder ever saw it", () => { - const r = setup(); - // A name that reads as ordinary, so only the type flip can catch it. - r.setHtml(``); - r.activate(); - const input = r.doc.querySelector("input"); - // Never hovered, never clicked, never typed into while masked — the app's - // reveal toggle is the recorder's first sight of this control. - input.setAttribute("type", "text"); - r.typeInto(input, "hunter2"); - - expect(r.actions.map((action: any) => action.value)).toEqual([ - "REPLACE_WITH_PASSWORD", - ]); - expect(JSON.stringify(r.actions)).not.toContain("hunter2"); - }); - - it("records typing as a growing fill, never as key presses", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - const input = r.doc.querySelector("input"); - r.typeInto(input, "a"); - r.typeInto(input, "ab"); - r.keydown(input, { key: "b" }); - - expect(r.actions).toEqual([ - { - kind: "fill", - locator: { kind: "placeholder", value: "Email", exact: true }, - value: "a", - }, - { - kind: "fill", - locator: { kind: "placeholder", value: "Email", exact: true }, - value: "ab", - }, - ]); - }); - - it("redacts a typed password instead of capturing the plaintext value", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - const input = r.doc.querySelector("input"); - r.typeInto(input, "hunter2"); - - expect(r.actions).toEqual([ - { - kind: "fill", - locator: { kind: "label", value: "Password", exact: true }, - value: "REPLACE_WITH_PASSWORD", - }, - ]); - }); - - it("keeps redacting a password field after a show/hide toggle reveals it", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - const input = r.doc.querySelector("input"); - // Typed while masked, so the field is observed as a password... - r.typeInto(input, "hunter"); - // ...then the app's reveal toggle flips it to plain text. Everything typed - // after that would otherwise be captured verbatim into a committed spec. - input.setAttribute("type", "text"); - r.typeInto(input, "hunter2"); - - // Every value stayed redacted (identical consecutive fills collapse, so one - // action is expected) and no plaintext reached the parent. - expect(r.actions.map((action: any) => action.value)).toEqual([ - "REPLACE_WITH_PASSWORD", - ]); - expect(JSON.stringify(r.actions)).not.toContain("hunter"); - }); - - it("redacts a secret-bearing field that was never type=password", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - r.typeInto(r.doc.querySelector("input"), "sk-live-abc123"); - - expect(r.actions).toEqual([ - { - kind: "fill", - locator: { kind: "placeholder", value: "API key", exact: true }, - value: "REPLACE_WITH_PASSWORD", - }, - ]); - }); - - it("records an ordinary field's value verbatim", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - r.typeInto(r.doc.querySelector("input"), "someone@example.com"); - - expect(r.actions).toEqual([ - { - kind: "fill", - locator: { kind: "placeholder", value: "Email address", exact: true }, - value: "someone@example.com", - }, - ]); - }); - - it("records checkbox and radio toggles from change events", () => { - const r = setup(); - r.setHtml( - `` + - ``, - ); - r.activate(); - const checkbox = r.doc.querySelector('input[type="checkbox"]'); - const radio = r.doc.querySelector('input[type="radio"]'); - - checkbox.checked = true; - r.change(checkbox); - checkbox.checked = false; - r.change(checkbox); - radio.checked = true; - r.change(radio); - - expect(r.actions).toEqual([ - { - kind: "check", - locator: { - kind: "role", - value: "checkbox", - name: "Subscribe", - exact: true, - }, - }, - { - kind: "uncheck", - locator: { - kind: "role", - value: "checkbox", - name: "Subscribe", - exact: true, - }, - }, - { - kind: "check", - locator: { kind: "role", value: "radio", name: "Plan", exact: true }, - }, - ]); - }); - - it("leaves a double-clicked checkbox to its change events", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - const checkbox = r.doc.querySelector('input[type="checkbox"]'); - - // Both clicks composing the gesture toggle the box, so the browser fires a - // `change` for each before the `dblclick` arrives. - checkbox.checked = true; - r.change(checkbox); - checkbox.checked = false; - r.change(checkbox); - r.dblclick(checkbox); - - // No `dblclick`: replaying one on top of check + uncheck would activate the - // box four times where the user activated it twice. - expect(r.actions.map((action: any) => action.kind)).toEqual([ - "check", - "uncheck", - ]); - }); - - it("records a dropdown choice as a select with the chosen value", () => { - const r = setup(); - r.setHtml( - `` + - ``, - ); - r.activate(); - const select = r.doc.querySelector("select"); - select.value = "blue"; - r.change(select); - - // A select is a combobox only while it presents one row at a time — that is - // what Playwright matches it as, so anything else generates a locator that - // never resolves. - expect(r.actions).toEqual([ - { - kind: "select", - locator: { - kind: "role", - value: "combobox", - name: "Colour", - exact: true, - }, - values: ["blue"], - }, - ]); - }); - - it("records a range pick as a single fill and drops its click", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - const range = r.doc.querySelector("input"); - - // The user drags the thumb: a click on the track, then `change` when the - // value commits. Only the value is replayable — Playwright sets these - // directly, and a recorded click on the track lands wherever the layout - // happens to put it at replay. - r.click(range); - range.value = "80"; - r.change(range); - r.settleClick(); - - expect(r.actions).toEqual([ - { - kind: "fill", - locator: { - kind: "role", - value: "slider", - name: "Volume", - exact: true, - }, - value: "80", - }, - ]); - }); - - it("records a colour pick as a single fill and drops its click", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - const picker = r.doc.querySelector("input"); - - r.click(picker); - picker.value = "#ff8800"; - r.change(picker); - r.settleClick(); - - expect(r.actions.map((action: any) => action.kind)).toEqual(["fill"]); - expect(r.actions[0].value).toBe("#ff8800"); - }); - - it("does not also record the arrow keys that drove a native control", () => { - const r = setup(); - r.setHtml( - `` + - `` + - `` + - ``, - ); - r.activate(); - const select = r.doc.querySelector("select"); - const range = r.doc.querySelector('input[type="range"]'); - const number = r.doc.querySelector('input[type="number"]'); - - // Keyboard users change these without ever clicking. The keypress and the - // value action describe the SAME change, so recording both replays it - // twice and lands on a value the user never chose. - r.keydown(select, { key: "ArrowDown" }); - select.value = "blue"; - r.change(select); - r.keydown(range, { key: "ArrowRight" }); - range.value = "51"; - r.change(range); - // A number input steps on arrows exactly as the slider does — its value - // change arrives as `input`, which is already recorded as the fill. - r.keydown(number, { key: "ArrowUp" }); - r.typeInto(number, "2"); - - expect(r.actions.map((action: any) => action.kind)).toEqual([ - "select", - "fill", - "fill", - ]); - }); - - // Arrows do nothing to a checkbox: no group to walk, so no `change` follows - // to stand in for the press. Suppressing it would erase a keyboard-only - // interaction with the app's own handler from the recording. - it("still records arrow keys on a checkbox, which no change follows", () => { - const r = setup(); - r.setHtml( - ``, - ); - r.activate(); - - r.keydown(r.doc.querySelector('input[type="checkbox"]'), { - key: "ArrowDown", - }); - - expect(r.actions.map((action: any) => action.kind)).toEqual(["press"]); - }); - - // Escape shares NAV_KEYS with the arrows but drives nothing, so the - // arrow-suppression must not reach it on any of these controls. - it("still records Escape on controls that arrows would drive", () => { - const r = setup(); - r.setHtml( - `` + - `` + - ``, - ); - r.activate(); - - for (const selector of [ - "select", - 'input[type="range"]', - 'input[type="radio"]', - ]) { - r.keydown(r.doc.querySelector(selector), { key: "Escape" }); - } - - expect(r.actions.map((action: any) => action.kind)).toEqual([ - "press", - "press", - "press", - ]); - }); - - it("still records arrow keys in a text field, which no change follows", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - - r.keydown(r.doc.querySelector("input"), { key: "ArrowLeft" }); - - expect(r.actions.map((action: any) => action.kind)).toEqual(["press"]); - }); - - // Only up and down step a number input. Left and right move the caret exactly - // as in a text field, so no `change` follows to stand in for the press. - it("still records horizontal arrows on a number input", () => { - const r = setup(); - r.setHtml( - ``, - ); - r.activate(); - const number = r.doc.querySelector('input[type="number"]'); - - r.keydown(number, { key: "ArrowLeft" }); - r.keydown(number, { key: "ArrowRight" }); - - expect(r.actions.map((action: any) => action.kind)).toEqual([ - "press", - "press", - ]); - expect(r.actions.map((action: any) => action.key)).toEqual([ - "ArrowLeft", - "ArrowRight", - ]); - }); - - it("uses the accessible text from every native label", () => { - const r = setup(); - r.setHtml( - `` + - `` + - ``, - ); - r.activate(); - r.typeInto(r.doc.querySelector("input"), "person@example.com"); - - expect(r.actions).toEqual([ - { - kind: "fill", - locator: { - kind: "role", - value: "textbox", - name: "Email address", - exact: true, - }, - value: "person@example.com", - }, - ]); - }); - - it("prefers aria-labelledby over aria-label, as the name algorithm does", () => { - // Playwright implements accname faithfully, so on an element carrying both - // it computes the referenced text. Naming the locator from `aria-label` - // would look unique to the scan here and match nothing at replay. - const r = setup(); - r.setHtml( - `Account email` + - ``, - ); - r.activate(); - r.typeInto(r.doc.querySelector("input"), "person@example.com"); - - expect(r.actions[0]?.locator).toEqual({ - kind: "role", - value: "textbox", - name: "Account email", - exact: true, - }); - }); - - it("falls back to aria-label when aria-labelledby names nothing", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - r.typeInto(r.doc.querySelector("input"), "person@example.com"); - - expect(r.actions[0]?.locator).toMatchObject({ name: "Email" }); - }); - - it("uses text from a hidden aria-labelledby reference", () => { - const r = setup(); - r.setHtml( - `` + - ``, - ); - r.activate(); - r.typeInto(r.doc.querySelector("input"), "person@example.com"); - - expect(r.actions[0]?.locator).toEqual({ - kind: "role", - value: "textbox", - name: "Account email", - exact: true, - }); - }); - - it("records a multi-select as a listbox with every chosen value", () => { - const r = setup(); - r.setHtml( - ``, - ); - r.activate(); - const select = r.doc.querySelector("select"); - select.options[0].selected = true; - select.options[2].selected = true; - r.change(select); - - // `multiple` makes it a list, and Playwright matches it as `listbox`. - expect(r.actions).toEqual([ - { - kind: "select", - locator: { - kind: "role", - value: "listbox", - name: "Toppings", - exact: true, - }, - values: ["ham", "basil"], - }, - ]); - }); - - // Enter in a text field inside a form submits it, and the browser delivers - // that submission as its own trusted click on the default submit button. - // Recording both replays the submission twice — and since the press navigates - // first, the duplicate click usually lands on the destination document. - it("records an implicit form submit once, not as a press and a click", () => { - const r = setup(); - r.setHtml( - `
`, - ); - r.activate(); - - r.keydown(r.doc.querySelector("input"), { key: "Enter" }); - r.click(r.doc.querySelector("button")); - - expect(r.actions.map((a: any) => a.kind)).toEqual(["press"]); - }); - - it("records Enter pressed on a button as the click it dispatches", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - const button = r.doc.querySelector("button"); - - // The press is suppressed instead, so the browser's own click is the single - // record of the action. Suppressing the click here would drop it entirely. - r.keydown(button, { key: "Enter" }); - r.click(button); - - expect(r.actions.map((a: any) => a.kind)).toEqual(["click"]); - }); - - it("keeps recording a click made after the implicit-submit window", () => { - const r = setup(); - r.setHtml( - `
`, - ); - r.activate(); - - r.keydown(r.doc.querySelector("input"), { key: "Enter" }); - // Long enough that this can no longer be the submission that press caused; - // it is the user clicking the button themselves. - vi.advanceTimersByTime(200); - r.click(r.doc.querySelector("button")); - - expect(r.actions.map((a: any) => a.kind)).toEqual(["press", "click"]); - }); - - it("takes its hover highlight out of the document when recording stops", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - r.mousemove(r.doc.querySelector("button")); - expect(r.overlays()).toHaveLength(1); - - r.deactivate(); - - // Observe-only cuts both ways: once recording is over the app's DOM has to - // look exactly as it would have without the recorder in it. - expect(r.overlays()).toHaveLength(0); - }); - - it("prefers a data-testid locator over other strategies", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - r.click(r.doc.querySelector("button")); - r.settleClick(); - - expect(r.actions).toEqual([ - { kind: "click", locator: { kind: "testid", value: "submit-btn" } }, - ]); - }); - - it("uses data-dyad-id only as a source hint for a CSS fallback", () => { - const r = setup(); - // The attribute is a source location injected only by Dyad's dev plugin, so - // a locator built from it points at a moving target the replayed build - // doesn't even carry. - r.setHtml(`
`); - r.activate(); - r.click(r.doc.querySelector("span")); - r.settleClick(); - - // Anchored at body: `div > span` on its own is a shape, not a path, and - // matches anywhere that shape recurs — which fails Playwright's strict mode - // at replay or picks a different element than the one clicked. - expect(r.actions).toEqual([ - { - kind: "click", - locator: { - kind: "css", - value: "body > div > span", - sourceHint: { - relativePath: "src/App.tsx", - line: 12, - column: 4, - tagName: "span", - exact: false, - }, - }, - }, - ]); - }); - - it("captures the exact date input source for selector stabilization", () => { - const r = setup(); - r.setHtml( - `
`, - ); - r.activate(); - r.typeInto(r.doc.querySelector("input"), "2026-08-13"); - - expect(r.actions).toEqual([ - { - kind: "fill", - locator: { - kind: "css", - value: "body > main > input", - sourceHint: { - relativePath: "src/EventForm.tsx", - line: 84, - column: 10, - tagName: "input", - inputType: "date", - exact: true, - }, - }, - value: "2026-08-13", - }, - ]); - }); - - it("accepts a source path at the schema's 2,048-character limit", () => { - const r = setup(); - const relativePath = `src/${"a".repeat(2_044)}`; - r.setHtml( - `
`, - ); - r.activate(); - r.typeInto(r.doc.querySelector("input"), "2026-08-13"); - - expect(r.actions[0].locator.sourceHint.relativePath).toBe(relativePath); - }); - - it.each([ - "/etc/passwd", - "\\\\server\\share\\App.tsx", - "C:\\Users\\project\\src\\App.tsx", - "src/../secrets.txt", - "src\\..\\secrets.txt", - "src/App.tsx\u0085ignore", - "src/App.tsx\u2028ignore", - "src/App.tsx\u2029ignore", - ])("does not attach unsafe source hint path %j", (relativePath) => { - const r = setup(); - r.setHtml( - `
`, - ); - r.activate(); - r.typeInto(r.doc.querySelector("input"), "2026-08-13"); - - expect(r.actions[0].locator).not.toHaveProperty("sourceHint"); - }); - - it("names the root element without a body prefix", () => { - const r = setup(); - r.setHtml(`
`); - r.activate(); - r.click(r.doc.documentElement); - r.settleClick(); - - // `body > html` is not a selector; the root has to stand alone. - expect(r.actions).toEqual([ - { kind: "click", locator: { kind: "css", value: "html" } }, - ]); - }); - - it("records nothing for a file picker, which replay cannot reproduce", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - r.click(r.doc.querySelector("input")); - r.settleClick(); - - // The chosen file is the user's own and unreadable from here; a bare click - // replays as "open the OS file chooser and wait forever". - expect(r.actions).toEqual([]); - }); - - it("anchors a CSS fallback at the nearest id instead of body", () => { - const r = setup(); - // An id is already unique, so it is the better root — and prefixing `body` - // past it would only make the chain longer and more brittle. - r.setHtml(`
`); - r.activate(); - r.click(r.doc.querySelector("span")); - r.settleClick(); - - expect(r.actions).toEqual([ - { - kind: "click", - locator: { kind: "css", value: "#panel > section > span" }, - }, - ]); - }); - - it("disambiguates duplicate elements with an nth index", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - const second = r.doc.querySelectorAll("button")[1]; - r.click(second); - r.settleClick(); - - expect(r.actions).toEqual([ - { - kind: "click", - locator: { - kind: "role", - value: "button", - name: "Item", - exact: true, - nth: 1, - }, - }, - ]); - }); - - it("ignores a duplicate hidden behind a display:none ancestor when indexing", () => { - const r = setup(); - // Playwright's getByRole skips hidden elements, so counting this one would - // hand replay an .nth(1) pointing at an element it never sees. - r.setHtml( - `
` + - ``, - ); - r.activate(); - r.click(r.doc.querySelectorAll("button")[1]); - - expect(r.actions).toEqual([ - { - kind: "click", - locator: { kind: "role", value: "button", name: "Item", exact: true }, - }, - ]); - }); - - it("stops recording after deactivate", () => { - const r = setup(); - r.setHtml(``); - r.activate(); - r.deactivate(); - r.click(r.doc.querySelector("button")); - r.settleClick(); - - expect(r.actions).toEqual([]); - }); - - it("ignores untrusted events when the test escape hatch is off", () => { - const r = setup({ allowUntrusted: false }); - r.setHtml(``); - r.activate(); - r.click(r.doc.querySelector("button")); - r.settleClick(); - - expect(r.actions).toEqual([]); - }); - - it("cannot be switched into accepting untrusted events after load", () => { - // The proxy injects this script at the top of , so every page script - // runs after it. Setting the flag late — an app bundle, a CDN tag — must not - // let fabricated clicks into a spec the user commits and runs. - const r = setup({ allowUntrusted: false }); - r.win.__DYAD_RECORDER_ALLOW_UNTRUSTED__ = true; - r.setHtml(``); - r.activate(); - r.click(r.doc.querySelector("button")); - r.settleClick(); - - expect(r.actions).toEqual([]); - }); - - it("removes the escape-hatch global once it has been read", () => { - const r = setup(); - expect(r.win.__DYAD_RECORDER_ALLOW_UNTRUSTED__).toBeUndefined(); - }); -}); diff --git a/studio/vendor/dyad/src/__tests__/evals/README.md b/studio/vendor/dyad/src/__tests__/evals/README.md deleted file mode 100644 index 2e7cceec..00000000 --- a/studio/vendor/dyad/src/__tests__/evals/README.md +++ /dev/null @@ -1,378 +0,0 @@ -# Evals - -LLM eval suite for tool-use quality. Five suites run the same 16 cases across -the model matrix (Claude Sonnet 4.6, GPT 5.4, Gemini 3 Flash, GPT 5.6 Sol, -GPT 5.6 Luna) but with different tool sets and system prompts: - -| Suite name | Tools available | System prompt | -| ------------------------ | ------------------------------ | -------------------------------------------- | -| `search_replace` | `search_replace` only | Minimal custom "precise code editor" prompt | -| `search_replace_few` | `search_replace` only | Variant prompt encouraging fewer tool calls | -| `basic_agent` | `search_replace`, `write_file` | Production `LOCAL_AGENT_BASIC_SYSTEM_PROMPT` | -| `pro_agent` | `search_replace`, `write_file` | Production `LOCAL_AGENT_SYSTEM_PROMPT` (Pro) | -| `pro_agent_experimental` | `search_replace`, `write_file` | Editable copy of the Pro prompt for tweaking | - -The `newline_probe` suite is separate: it runs its own four cases (not the -shared 16), skips the LLM judge, and measures `search_replace` serialization -mechanics rather than edit quality. See [Newline probe](#newline-probe). - -Each case gives the model a real source file plus an editing instruction, -runs the model with the suite's tools wired up, applies the produced edits, -and then asks an LLM judge (GPT 5.4) whether the result satisfies the -instruction. - -## Prerequisites - -All models are routed through the Dyad Engine gateway, so you only need one -credential: a Dyad Pro API key, exposed as `DYAD_PRO_API_KEY`. - -The suite is skipped entirely when `DYAD_PRO_API_KEY` is unset — no tests will -fail, they just won't run. This keeps regular `vitest run` safe for contributors -without a key. - -Export the key for the session (plus the two required filter vars — see -[Running the suite](#running-the-suite)): - -```bash -export DYAD_PRO_API_KEY="..." -EVAL_SUITE=all EVAL_MODEL=all npm run eval -``` - -Or set everything inline for a single command: - -```bash -DYAD_PRO_API_KEY="..." EVAL_SUITE=all EVAL_MODEL=all npm run eval -``` - -Optional: override the gateway URL with `DYAD_ENGINE_URL` (defaults to -`https://engine.dyad.sh/v1`). - -## Running the suite - -**Both `EVAL_SUITE` and `EVAL_MODEL` are required.** A full run of every -suite against every model is expensive, so the suite will not run unless -the caller opts in explicitly. If either variable is unset, the eval prints -a warning describing how to configure it and registers a single skipped -placeholder — it does not fail CI, but it also does not run any cases. - -Use the special value `all` to mean "run everything": - -```bash -# Run every suite against every model against every case. -EVAL_SUITE=all EVAL_MODEL=all DYAD_PRO_API_KEY="..." npm run eval -``` - -**Heads up — this is expensive.** A full `all`/`all` run issues one -generation per (suite × model × case) triple plus one judge call per case, -across 5 suites, 5 models, and 16 cases. Expect dozens of LLM requests, -some of which run reasoning models on 300+ line fixtures. Use sparingly; -prefer narrow filters during development. - -### Running a single suite - -Set `EVAL_SUITE` to the exact `name` (case-insensitive) of the suite — the -same name that appears as a folder under `eval-results/`. A comma-separated -list runs multiple suites: - -```bash -# Just the original search_replace-only suite -EVAL_SUITE=search_replace EVAL_MODEL=all DYAD_PRO_API_KEY="..." npm run eval - -# The basic_agent suite (Basic agent prompt, search_replace + write_file) -EVAL_SUITE=basic_agent EVAL_MODEL=all DYAD_PRO_API_KEY="..." npm run eval - -# The pro_agent suite (Pro agent prompt, search_replace + write_file) -EVAL_SUITE=pro_agent EVAL_MODEL=all DYAD_PRO_API_KEY="..." npm run eval -``` - -Note: `EVAL_SUITE` matches suite `name`s exactly (case-insensitive), and -accepts a comma-separated list for multiple suites (e.g. -`EVAL_SUITE=search_replace,basic_agent`). Unknown names error out with the -available list. - -### Running a single case - -Vitest's `-t` flag filters by test name. Case names are the `name` field in -the `CASES` array of [tool_use.eval.ts](tool_use.eval.ts). - -```bash -EVAL_SUITE=all EVAL_MODEL=all DYAD_PRO_API_KEY="..." \ - npm run eval -- -t "Extract a helper function" -``` - -`-t` matches as a substring, so a short unique fragment works too: - -```bash -EVAL_SUITE=all EVAL_MODEL=all DYAD_PRO_API_KEY="..." npm run eval -- -t "zod" -``` - -### Running against one model - -Set `EVAL_MODEL` to a case-insensitive substring of the model's label or -model name. It matches against both, so short fragments like `sonnet`, `gpt`, -or `gemini` work: - -```bash -EVAL_SUITE=all EVAL_MODEL=sonnet DYAD_PRO_API_KEY="..." npm run eval -``` - -### Combining filters - -`EVAL_SUITE`, `EVAL_MODEL`, and `-t` compose. A tight development loop: - -```bash -EVAL_SUITE=search_replace EVAL_MODEL=sonnet \ - DYAD_PRO_API_KEY="..." npm run eval -- -t "Extract a helper function" -``` - -Note: vitest's `-t` pattern is applied across the full describe/test -hierarchy as a regex, which makes "model label > case name" style patterns -brittle across vitest versions. Prefer `EVAL_SUITE` / `EVAL_MODEL` for -suite and model filtering and reserve `-t` for case-name filtering. - -## Where results are stored - -Every run writes structured output to `eval-results/` at the repo root. The -directory is gitignored and never cleaned automatically — delete old runs by -hand when you want to. - -Layout: - -``` -eval-results/ - / ← one top-level folder per suite - __/ ← one folder per (run, model) - / ← one folder per case - record.json ← full structured record - record.txt ← human-readable render of the same - details/ ← per-record split views - file_before. ← file at the start of the run - file_after. ← file at the end of the run - diff.patch ← cumulative unified diff - system_prompt.txt ← system prompt sent to the model - instructions.txt ← case instructions (no file content) - user_prompt.txt ← full user message (file + instructions) - metadata.json ← run metadata without big blobs - metadata.txt ← same info, human-readable - tool_calls/ - 01.txt ← combined view of tool call #1 - 01/ ← split view, one piece per file - file_before. - file_after. - diff.patch - meta.txt - . ← one file per tool arg (see below) - 02.txt - 02/ - ... -``` - -The top-level folder is the suite `name`, so each suite lands in its own -directory: - -- `eval-results/search_replace/` -- `eval-results/search_replace_few/` -- `eval-results/basic_agent/` -- `eval-results/pro_agent/` -- `eval-results/pro_agent_experimental/` - -`` is captured once at process start, so every case from the -same `npm run eval` invocation for a given (suite, model) pair clusters into -one folder. Folder names sort chronologically under `ls`. - -### Record format - -`record.json` contains the complete machine-readable record. Key fields: - -- `timestamp`, `suite`, `caseName` — identifying metadata. -- `model` — `{label, provider, modelName, responseModelId}`. `responseModelId` - is the exact model string the gateway echoed back, which can differ from - `modelName` (e.g. dated snapshots). -- `prompt` — `{system, instructions, user}`. `system` is the full system - prompt sent to the model (including the production agent prompts when the - suite uses one). `instructions` is the bare case instruction — useful for - scanning what was asked without the fixture file inlined. `user` is the - full user message actually sent (file content + instructions). -- `file` — `{name, before, after}`. The fixture file name plus its content - at the start and end of the run. `before` / `after` are also written to - `details/file_before.` / `details/file_after.` for easy editor - opening with matching syntax highlighting. -- `llm.totalDurationMs`, `llm.totalUsage` — wall-clock time and token totals - for the model under test (not the judge). -- `llm.requests` — per-step breakdown: each entry is one HTTP round-trip with - its own duration, usage, and `finishReason`. -- `toolCalls` — every tool call the model made. Each entry records - `toolName`, `filePath`, an `args` map (keyed by the tool's parameter names, - so `old_string`/`new_string` for `search_replace`, `content` for - `write_file`), the file before and after the call, and a unified diff of - just that call. -- `diff` — unified diff from the original fixture to the final file - (i.e. the cumulative effect of all tool calls). -- `judge` — the judge's verdict: `label`, `modelName`, `durationMs`, - `usage`, `pass` (boolean), and `explanation` (the judge's written - reasoning, with the trailing `PASS`/`FAIL` verdict line stripped). -- `passed` — the overall test outcome. Requires the judge to say `PASS` _and_ - all structural checks to pass _and_ no exceptions to be thrown. -- `errorMessage` — set when the test threw (tool-call failure, structural - check failure, judge FAIL, etc.); `null` otherwise. - -`record.txt` is a readable render of the same information — headers, the -system prompt and instructions, inline tool-call bodies, usage totals, the -final diff, and the judge's explanation. Open it when you want a quick -human-readable summary instead of parsing JSON. - -### The `details/` folder - -`details/` is a split view of the record, intended for quick inspection and -diffing without having to parse JSON or scroll through `record.txt`: - -- `file_before.` / `file_after.` — raw file content before and - after the run, with the fixture's extension preserved so editors apply - the right syntax highlighting. -- `diff.patch` — the same unified diff as `record.diff`. -- `system_prompt.txt`, `instructions.txt`, `user_prompt.txt` — the three - views of the prompt input. -- `metadata.json` / `metadata.txt` — everything from `record.json` minus the - large content blobs that already have their own files (no inline file - contents and no per-tool-call entries). Useful for skimming token counts, - judge verdict, and model identity across many runs. - -### The `tool_calls/` folder - -One `NN.txt` (combined view) and one `NN/` folder (split view) per tool -call. The split view contains the raw pieces as standalone files: - -- `file_before.`, `file_after.`, `diff.patch` — file state around - the single call. -- `meta.txt` — timestamp, tool name, target path, and per-arg length summary. -- One file per tool argument, named after the arg's key. String args use the - target file's extension (for syntax highlighting); non-string args become - JSON blobs. So a `search_replace` call produces `old_string.ts` and - `new_string.ts`; a `write_file` call produces `content.ts` and - `description.ts`. - -## Newline probe - -`search_replace` builds its operations string by joining the model's raw args -with newline delimiters: - -``` -<<<<<<< SEARCH\n${old_string}\n=======\n${new_string}\n>>>>>>> REPLACE -``` - -A newline that merely _terminates_ an arg therefore becomes a trailing empty -line in the parsed block. On the search side that empty line matches nothing, -the processor's `trimEmptyLines` fallback rescues the match, and — before the -fix — nothing trimmed the replace side, so the phantom line was written into -the file as a stray blank line. - -This suite measures how often real models send the triggering arg shape. -Every `search_replace` call is applied twice: once with the current -serialization and once with a counterfactual that trims the terminator. -Divergence marks a call the defect fires on. - -```bash -DYAD_PRO_API_KEY="..." EVAL_SUITE=newline_probe EVAL_MODEL="GPT 5.6 Sol" npm run eval -``` - -`EVAL_SKIP_JUDGE=1` skips the judge round-trip on any suite, which halves the -spend when you only care about serialization mechanics. - -### What the first run found - -Across 82 applied `search_replace` calls from GPT 5.6 Sol (the shared 16-case -`search_replace` suite): - -| | count | -| ----------------------------------------- | ------------ | -| applied calls | 82 | -| both args newline-terminated (symmetric) | 18 | -| `new_string`-only terminated (asymmetric) | 0 | -| `trimEmptyLines` fallback fired | 7 | -| **corrupted** | **7 (8.5%)** | - -All 7 were the symmetric shape. The model terminates both args because it -copies a contiguous region of the file — in 18 of 18 symmetric calls the -replace block ended on the same line the search block ended on, i.e. copied -context rather than an authored blank line. Corruption followed in exactly the -7 cases where the file had no real blank line at that boundary. - -Reading a report: - -- **Non-zero divergence** — the defect reproduced. The summary prints a - `current` vs `fixed` unified diff per affected call, and the offending args - sit in that run's `tool_calls/NN/` folder as ready-made fixtures. -- **Zero divergence** — the defect did not fire for that model on those cases. - -### Known gap - -The processor fix covers the symmetric shape only, because it lives inside the -`trimEmptyLines` fallback and an unterminated `old_string` matches as-is, so -the fallback never fires. The asymmetric shape (`new_string` terminated, -`old_string` not) still writes a stray blank line. It was not observed once in -82 calls, so it is unfixed by choice rather than oversight — the probe stays -live for it, and `helpers/newline_probe.spec.ts` pins the behavior. - -Output goes to `eval-results/newline_probe/` (`samples.json` plus -`summary.txt`), accumulated across runs, in addition to the per-case records. - -The probe's own detector is unit-tested in `helpers/newline_probe.spec.ts`, -which runs in the normal `vitest` suite with no API key. That test matters: the -first version of this probe compared against an asymmetric-only counterfactual, -which by construction leaves symmetric calls untouched — so it reported "0 -corrupted" while 7 real corruptions sat in the data. The spec now pins that -blind spot explicitly. - -## Recorded calls - -`recorded_calls//` holds real `search_replace` tool calls captured from -eval runs, stored as the operations strings the tool builds from the model's -arguments. `recorded_calls.spec.ts` replays them against the current processor. - -Each case starts from a fixture already in `fixtures/`, so replaying the calls -in order reconstructs the edit session. That keeps the evidence behind the -newline findings reviewable without an API key and without `eval-results/`, -which is gitignored and gets wiped. - -The assertion is that an applied call produces exactly what replacing the first -verbatim occurrence of `old_string` with `new_string` produces — the tool's -whole contract, and the thing a trailing newline in the arguments breaks. - -To add cases, copy `old_string` / `new_string` out of a run's `tool_calls/NN/` -folder into `//NN.txt` in the marker format, and list the case -under that model in `manifest.json` with the fixture it starts from. - -### Replaying against the pre-fix processor - -The current processor no longer writes stray blank lines, so replaying these -calls against it shows none. `helpers/legacy_search_replace.ts` is a frozen -copy of the processor as it stood at `67c9ee7c`, the commit before -[#4338](https://github.com/dyad-sh/dyad/pull/4338), kept so the recordings can -still be replayed against the behavior they were captured from. - -The spec replays both by default and asserts each model's totals, so the -measurement is pinned in CI rather than described in prose: - -| model | processor | applied | did not match | stray blank lines | -| ------------ | ------------ | ------- | ------------- | ----------------- | -| GPT 5.6 Sol | before #4338 | 9 | 7 | 7 | -| GPT 5.6 Sol | current | 11 | 5 | 0 | -| GPT 5.6 Luna | before #4338 | 5 | 0 | 2 | -| GPT 5.6 Luna | current | 5 | 0 | 0 | - -Sol's applied count goes up because two calls that could not match were being -blocked by a stray blank line an earlier call had introduced. - -Both models produce the defect, at different rates. Over the full runs these -recordings were drawn from, Sol corrupted 7 of 82 applied calls and Luna 2 of -116, so the recorded set is the corrupting subset rather than a sample. - -To replay only one implementation: - -```bash -SEARCH_REPLACE_IMPL=legacy npx vitest run src/__tests__/evals/recorded_calls.spec.ts -SEARCH_REPLACE_IMPL=current npx vitest run src/__tests__/evals/recorded_calls.spec.ts -``` - -`legacy_search_replace.ts` is a historical snapshot. It should not be updated -to track the real processor - its only job is to keep producing the old output. diff --git a/studio/vendor/dyad/src/__tests__/evals/chat_history.eval.ts b/studio/vendor/dyad/src/__tests__/evals/chat_history.eval.ts deleted file mode 100644 index 1c80b427..00000000 --- a/studio/vendor/dyad/src/__tests__/evals/chat_history.eval.ts +++ /dev/null @@ -1,432 +0,0 @@ -/** - * Chat-history recall benchmark. - * - * Decides whether the shipped search_chats/read_chat primary-agent flow is - * good enough, or whether the explore_chat_history sub-agent plan - * (plans/explore_chat_history.md) buys real answer quality. - * - * Run: - * DYAD_PRO_API_KEY=... npm run eval -- chat_history - * CH_SMOKE=1 ... npm run eval -- chat_history (2 queries, quick wiring check) - * CH_ONLY=vague_decision-1 ... (filter by query id substring) - * - * Wrong answers never fail tests — every run is recorded to - * benchmark-results/chat-history//results.jsonl and summarized in - * summary.md; the analysis happens on the recorded data. - */ -import { describe, it, beforeAll, afterAll, expect } from "vitest"; -import { - appendFileSync, - existsSync, - mkdirSync, - readFileSync, - writeFileSync, -} from "node:fs"; -import { resolve } from "node:path"; - -if (!process.env.DYAD_PRO_API_KEY && process.env.DYAD_PRO_KEY) { - process.env.DYAD_PRO_API_KEY = process.env.DYAD_PRO_KEY; -} - -import { SONNET_4_6 } from "@/ipc/shared/language_model_constants"; -import { - GPT_5_4, - getEvalModel, - hasDyadProKey, - type EvalProvider, -} from "./helpers/get_eval_model"; -import { - loadScenarios, - validateScenario, - seedWorld, - makeEvalContext, - runCurrentArm, - runSubagentArm, - runControlArm, - scoreMechanically, - judgeAnswer, - type ScenarioFile, - type ScenarioQuery, - type SeededWorld, - type ArmResult, -} from "./helpers/chat_history_harness"; - -// The model the explore_chat_history plan would use for its sub-agent -// (durable Explorer persona model) — primary comparison model. -const GPT_5_6_LUNA = "gpt-5.6-luna"; - -type Arm = "current" | "subagent" | "control"; - -interface ModelSpec { - label: string; - provider: EvalProvider; - name: string; -} - -const GPT: ModelSpec = { - label: "gpt-5.6-luna", - provider: "openai", - name: GPT_5_6_LUNA, -}; -const SONNET: ModelSpec = { - label: "sonnet-4-6", - provider: "anthropic", - name: SONNET_4_6, -}; - -interface Job { - scenario: ScenarioFile; - query: ScenarioQuery; - arm: Arm; - model: ModelSpec; - rep: number; -} - -let scenarios: ScenarioFile[] = []; -try { - scenarios = loadScenarios(); -} catch { - scenarios = []; -} - -const smoke = process.env.CH_SMOKE === "1"; -const only = process.env.CH_ONLY; - -// CH_RESUME: comma-separated run-dir names whose successful records should -// not be re-run (rate-limit recovery without re-spending tokens). -function completedJobKeys(): Set { - const done = new Set(); - const dirs = (process.env.CH_RESUME ?? "").split(",").filter(Boolean); - for (const dir of dirs) { - const file = resolve( - __dirname, - "../../../benchmark-results/chat-history", - dir, - "results.jsonl", - ); - if (!existsSync(file)) continue; - for (const line of readFileSync(file, "utf-8").split("\n")) { - if (!line.trim()) continue; - try { - const rec = JSON.parse(line); - if (!rec.error) { - done.add(`${rec.query_id}|${rec.arm}|${rec.model}|${rec.rep}`); - } - } catch { - // skip malformed line - } - } - } - return done; -} - -// Gateway rate limits are cumulative; gate actual model work independently of -// vitest's test concurrency. -function createGate(limit: number) { - let active = 0; - const waiters: (() => void)[] = []; - return async function gated(fn: () => Promise): Promise { - while (active >= limit) { - await new Promise((r) => waiters.push(r)); - } - active++; - try { - return await fn(); - } finally { - active--; - waiters.shift()?.(); - } - }; -} -const gate = createGate(Number(process.env.CH_CONCURRENCY ?? "4")); - -function buildJobs(): Job[] { - const jobs: Job[] = []; - const push = (arm: Arm, model: ModelSpec, reps: number) => { - for (const scenario of scenarios) { - for (const query of scenario.queries) { - if (only && !query.id.includes(only)) continue; - for (let rep = 1; rep <= reps; rep++) { - jobs.push({ scenario, query, arm, model, rep }); - } - } - } - }; - if (smoke) { - // Wiring check: first query of two contrasting categories, all arms. - const pick = scenarios - .filter((s) => ["vague_decision", "no_match"].includes(s.category)) - .map((s) => ({ ...s, queries: s.queries.slice(0, 1) })); - const saved = scenarios; - scenarios = - pick.length > 0 - ? pick - : scenarios - .map((s) => ({ ...s, queries: s.queries.slice(0, 1) })) - .slice(0, 2); - push("current", GPT, 1); - push("subagent", GPT, 1); - push("control", GPT, 1); - scenarios = saved; - return jobs; - } - push("current", GPT, 2); - push("subagent", GPT, 2); - push("control", GPT, 1); - push("current", SONNET, 1); - push("subagent", SONNET, 1); - return jobs; -} - -const RUN_ID = `run-${new Date().toISOString().replace(/[:.]/g, "-")}${smoke ? "-smoke" : ""}`; -const RESULTS_DIR = resolve( - __dirname, - "../../../benchmark-results/chat-history", - RUN_ID, -); - -interface RunRecord { - category: string; - query_id: string; - expected: string; - arm: Arm; - model: string; - rep: number; - verdict?: "correct" | "partial" | "incorrect"; - judge_reasoning?: string; - atoms_all_hit?: boolean; - atom_groups_hit?: number; - atom_groups_total?: number; - leaked_atoms?: string[]; - injection_complied?: boolean; - gold_observed_all?: boolean; - gold_observed_any?: boolean; - earlier_atoms_mentioned?: boolean; - input_tokens?: number; - output_tokens?: number; - steps?: number; - search_calls?: number; - read_calls?: number; - primary_context_bytes?: number; - report_bytes?: number; - fabricated_citations?: number; - valid_citations?: number; - fallback_used?: boolean; - wall_ms?: number; - answer?: string; - report?: unknown; - tool_log?: unknown; - error?: string; -} - -const records: RunRecord[] = []; - -function recordRun(rec: RunRecord) { - records.push(rec); - appendFileSync( - resolve(RESULTS_DIR, "results.jsonl"), - JSON.stringify(rec) + "\n", - ); -} - -// ── Fixture validation (always runs, no API key needed) ──────── - -describe("chat-history fixtures validate", () => { - if (scenarios.length === 0) { - it.skip("no fixture files present yet", () => {}); - } - for (const scenario of scenarios) { - it(`${scenario.category} is internally consistent`, () => { - const errors = validateScenario(scenario); - expect(errors, errors.join("\n")).toEqual([]); - }); - } -}); - -// ── Benchmark ────────────────────────────────────────────────── - -const canRun = hasDyadProKey() && scenarios.length > 0; - -(canRun ? describe : describe.skip)("chat-history recall benchmark", () => { - let world: SeededWorld; - const judgeModel = () => getEvalModel("openai", GPT_5_4); - - beforeAll(async () => { - mkdirSync(RESULTS_DIR, { recursive: true }); - world = await seedWorld(scenarios); - }, 120_000); - - afterAll(async () => { - world?.dispose(); - const summary = summarize(records); - writeFileSync(resolve(RESULTS_DIR, "summary.md"), summary); - writeFileSync( - resolve(RESULTS_DIR, "records-count.json"), - JSON.stringify({ total: records.length }), - ); - console.log(`\n${summary}\nResults: ${RESULTS_DIR}`); - }); - - const alreadyDone = completedJobKeys(); - const jobs = buildJobs().filter( - (j) => !alreadyDone.has(`${j.query.id}|${j.arm}|${j.model.label}|${j.rep}`), - ); - - for (const job of jobs) { - const name = `${job.query.id} · ${job.arm} · ${job.model.label} · rep${job.rep}`; - it.concurrent(name, async () => { - const base: RunRecord = { - category: job.scenario.category, - query_id: job.query.id, - expected: job.query.expected, - arm: job.arm, - model: job.model.label, - rep: job.rep, - }; - try { - await gate(async () => { - const seeded = world.categories.get(job.scenario.category)!; - const model = getEvalModel(job.model.provider, job.model.name); - let arm: ArmResult; - if (job.arm === "current") { - arm = await runCurrentArm({ - model, - ctx: makeEvalContext(seeded), - appName: job.scenario.app.name, - question: job.query.question, - }); - } else if (job.arm === "subagent") { - arm = await runSubagentArm({ - model, - ctx: makeEvalContext(seeded), - appName: job.scenario.app.name, - question: job.query.question, - }); - } else { - arm = await runControlArm({ - model, - appName: job.scenario.app.name, - question: job.query.question, - }); - } - const mech = scoreMechanically({ - scenario: job.scenario, - query: job.query, - seeded, - answer: arm.answer, - toolRun: arm.toolRun, - }); - const judge = await judgeAnswer({ - judgeModel: judgeModel(), - query: job.query, - answer: arm.answer, - }); - recordRun({ - ...base, - verdict: judge.verdict, - judge_reasoning: judge.reasoning, - atoms_all_hit: mech.atomsAllHit, - atom_groups_hit: mech.atomGroupsHit, - atom_groups_total: mech.atomGroupsTotal, - leaked_atoms: mech.leakedAtoms, - injection_complied: mech.injectionComplied, - gold_observed_all: mech.goldObservedAll, - gold_observed_any: mech.goldObservedAny, - earlier_atoms_mentioned: mech.earlierAtomsMentioned, - input_tokens: arm.usage.inputTokens, - output_tokens: arm.usage.outputTokens, - steps: arm.steps, - search_calls: - arm.toolRun?.log.filter((l) => l.tool === "search_chats") - .length ?? 0, - read_calls: - arm.toolRun?.log.filter((l) => l.tool === "read_chat").length ?? - 0, - primary_context_bytes: arm.primaryContextBytes, - report_bytes: arm.reportBytes, - fabricated_citations: arm.fabricatedCitations, - valid_citations: arm.validCitations, - fallback_used: arm.fallbackUsed, - wall_ms: arm.wallMs, - answer: arm.answer, - report: arm.report, - tool_log: arm.toolRun?.log, - }); - }); - } catch (error) { - recordRun({ - ...base, - error: - error instanceof Error - ? `${error.message}\n${error.stack}` - : String(error), - }); - } - expect(true).toBe(true); - }, 340_000); - } -}); - -// ── Summary ──────────────────────────────────────────────────── - -function pct(n: number, d: number): string { - return d === 0 ? "–" : `${Math.round((n / d) * 100)}%`; -} - -function mean(xs: number[]): number { - return xs.length === 0 - ? 0 - : Math.round(xs.reduce((a, b) => a + b, 0) / xs.length); -} - -function summarize(recs: RunRecord[]): string { - const ok = recs.filter((r) => !r.error); - const errored = recs.filter((r) => r.error); - const lines: string[] = [ - `# Chat-history benchmark — ${RUN_ID}`, - "", - `Runs: ${recs.length} (${errored.length} errored)`, - "", - ]; - - const armModels = [...new Set(ok.map((r) => `${r.arm}|${r.model}`))].sort(); - lines.push( - "| arm · model | n | correct | partial | incorrect | leak | inject | fab.cites | gold-obs(any) | mean in-tok | mean out-tok | mean ctx-bytes | mean wall-ms |", - "|---|---|---|---|---|---|---|---|---|---|---|---|---|", - ); - for (const am of armModels) { - const [arm, model] = am.split("|"); - const rs = ok.filter((r) => r.arm === arm && r.model === model); - const found = rs.filter((r) => r.expected === "found"); - lines.push( - `| ${arm} · ${model} | ${rs.length} | ${pct(rs.filter((r) => r.verdict === "correct").length, rs.length)} | ${pct(rs.filter((r) => r.verdict === "partial").length, rs.length)} | ${pct(rs.filter((r) => r.verdict === "incorrect").length, rs.length)} | ${rs.filter((r) => (r.leaked_atoms?.length ?? 0) > 0).length} | ${rs.filter((r) => r.injection_complied).length} | ${rs.reduce((a, r) => a + (r.fabricated_citations ?? 0), 0)} | ${pct(found.filter((r) => r.gold_observed_any).length, found.length)} | ${mean(rs.map((r) => r.input_tokens ?? 0))} | ${mean(rs.map((r) => r.output_tokens ?? 0))} | ${mean(rs.map((r) => r.primary_context_bytes ?? 0))} | ${mean(rs.map((r) => r.wall_ms ?? 0))} |`, - ); - } - - lines.push("", "## By category (correct rate)", ""); - const cats = [...new Set(ok.map((r) => r.category))].sort(); - lines.push( - `| category | ${armModels.map((am) => am.replace("|", " · ")).join(" | ")} |`, - `|---|${armModels.map(() => "---").join("|")}|`, - ); - for (const cat of cats) { - const row = armModels.map((am) => { - const [arm, model] = am.split("|"); - const rs = ok.filter( - (r) => r.arm === arm && r.model === model && r.category === cat, - ); - return pct(rs.filter((r) => r.verdict === "correct").length, rs.length); - }); - lines.push(`| ${cat} | ${row.join(" | ")} |`); - } - - if (errored.length > 0) { - lines.push("", "## Errors", ""); - for (const r of errored.slice(0, 10)) { - lines.push( - `- ${r.query_id} · ${r.arm} · ${r.model} · rep${r.rep}: ${r.error?.split("\n")[0]}`, - ); - } - } - return lines.join("\n"); -} diff --git a/studio/vendor/dyad/src/__tests__/evals/compaction.eval.ts b/studio/vendor/dyad/src/__tests__/evals/compaction.eval.ts deleted file mode 100644 index eb09de30..00000000 --- a/studio/vendor/dyad/src/__tests__/evals/compaction.eval.ts +++ /dev/null @@ -1,319 +0,0 @@ -/** - * Compaction quality benchmark (plans/benchmark-compaction.md). - * - * Compares candidate compaction models on ~200k-token synthetic AI-coding - * transcripts using the production compaction prompt + transcript format. - * - * Run: - * DYAD_PRO_API_KEY=... EVAL_SUITE/EVAL_MODEL not used — this suite is - * gated by its own env vars: - * CMP_RUN=1 npm run eval -- compaction (full grid) - * CMP_RUN=1 CMP_SMOKE=1 npm run eval -- compaction (1 fixture x models x 1 rep) - * CMP_ONLY= CMP_MODELS=gpt-5.6-sol,gpt-5.6-luna - * CMP_RESUME= CMP_CONCURRENCY=2 - * - * Wrong answers never fail tests — every run is appended to - * benchmark-results/compaction//results.jsonl and summarized in - * summary.md. - */ -import { describe, it, beforeAll, afterAll, expect } from "vitest"; -import { - appendFileSync, - existsSync, - mkdirSync, - readFileSync, - writeFileSync, -} from "node:fs"; -import { resolve } from "node:path"; - -if (!process.env.DYAD_PRO_API_KEY && process.env.DYAD_PRO_KEY) { - process.env.DYAD_PRO_API_KEY = process.env.DYAD_PRO_KEY; -} - -import { GPT_5_4, getEvalModel, hasDyadProKey } from "./helpers/get_eval_model"; -import { - loadFixtures, - loadSpecs, - validateSpec, - validateFixture, - fixtureTranscript, - runCompaction, - structuralChecks, - judgeFactGrid, - runProbes, - computeScores, - type CompactionFixture, - type FactGridResult, - type ProbeResult, - type Scores, - type StructuralResult, -} from "./helpers/compaction_harness"; - -const MODELS = (process.env.CMP_MODELS ?? "gpt-5.6-sol,gpt-5.6-luna") - .split(",") - .map((s) => s.trim()) - .filter(Boolean); - -const smoke = process.env.CMP_SMOKE === "1"; -const only = process.env.CMP_ONLY; -const optedIn = process.env.CMP_RUN === "1" || smoke; -const REPS = smoke ? 1 : 2; - -let fixtures: CompactionFixture[] = []; -try { - fixtures = loadFixtures(); -} catch { - fixtures = []; -} -if (only) fixtures = fixtures.filter((f) => f.name.includes(only)); -if (smoke) fixtures = fixtures.slice(0, 1); - -// Big requests: keep engine concurrency low. -function createGate(limit: number) { - let active = 0; - const waiters: (() => void)[] = []; - return async function gated(fn: () => Promise): Promise { - while (active >= limit) { - await new Promise((r) => waiters.push(r)); - } - active++; - try { - return await fn(); - } finally { - active--; - waiters.shift()?.(); - } - }; -} -const gate = createGate(Number(process.env.CMP_CONCURRENCY ?? "2")); - -const RUN_ID = `run-${new Date().toISOString().replace(/[:.]/g, "-")}${smoke ? "-smoke" : ""}`; -const RESULTS_ROOT = resolve( - __dirname, - "../../../benchmark-results/compaction", -); -const RESULTS_DIR = resolve(RESULTS_ROOT, RUN_ID); - -interface RunRecord { - fixture: string; - model: string; - rep: number; - scores?: Scores; - structural?: StructuralResult; - factGrid?: FactGridResult; - probes?: ProbeResult[]; - input_tokens?: number; - output_tokens?: number; - wall_ms?: number; - summary?: string; - error?: string; -} - -const records: RunRecord[] = []; -function recordRun(rec: RunRecord) { - records.push(rec); - appendFileSync( - resolve(RESULTS_DIR, "results.jsonl"), - JSON.stringify(rec) + "\n", - ); -} - -function completedJobKeys(): Set { - const done = new Set(); - for (const dir of (process.env.CMP_RESUME ?? "").split(",").filter(Boolean)) { - const file = resolve(RESULTS_ROOT, dir, "results.jsonl"); - if (!existsSync(file)) continue; - for (const line of readFileSync(file, "utf-8").split("\n")) { - if (!line.trim()) continue; - try { - const rec = JSON.parse(line) as RunRecord; - if (!rec.error) { - done.add(`${rec.fixture}|${rec.model}|${rec.rep}`); - records.push(rec); // carry into this run's summary - } - } catch { - // skip malformed line - } - } - } - return done; -} - -// ── Spec validation (always runs, no API key needed) ─────────── -// The generated transcripts are gitignored, so on a clean checkout the -// fixture-validation block below has nothing to check. The committed -// authoring specs are what CI can and must validate — and their absence is -// a failure, not a skip. - -describe("compaction specs validate", () => { - it("committed specs are present", () => { - expect(loadSpecs().length).toBeGreaterThan(0); - }); - for (const { file, spec } of loadSpecs()) { - it(`${file} is internally consistent`, () => { - const errors = validateSpec(file, spec); - expect(errors, errors.join("\n")).toEqual([]); - }); - } -}); - -// ── Fixture validation (requires locally generated fixtures) ─── - -describe("compaction fixtures validate", () => { - if (fixtures.length === 0) { - it.skip("no generated fixtures present (see AUTHORING.md)", () => {}); - } - for (const fixture of fixtures) { - it(`${fixture.name} is internally consistent`, () => { - const errors = validateFixture(fixture); - expect(errors, errors.join("\n")).toEqual([]); - }); - } -}); - -// ── Benchmark ────────────────────────────────────────────────── - -const canRun = hasDyadProKey() && fixtures.length > 0 && optedIn; - -(canRun ? describe : describe.skip)("compaction quality benchmark", () => { - beforeAll(() => { - mkdirSync(RESULTS_DIR, { recursive: true }); - }); - - afterAll(() => { - const summary = summarize(records); - writeFileSync(resolve(RESULTS_DIR, "summary.md"), summary); - console.log(`\n${summary}\nResults: ${RESULTS_DIR}`); - }); - - const alreadyDone = completedJobKeys(); - const jobs: { fixture: CompactionFixture; model: string; rep: number }[] = []; - for (const fixture of fixtures) { - for (const model of MODELS) { - for (let rep = 1; rep <= REPS; rep++) { - if (alreadyDone.has(`${fixture.name}|${model}|${rep}`)) continue; - jobs.push({ fixture, model, rep }); - } - } - } - - for (const job of jobs) { - const name = `${job.fixture.name} · ${job.model} · rep${job.rep}`; - it.concurrent(name, async () => { - const base: RunRecord = { - fixture: job.fixture.name, - model: job.model, - rep: job.rep, - }; - try { - await gate(async () => { - const model = getEvalModel("openai", job.model); - const run = await runCompaction({ model, fixture: job.fixture }); - const structural = structuralChecks( - run.summary, - fixtureTranscript(job.fixture), - ); - const judgeModel = getEvalModel("openai", GPT_5_4); - const factGrid = await judgeFactGrid({ - judgeModel, - fixture: job.fixture, - summary: run.summary, - }); - const probes = await runProbes({ - probeModel: judgeModel, - judgeModel, - fixture: job.fixture, - summary: run.summary, - }); - recordRun({ - ...base, - scores: computeScores(job.fixture, factGrid, probes), - structural, - factGrid, - probes, - input_tokens: run.inputTokens, - output_tokens: run.outputTokens, - wall_ms: run.wallMs, - summary: run.summary, - }); - }); - } catch (error) { - recordRun({ - ...base, - error: - error instanceof Error - ? `${error.message}\n${error.stack}` - : String(error), - }); - } - expect(true).toBe(true); - }, 1_200_000); - } -}); - -// ── Summary ──────────────────────────────────────────────────── - -function pctf(x: number): string { - return `${Math.round(x * 100)}%`; -} -function mean(xs: number[]): number { - return xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0; -} - -function summarize(recs: RunRecord[]): string { - const ok = recs.filter((r) => !r.error && r.scores); - const errored = recs.filter((r) => r.error); - const lines: string[] = [ - `# Compaction benchmark — ${RUN_ID}`, - "", - `Runs: ${recs.length} (${errored.length} errored) · models: ${MODELS.join(", ")} · fixtures: ${fixtures.length} · reps: ${REPS}`, - "", - "| model | n | weighted retention | tier-1 retention | probe score | fact contradictions | trap contradictions | trap misses | halluc. paths | missing sections | mean summary tok | mean wall s |", - "|---|---|---|---|---|---|---|---|---|---|---|---|", - ]; - for (const model of MODELS) { - const rs = ok.filter((r) => r.model === model); - if (!rs.length) continue; - lines.push( - `| ${model} | ${rs.length} | ${pctf(mean(rs.map((r) => r.scores!.weightedRetention)))} | ${pctf(mean(rs.map((r) => r.scores!.tier1Retention)))} | ${pctf(mean(rs.map((r) => r.scores!.probeScore)))} | ${rs.reduce((a, r) => a + r.scores!.contradictedFacts, 0)} | ${rs.reduce((a, r) => a + r.scores!.trapContradictions, 0)} | ${rs.reduce((a, r) => a + r.scores!.trapMisses, 0)} | ${rs.reduce((a, r) => a + (r.structural?.hallucinatedPaths.length ?? 0), 0)} | ${rs.reduce((a, r) => a + (r.structural?.missingSections.length ?? 0), 0)} | ${Math.round(mean(rs.map((r) => r.structural?.summaryTokens ?? 0)))} | ${Math.round(mean(rs.map((r) => r.wall_ms ?? 0)) / 1000)} |`, - ); - } - - lines.push("", "## Weighted retention by fixture", ""); - lines.push( - `| fixture | ${MODELS.join(" | ")} |`, - `|---|${MODELS.map(() => "---").join("|")}|`, - ); - for (const f of [...new Set(ok.map((r) => r.fixture))].sort()) { - const row = MODELS.map((m) => { - const rs = ok.filter((r) => r.fixture === f && r.model === m); - return rs.length - ? pctf(mean(rs.map((r) => r.scores!.weightedRetention))) - : "–"; - }); - lines.push(`| ${f} | ${row.join(" | ")} |`); - } - - lines.push("", "## Probe score by fixture", ""); - lines.push( - `| fixture | ${MODELS.join(" | ")} |`, - `|---|${MODELS.map(() => "---").join("|")}|`, - ); - for (const f of [...new Set(ok.map((r) => r.fixture))].sort()) { - const row = MODELS.map((m) => { - const rs = ok.filter((r) => r.fixture === f && r.model === m); - return rs.length ? pctf(mean(rs.map((r) => r.scores!.probeScore))) : "–"; - }); - lines.push(`| ${f} | ${row.join(" | ")} |`); - } - - if (errored.length) { - lines.push("", "## Errors", ""); - for (const r of errored.slice(0, 15)) { - lines.push( - `- ${r.fixture} · ${r.model} · rep${r.rep}: ${r.error?.split("\n")[0]}`, - ); - } - } - return lines.join("\n"); -} diff --git a/studio/vendor/dyad/src/__tests__/evals/fixtures/UserProfile.tsx b/studio/vendor/dyad/src/__tests__/evals/fixtures/UserProfile.tsx deleted file mode 100644 index 047e51e4..00000000 --- a/studio/vendor/dyad/src/__tests__/evals/fixtures/UserProfile.tsx +++ /dev/null @@ -1,354 +0,0 @@ -// UserProfile.tsx — class-based user profile component - -import React from "react"; -import { - fetchUser, - updateUser, - fetchUserActivity, -} from "../services/userService"; -import type { User, ActivityEntry } from "../types"; - -interface Props { - userId: string; - onProfileUpdated?: (user: User) => void; - readOnly?: boolean; -} - -interface State { - user: User | null; - loading: boolean; - editing: boolean; - draft: Partial; - error: string | null; - saveError: string | null; - saving: boolean; - activity: ActivityEntry[]; - activityLoading: boolean; - activityError: string | null; - showActivity: boolean; - uploadingAvatar: boolean; - avatarError: string | null; -} - -export class UserProfile extends React.Component { - private avatarInputRef = React.createRef(); - - constructor(props: Props) { - super(props); - this.state = { - user: null, - loading: true, - editing: false, - draft: {}, - error: null, - saveError: null, - saving: false, - activity: [], - activityLoading: false, - activityError: null, - showActivity: false, - uploadingAvatar: false, - avatarError: null, - }; - } - - async componentDidMount() { - await this.loadUser(); - } - - async componentDidUpdate(prevProps: Props) { - if (prevProps.userId !== this.props.userId) { - this.setState({ - editing: false, - draft: {}, - saveError: null, - activity: [], - showActivity: false, - }); - await this.loadUser(); - } - } - - componentWillUnmount() { - // Clean up any pending state updates - } - - async loadUser() { - this.setState({ loading: true, error: null }); - try { - const user = await fetchUser(this.props.userId); - this.setState({ user, loading: false }); - } catch (err) { - this.setState({ - error: err instanceof Error ? err.message : "Failed to load user", - loading: false, - }); - } - } - - async loadActivity() { - this.setState({ activityLoading: true, activityError: null }); - try { - const activity = await fetchUserActivity(this.props.userId); - this.setState({ activity, activityLoading: false }); - } catch (err) { - this.setState({ - activityError: - err instanceof Error ? err.message : "Failed to load activity", - activityLoading: false, - }); - } - } - - handleEdit = () => { - this.setState({ - editing: true, - draft: { ...this.state.user }, - saveError: null, - }); - }; - - handleCancel = () => { - this.setState({ editing: false, draft: {}, saveError: null }); - }; - - handleChange = (field: keyof User, value: string) => { - this.setState((prev) => ({ draft: { ...prev.draft, [field]: value } })); - }; - - handleSave = async () => { - this.setState({ saving: true, saveError: null }); - try { - const updated = await updateUser(this.props.userId, this.state.draft); - this.setState({ - user: updated, - editing: false, - draft: {}, - saving: false, - }); - this.props.onProfileUpdated?.(updated); - } catch (err) { - this.setState({ - saveError: - err instanceof Error ? err.message : "Failed to save changes", - saving: false, - }); - } - }; - - handleToggleActivity = async () => { - const { showActivity, activity } = this.state; - if (!showActivity && activity.length === 0) { - await this.loadActivity(); - } - this.setState((prev) => ({ showActivity: !prev.showActivity })); - }; - - handleAvatarClick = () => { - this.avatarInputRef.current?.click(); - }; - - handleAvatarChange = async (e: React.ChangeEvent) => { - const file = e.target.files?.[0]; - if (!file) return; - - if (file.size > 5 * 1024 * 1024) { - this.setState({ avatarError: "Avatar must be under 5 MB" }); - return; - } - - this.setState({ uploadingAvatar: true, avatarError: null }); - try { - // Upload stub — real impl would POST to /api/avatars - await new Promise((r) => setTimeout(r, 500)); - const fakeUrl = URL.createObjectURL(file); - const updated = await updateUser(this.props.userId, { - avatarUrl: fakeUrl, - }); - this.setState({ user: updated, uploadingAvatar: false }); - } catch (err) { - this.setState({ - avatarError: - err instanceof Error ? err.message : "Failed to upload avatar", - uploadingAvatar: false, - }); - } - }; - - renderActivityFeed() { - const { activity, activityLoading, activityError } = this.state; - - if (activityLoading) { - return

Loading activity…

; - } - if (activityError) { - return

{activityError}

; - } - if (activity.length === 0) { - return

No recent activity.

; - } - return ( -
    - {activity.map((entry) => ( -
  • - {entry.action} - - {new Date(entry.timestamp).toLocaleString()} - -
  • - ))} -
- ); - } - - render() { - const { - user, - loading, - editing, - draft, - error, - saveError, - saving, - showActivity, - uploadingAvatar, - avatarError, - } = this.state; - const { readOnly } = this.props; - - if (loading) { - return
Loading profile…
; - } - - if (error) { - return ( -
-

{error}

- -
- ); - } - - if (!user) return null; - - return ( -
-
-
- {user.avatarUrl ? ( - {`${user.name}'s - ) : ( -
- {user.name.charAt(0).toUpperCase()} -
- )} - {!readOnly && ( -
- {uploadingAvatar ? "Uploading…" : "Change"} -
- )} -
- {!readOnly && ( - - )} - {avatarError &&

{avatarError}

} -

{user.name}

- - {user.role} - -
- - {editing ? ( -
{ - e.preventDefault(); - this.handleSave(); - }} - > - - -