Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(web): add consent-aware frontend observability (#875)
Gener17ba785038ec
diff --git a/codecov.yml b/codecov.ymlindex c4654f562..fb913a1c9 100644--- a/codecov.yml+++ b/codecov.yml@@ -29,6 +29,7 @@ ignore:# Next config is loaded by the Next runtime, not vitest — redirects live in# `src/web/src/lib/blog/redirects.ts` (unit-tested) and are wired here only.- "src/web/next.config.ts"+ - "src/web/blog/next.config.ts"# Playwright browser E2E — driven by `playwright test`, not vitest, so these# files never appear in coverage and shouldn't count against patch %.- "src/web/src/test/e2e-ui/**"diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c84b13e41..65f831060 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -292,6 +292,12 @@ importers:'@emoji-mart/react':specifier: ^1.1.1version: 1.1.1([email protected])([email protected])+ '@grafana/faro-web-sdk':+ specifier: 2.12.1+ version: 2.12.1+ '@grafana/faro-web-tracing':+ specifier: 2.12.1+ version: 2.12.1'@gsap/react':specifier: ^2.1.2version: 2.1.2([email protected])([email protected])@@ -309,16 +315,19 @@ importers:version: 16.3.8(@mdx-js/[email protected])(@mdx-js/[email protected](@types/[email protected])([email protected]))'@next/third-parties':specifier: ^16.3.8- version: 16.3.8([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 16.3.8([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected])'@number-flow/react':specifier: ^0.6.2'@opennextjs/cloudflare':specifier: ^1.20.6- version: 1.20.6([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected](@cloudflare/[email protected])(@types/[email protected]))+ version: 1.20.6([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected](@cloudflare/[email protected])(@types/[email protected]))'@openrouter/sdk':specifier: 1.4.18version: 1.4.18+ '@opentelemetry/api':+ specifier: 1.9.0+ version: 1.9.0'@shikijs/core':specifier: 4.5.0version: 4.5.0@@ -411,7 +420,7 @@ importers:version: 12.12.0(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])better-auth:specifier: 1.7.7- version: 1.7.7(@opentelemetry/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])+ version: 1.7.7(@opentelemetry/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected])class-variance-authority:specifier: ^0.7.1version: 0.7.1@@ -477,7 +486,7 @@ importers:version: 5.1.16next:specifier: 16.3.8- version: 16.3.8(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])+ version: 16.3.8(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])next-themes:specifier: ^0.4.6@@ -616,7 +625,7 @@ importers:version: 6.32.2react-scan:specifier: 0.5.7- version: 0.5.7(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 0.5.7(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))remark-parse:specifier: ^11.0.0version: 11.0.0@@ -634,7 +643,7 @@ importers:version: 11.0.5vitest:specifier: 4.1.11- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))wrangler:specifier: 4.146.0version: 4.146.0(@cloudflare/[email protected])(@types/[email protected])@@ -1965,6 +1974,15 @@ packages:'@formatjs/[email protected]':resolution: {integrity: sha512-XOMO2Hupl0wdd172Y06h6kLpBz6Dv+J4okPLl4LPtzbr8f66WbIoy4ev98EBuZ6ZK4h5ydTN6XneT4QVpD7cdA==}+ '@grafana/[email protected]':+ resolution: {integrity: sha512-Pg0vjgsR1BxdmLzzX9r8YcZ8rI4aXLlDGtreppZev++BbnH2utKBwCI16Vx+IzfQqHKRT+7WGc63HOue8/9J6Q==}++ '@grafana/[email protected]':+ resolution: {integrity: sha512-JnpZy/ztfkP3UZ3AW0DzUxVgMRTBvYz+m0oZuVi+KRpGTYz0GGF0umi0S0pAemnaUbQBo6umGdCm5CL6n8BAWQ==}++ '@grafana/[email protected]':+ resolution: {integrity: sha512-m9TEjPsEc8kJVeKnHoHCEPz7eDVpn/etZqMc2louYCWZsXIH4v2hlfT8ZY3MAIKCzBPBgoxVFqOOjvSwtOKRfw==}+'@gsap/[email protected]':resolution: {integrity: sha512-JqliybO1837UcgH2hVOM4VO+38APk3ECNrsuSM4MuXp+rbf+/2IG2K1YJiqfTcXQHH7XlA0m3ykniFYstfq0Iw==}peerDependencies:@@ -2704,6 +2722,14 @@ packages:resolution: {integrity: sha512-CmVa4ImJ+ynfrPMNaAXHET6Bhb44SwzmfyVJFq9ni2jgXJR/l7C6gfVFddNmHP+ZOkP9cf4f9DBe68qVLTHc9w==}engines: {node: '>=8.0.0'}+ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-9mb1If+IF6u0ZVXkHQ6ogEae5HwA6ajIVUgpSDQyRASxft6BSXHvBvPooRle3yFN/fKnCdSOnuu0OC3PLcF6+g==}+ engines: {node: '>=8.0.0'}++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==}+ engines: {node: '>=8.0.0'}+'@opentelemetry/[email protected]':resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==}engines: {node: '>=8.0.0'}@@ -2714,24 +2740,78 @@ packages:peerDependencies:'@opentelemetry/api': '>=1.0.0 <1.10.0'+ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-RCnPWcHppwiquQ+cV3nWvNwdf0MG1w26e5jewW2T83nTZOlXgcg88sY9ulCVgagGHcq1mj0L0GP6YHgzk2v8oA==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-I0Vlvi1uzSnu4+cMssnYdaQgcJf/ffs0HSnq8/ZlkjgNS/J+ABc3196lZyL7uy++yRCl3bg2zPMhTphVdNx5sA==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-bA+6QSEV0tk/7IfGgCBnVIhTB6ljVP+eMuwCq/vPapNAZWsuS/8nFd+WE1R0oPJk+TBGGck23bhjq662MqJAEg==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0+'@opentelemetry/[email protected]':resolution: {integrity: sha512-xQx3E2WxP1mDvKzxLxX+CTCtNLa560YJZ3087qYHerl2YmiKpv7AH+dAy7vmx+eVrZ5BwhfWUAVoKOoxCNHcpw==}engines: {node: ^18.19.0 || >=20.6.0}peerDependencies:'@opentelemetry/api': ^1.3.0+ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-fhbRDuAgzPKpq1k5+hX3uS+3QAYNca0on0Ngot/R8dDsQtuFaADeZnG2uSgxABuvcI7S2phAaRhbct9jieeKZw==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-YbywG3veEm2Fb6TbdxRkuquWob6eVWXuA8/Ba1tXz9jHfUqpdE3keilOHEtPboC4CvS1bjeeVfNkWGOOrLj+lw==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-/F3BZ89+CJQnZkMh2tCrtcdB+XT2Dxhj4FFE+WPQ//413hmFL0/RfEX6vgOIWGhiSzrkHWTK3+6SiT7K5/g/jQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0+'@opentelemetry/[email protected]':resolution: {integrity: sha512-Ie7+8q8MDF4FAEQCKVMTx3ReUvxiIAgIiiW3c9JdmP8+HMcDy20puT+AHjexnExgnbvBxjQ9fjkFDWrikJ2jQA==}engines: {node: ^18.19.0 || >=20.6.0}peerDependencies:'@opentelemetry/api': '>=1.3.0 <1.10.0'+ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-+19YHODIjaUCArxleaJtuufFZVpz/xvvK+VllQqE+W8hHolxdoRwHfK/s667zezwh1hkx6FFF+oYzetYgqK+Bg==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.4.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-7GXXcObyHyDUUSG+L+kJoquty01bzm7ivE7+SSgXXJcHuPzGviptxwARmI2c+bnnxjexGQbJnyNlN8HxBP/Y7A==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.9.0 <1.10.0'+'@opentelemetry/[email protected]':resolution: {integrity: sha512-H19x/TX/LZdqiYOjM7fqtSxwlplC5pgelavqbQdHbhdq0q/AI/TGkM2dfGuuynTXmJPeF2HoZVoPDu+TGoW78A==}engines: {node: ^18.19.0 || >=20.6.0}peerDependencies:'@opentelemetry/api': '>=1.3.0 <1.10.0'+ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-8hgLI437x8VRKzgUr+WRcHFp9AeaHmveKRsPIMNele9tethgCKprakRRqZCWyt41ilALHATfspUMl1An0OTMUQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.0.0 <1.10.0'+'@opentelemetry/[email protected]':resolution: {integrity: sha512-fFnTqGm8/G73GQVnxYi7LXa1ZVYEUvgL6XI1LpvV0bPC7WQ/ZGgKxCSl8FnlZBKto9JHHEFTO6s6CUpvvtwFrA==}engines: {node: ^18.19.0 || >=20.6.0}@@ -8088,8 +8168,8 @@ packages:resolution: {integrity: sha512-FY91FiDBj7ls5MsFS9jN3tjz2o0/zsdSsymlakySaBwVJZorHhkWyICLZMKxlu1R9vYo+sd3z1jwb4J8x7bNDw==}- resolution: {integrity: sha512-YGdwFmQXGQulT63SnVD9JI1hV2EwGnZHrgSlUMQaOkvnhYA200QwDeb7DfVT8UBt34lBvbkjtz8VRFJugHjsRQ==}+ resolution: {integrity: sha512-j6tdFoJbLztISYNlw7LMT+6naqhVsXTNn7drhoGRIqf0x2mCSD2Ur71hK0E/VrLens355finI6j+sMqHxHpEfA==}engines: {node: ^20.19.0 || >=22.13.0}@@ -8439,8 +8519,8 @@ packages:resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==}hasBin: true- resolution: {integrity: sha512-JzOwAY/hoSxHa4Siyqgfxr/KCNak0SB9pSTseFVStFHAnWS+XxR6RsWU6Q5Ho+J5Jmyb9LZRXc6ZK5jt3cfcQQ==}+ resolution: {integrity: sha512-YCsjYk6MocO/oBhVxCcKvPotFxEOf/WJep/oF7jrpyVUBVKDKdpt7jVwTxrJrFE8uALMmVTljzXNTIjoL3talg==}engines: {node: ^20.19.0 || >=22.13.0}hasBin: true@@ -9376,6 +9456,10 @@ packages:engines: {node: '>=14.17'}hasBin: true+ resolution: {integrity: sha512-LbBDqdIC5s8iROCUjMbW1f5dJQTEFB1+KO9ogbvlb3nm9n4YHa5p4KTvFPWvh2Hs8gZMBuiB1/8+pdfe/tDPug==}+ hasBin: true+resolution: {integrity: sha512-8iAasVS4wUx0gPLjH8Xtz2PeDzTSiy8QiLGu2DT3X5GU+egFEQhpnbtkehbAwjvDcxIERmCYcysiODFmE3Ud0Q==}engines: {node: '>=18'}@@ -9662,6 +9746,9 @@ packages:resolution: {integrity: sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==}engines: {node: '>= 14'}+ resolution: {integrity: sha512-Dmy+vdO1UPMqXiAtZSNayhl4f794Bxfd94W4HIj2HlYtczEQfEOon969memlcpcHrTuOKLa5baFjX7WbgmOq+A==}+resolution: {integrity: sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw==}@@ -10776,7 +10863,7 @@ snapshots:'@bcoe/[email protected]': {}- '@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])':+ '@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])':dependencies:'@better-auth/utils': 0.4.2'@better-fetch/fetch': 1.3.2@@ -10788,40 +10875,40 @@ snapshots:nanostores: 1.5.4zod: 4.6.5optionalDependencies:- '@opentelemetry/api': 1.9.1+ '@opentelemetry/api': 1.9.0- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))':+ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))':dependencies:- '@better-auth/core': 1.7.7(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/core': 1.7.7(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/utils': 0.4.2optionalDependencies:- drizzle-orm: 0.45.3(@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])+ drizzle-orm: 0.45.3(@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected])':+ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected])':dependencies:- '@better-auth/core': 1.7.7(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/core': 1.7.7(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/utils': 0.4.2optionalDependencies:kysely: 0.29.6- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':+ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':dependencies:- '@better-auth/core': 1.7.7(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/core': 1.7.7(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/utils': 0.4.2- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':+ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':dependencies:- '@better-auth/core': 1.7.7(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/core': 1.7.7(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/utils': 0.4.2- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':+ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])':dependencies:- '@better-auth/core': 1.7.7(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/core': 1.7.7(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/utils': 0.4.2- '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])':+ '@better-auth/[email protected](@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])':dependencies:- '@better-auth/core': 1.7.7(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/core': 1.7.7(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])'@better-auth/utils': 0.4.2'@better-fetch/fetch': 1.3.2@@ -10858,7 +10945,7 @@ snapshots:cjs-module-lexer: 1.2.3esbuild: 0.28.1miniflare: 5.20261001.0-alpha(@types/[email protected])- vitest: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))wrangler: 4.146.0(@cloudflare/[email protected])(@types/[email protected])zod: 4.4.3transitivePeerDependencies:@@ -11379,6 +11466,33 @@ snapshots:dependencies:tslib: 2.8.1+ '@grafana/[email protected]':+ dependencies:+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/otlp-transformer': 0.222.0(@opentelemetry/[email protected])++ '@grafana/[email protected]':+ dependencies:+ '@grafana/faro-core': 2.12.1+ ua-parser-js: 1.0.41+ web-vitals: 6.2.3++ '@grafana/[email protected]':+ dependencies:+ '@grafana/faro-web-sdk': 2.12.1+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-trace-otlp-http': 0.222.0(@opentelemetry/[email protected])+ '@opentelemetry/instrumentation': 0.222.0(@opentelemetry/[email protected])+ '@opentelemetry/instrumentation-fetch': 0.222.0(@opentelemetry/[email protected])+ '@opentelemetry/instrumentation-xml-http-request': 0.222.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.222.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-web': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0+ transitivePeerDependencies:+ - supports-color+dependencies:gsap: 3.15.0@@ -12001,9 +12115,9 @@ snapshots:'@next/[email protected]':optional: true- '@next/[email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected])':+ '@next/[email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected])':dependencies:- next: 16.3.8(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])+ next: 16.3.8(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])react: 19.3.0third-party-capital: 1.0.20@@ -12070,7 +12184,7 @@ snapshots:'@open-draft/[email protected]':optional: true- '@opennextjs/[email protected](patch_hash=6a1b801adbed4307cde86c12f701bc354047783b077e836f58af1e362e244b9e)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))':+ '@opennextjs/[email protected](patch_hash=6a1b801adbed4307cde86c12f701bc354047783b077e836f58af1e362e244b9e)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))':dependencies:'@ast-grep/napi': 0.40.5'@aws-sdk/client-cloudfront': 3.984.0@@ -12086,24 +12200,24 @@ snapshots:cookie: 1.1.1esbuild: 0.25.4express: 5.2.1- next: 16.3.8(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])+ next: 16.3.8(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])path-to-regexp: 6.3.0urlpattern-polyfill: 10.1.0yaml: 2.9.0transitivePeerDependencies:- supports-color- '@opennextjs/[email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected](@cloudflare/[email protected])(@types/[email protected]))':+ '@opennextjs/[email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected](@cloudflare/[email protected])(@types/[email protected]))':dependencies:'@ast-grep/napi': 0.40.5'@dotenvx/dotenvx': 1.31.0- '@opennextjs/aws': 4.1.4(patch_hash=6a1b801adbed4307cde86c12f701bc354047783b077e836f58af1e362e244b9e)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))+ '@opennextjs/aws': 4.1.4(patch_hash=6a1b801adbed4307cde86c12f701bc354047783b077e836f58af1e362e244b9e)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))ci-info: 4.4.0cloudflare: 4.5.0comment-json: 4.6.2enquirer: 2.4.1glob: 12.0.0- next: 16.3.8(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])+ next: 16.3.8(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])ts-tqdm: 0.8.6wrangler: 4.146.0(@cloudflare/[email protected])(@types/[email protected])yargs: 18.0.0@@ -12117,15 +12231,53 @@ snapshots:'@opentelemetry/[email protected]':dependencies:- '@opentelemetry/api': 1.9.1+ '@opentelemetry/api': 1.9.0++ '@opentelemetry/[email protected]':+ dependencies:+ '@opentelemetry/api': 1.9.0++ '@opentelemetry/[email protected]': {}'@opentelemetry/[email protected]': {}+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/semantic-conventions': 1.43.0+'@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:'@opentelemetry/api': 1.9.1'@opentelemetry/semantic-conventions': 1.43.0+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/otlp-exporter-base': 0.222.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.222.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace': 2.11.0(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/instrumentation': 0.222.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-web': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0+ transitivePeerDependencies:+ - supports-color++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/instrumentation': 0.222.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-web': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0+ transitivePeerDependencies:+ - supports-color+'@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:'@opentelemetry/api': 1.9.1@@ -12135,12 +12287,65 @@ snapshots:transitivePeerDependencies:- supports-color+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/api-logs': 0.222.0+ import-in-the-middle: 3.5.2+ require-in-the-middle: 8.0.1+ transitivePeerDependencies:+ - supports-color++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.222.0(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/api-logs': 0.222.0+ '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-logs': 0.222.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-metrics': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace': 2.11.0(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0+'@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:'@opentelemetry/api': 1.9.1'@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])'@opentelemetry/semantic-conventions': 1.43.0+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/api-logs': 0.222.0+ '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.11.0(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0+'@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:'@opentelemetry/api': 1.9.1@@ -12149,6 +12354,19 @@ snapshots:'@opentelemetry/sdk-trace': 2.11.0(@opentelemetry/[email protected])'@opentelemetry/semantic-conventions': 1.43.0+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-base': 2.11.0(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.0+ '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0+'@opentelemetry/[email protected](@opentelemetry/[email protected])':dependencies:'@opentelemetry/api': 1.9.1@@ -12537,27 +12755,28 @@ snapshots:'@sentry/utils': 7.120.4localforage: 1.10.0- '@sentry/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))':+ '@sentry/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))':dependencies:'@sentry/conventions': 0.16.0'@sentry/core': 10.75.3- '@sentry/opentelemetry': 10.75.3(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))+ '@sentry/opentelemetry': 10.75.3(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))import-in-the-middle: 3.5.2optionalDependencies:'@opentelemetry/api': 1.9.1- '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-trace-otlp-http': 0.222.0(@opentelemetry/[email protected])'@opentelemetry/instrumentation': 0.220.0(@opentelemetry/[email protected])'@opentelemetry/sdk-trace-base': 2.11.0(@opentelemetry/[email protected])+ '@sentry/[email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))':dependencies:'@opentelemetry/api': 1.9.1'@opentelemetry/instrumentation': 0.220.0(@opentelemetry/[email protected])'@opentelemetry/sdk-trace-base': 2.11.0(@opentelemetry/[email protected])'@sentry/conventions': 0.16.0'@sentry/core': 10.75.3- '@sentry/node-core': 10.75.3(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))- '@sentry/opentelemetry': 10.75.3(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))+ '@sentry/node-core': 10.75.3(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))+ '@sentry/opentelemetry': 10.75.3(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))'@sentry/server-utils': 10.75.3import-in-the-middle: 3.5.2transitivePeerDependencies:@@ -12573,10 +12792,10 @@ snapshots:'@sentry/types': 7.120.4'@sentry/utils': 7.120.4- '@sentry/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))':+ '@sentry/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))':dependencies:'@opentelemetry/api': 1.9.1- '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])+ '@opentelemetry/core': 2.11.0(@opentelemetry/[email protected])'@opentelemetry/sdk-trace-base': 2.11.0(@opentelemetry/[email protected])'@sentry/conventions': 0.16.0'@sentry/core': 10.75.3@@ -13205,7 +13424,7 @@ snapshots:picocolors: 1.1.1redent: 3.0.0optionalDependencies:- vitest: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@testing-library/[email protected](@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:@@ -13870,7 +14089,7 @@ snapshots:magicast: 0.5.4obug: 2.1.4tinyrainbow: 3.1.1- vitest: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))transitivePeerDependencies:- supports-color@@ -13886,7 +14105,7 @@ snapshots:obug: 2.1.4std-env: 4.2.0tinyrainbow: 3.1.1- vitest: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@vitest/[email protected]':dependencies:@@ -14250,15 +14469,15 @@ snapshots:- [email protected](@opentelemetry/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected]):+ [email protected](@opentelemetry/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected]):dependencies:- '@better-auth/core': 1.7.7(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])- '@better-auth/drizzle-adapter': 1.7.7(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))- '@better-auth/kysely-adapter': 1.7.7(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected])- '@better-auth/memory-adapter': 1.7.7(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])- '@better-auth/mongo-adapter': 1.7.7(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])- '@better-auth/prisma-adapter': 1.7.7(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])- '@better-auth/telemetry': 1.7.7(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])+ '@better-auth/core': 1.7.7(@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])+ '@better-auth/drizzle-adapter': 1.7.7(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))+ '@better-auth/kysely-adapter': 1.7.7(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected])+ '@better-auth/memory-adapter': 1.7.7(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])+ '@better-auth/mongo-adapter': 1.7.7(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])+ '@better-auth/prisma-adapter': 1.7.7(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])+ '@better-auth/telemetry': 1.7.7(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])'@better-auth/utils': 0.4.2'@better-fetch/fetch': 1.3.2'@noble/ciphers': 2.4.0@@ -14270,12 +14489,12 @@ snapshots:nanostores: 1.5.4zod: 4.6.5optionalDependencies:- drizzle-orm: 0.45.3(@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])- next: 16.3.8(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])+ drizzle-orm: 0.45.3(@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])+ next: 16.3.8(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])react: 19.3.0react-dom: 19.3.0([email protected])solid-js: 1.9.15- vitest: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))transitivePeerDependencies:- '@opentelemetry/api'@@ -15056,6 +15275,16 @@ snapshots:+ [email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]):+ optionalDependencies:+ '@cloudflare/workers-types': 5.20261002.1+ '@opentelemetry/api': 1.9.0+ '@types/better-sqlite3': 7.6.13+ better-sqlite3: 12.11.1+ bun-types: 1.4.2+ kysely: 0.29.6+ optional: true+[email protected](@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]):optionalDependencies:'@cloudflare/workers-types': 5.20261002.1@@ -15362,7 +15591,7 @@ snapshots:'@next/eslint-plugin-next': 16.3.8([email protected]([email protected]))eslint: 9.39.5([email protected])eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected]([email protected]([email protected])))([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))eslint-plugin-react: 7.37.5([email protected]([email protected]))@@ -15385,7 +15614,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])):dependencies:'@nolyfill/is-core-module': 1.0.39debug: 4.4.3@@ -15400,13 +15629,13 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected]([email protected])([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:eslint: 9.39.5([email protected])eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected]([email protected]([email protected])))([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))transitivePeerDependencies:- supports-color@@ -15421,7 +15650,7 @@ snapshots:doctrine: 2.1.0eslint: 9.39.5([email protected])eslint-import-resolver-node: 0.3.10- eslint-module-utils: 2.14.0([email protected])([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))+ eslint-module-utils: 2.14.0([email protected])([email protected])([email protected]([email protected]))hasown: 2.0.4is-core-module: 2.17.0is-glob: 4.0.3@@ -17830,7 +18059,7 @@ snapshots:react: 19.3.0react-dom: 19.3.0([email protected])- [email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]):+ [email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected]):dependencies:'@next/env': 16.3.8'@swc/helpers': 0.5.23@@ -17849,7 +18078,7 @@ snapshots:'@next/swc-linux-x64-musl': 16.3.8'@next/swc-win32-arm64-msvc': 16.3.8'@next/swc-win32-x64-msvc': 16.3.8- '@opentelemetry/api': 1.9.1+ '@opentelemetry/api': 1.9.0'@playwright/test': 1.63.0sharp: 0.35.5(@types/[email protected])transitivePeerDependencies:@@ -18105,7 +18334,7 @@ snapshots:'@oxc-resolver/binding-win32-arm64-msvc': 11.24.2'@oxc-resolver/binding-win32-x64-msvc': 11.24.2dependencies:'@shaderfrog/glsl-parser': 7.0.1'@typescript-eslint/types': 8.71.0@@ -18522,10 +18751,10 @@ snapshots:minimist: 1.2.8strip-json-comments: 2.0.1- [email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))([email protected]):+ [email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))([email protected]):dependencies:'@astrojs/compiler': 4.0.0- '@sentry/node': 10.75.3(@opentelemetry/[email protected](@opentelemetry/[email protected]))+ '@sentry/node': 10.75.3(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))agent-install: 0.0.5bippy: 0.6.1([email protected])conf: 15.1.0@@ -18537,7 +18766,7 @@ snapshots:oxc-parser: 0.148.0oxc-resolver: 11.24.2oxlint: 1.81.0- oxlint-plugin-react-doctor: 0.9.14+ oxlint-plugin-react-doctor: 0.9.17playwright-core: 1.63.0prompts: 2.4.2typescript: 5.9.3@@ -18579,7 +18808,7 @@ snapshots:react: 19.3.0react-dom: 19.3.0([email protected])- [email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@babel/core': 7.29.7'@babel/types': 7.29.7@@ -18591,7 +18820,7 @@ snapshots:preact: 10.29.7prompts: 2.4.2react: 19.3.0- react-doctor: 0.9.14(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))([email protected])+ react-doctor: 0.9.17(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))([email protected])react-dom: 19.3.0([email protected])react-grab: 0.2.0([email protected])optionalDependencies:@@ -19912,6 +20141,8 @@ snapshots:+ [email protected]: {}+@@ -20138,6 +20369,37 @@ snapshots:tsx: 4.23.15yaml: 2.9.1+ [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ dependencies:+ '@vitest/expect': 4.1.11+ '@vitest/mocker': 4.1.11([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ '@vitest/pretty-format': 4.1.11+ '@vitest/runner': 4.1.11+ '@vitest/snapshot': 4.1.11+ '@vitest/spy': 4.1.11+ '@vitest/utils': 4.1.11+ es-module-lexer: 2.3.2+ expect-type: 1.4.0+ magic-string: 0.30.21+ obug: 2.1.4+ pathe: 2.0.3+ picomatch: 4.0.7+ std-env: 4.2.0+ tinybench: 2.9.0+ tinyexec: 1.3.1+ tinyglobby: 0.2.17+ tinyrainbow: 3.1.1+ vite: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ why-is-node-running: 2.3.0+ optionalDependencies:+ '@opentelemetry/api': 1.9.0+ '@types/node': 25.9.4+ '@vitest/coverage-istanbul': 4.1.11([email protected])+ '@vitest/coverage-v8': 4.1.11([email protected])+ jsdom: 29.1.1(@noble/[email protected])+ transitivePeerDependencies:+ - msw+[email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@vitest/expect': 4.1.11@@ -20243,6 +20505,8 @@ snapshots:+ [email protected]: {}+diff --git a/src/web/blog/src/app/blog/(index)/page.tsx b/src/web/blog/src/app/blog/(index)/page.tsxindex de6870221..4cf93553b 100644--- a/src/web/blog/src/app/blog/(index)/page.tsx+++ b/src/web/blog/src/app/blog/(index)/page.tsx@@ -1,3 +1,4 @@+import { ObservedStaticContent } from "@/lib/observability/regions";import type { Metadata } from "next";import Image from "next/image";import Link from "next/link";@@ -47,6 +48,7 @@ export default async function BlogPage() {return (<>+ <ObservedStaticContent key="/blog" pathname="/blog" /><scripttype="application/ld+json"dangerouslySetInnerHTML={{ __html: JSON.stringify(collectionJsonLd) }}diff --git a/src/web/blog/src/app/blog/[slug]/page.tsx b/src/web/blog/src/app/blog/[slug]/page.tsxindex 2fe7c9c59..ea769f135 100644--- a/src/web/blog/src/app/blog/[slug]/page.tsx+++ b/src/web/blog/src/app/blog/[slug]/page.tsx@@ -1,3 +1,4 @@+import { ObservedStaticContent } from "@/lib/observability/regions";import type { Metadata } from "next";import { notFound } from "next/navigation";import Link from "next/link";@@ -59,6 +60,7 @@ export default async function BlogPostPage({return (<>+ <ObservedStaticContent key={slug} pathname={`/blog/${slug}`} /><scripttype="application/ld+json"dangerouslySetInnerHTML={{ __html: JSON.stringify(blogPostingJsonLd) }}diff --git a/src/web/blog/src/app/blog/observability.dom.test.tsx b/src/web/blog/src/app/blog/observability.dom.test.tsxnew file mode 100644index 000000000..e10cde53a--- /dev/null+++ b/src/web/blog/src/app/blog/observability.dom.test.tsx@@ -0,0 +1,146 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import type { ComponentProps } from "react";+import { act, render, screen, waitFor } from "@/test/react-dom-harness";+import { beginNavigation, clearActions, commitNavigation } from "@/lib/observability/context";+import { configureTelemetry, installTelemetrySink, retireTelemetry } from "@/lib/observability/telemetry";+import { ObservedRouteCommit } from "@/lib/observability/regions";+import type { BlogPost } from "@blog/lib/blog/types";+import BlogPage from "./(index)/page";+import BlogPostPage, { generateMetadata, generateStaticParams } from "./[slug]/page";++const loaders = vi.hoisted(() => ({ all: vi.fn(), one: vi.fn() }));+vi.mock("@blog/lib/blog/posts", () => ({ getAllPosts: loaders.all, getPostBySlug: loaders.one }));+vi.mock("next/link", () => ({ default: (props: ComponentProps<"a">) => <a {...props} /> }));+vi.mock("next/image", () => ({ default: ({ fill: _fill, preload: _preload, ...props }: ComponentProps<"img"> & { fill?: boolean; preload?: boolean }) => <img {...props} alt={props.alt ?? ""} /> }));+vi.mock("next/navigation", () => ({+ usePathname: () => window.location.pathname,+ useSearchParams: () => new URLSearchParams(window.location.search),+ notFound: () => { throw new Error("NEXT_HTTP_ERROR_FALLBACK;404"); },+}));+vi.mock("@blog/content/introducing-alook.mdx", () => ({ default: () => <p>Shared rooms retain the team's context.</p>, jsonLd: { "@type": "FAQPage" } }));+vi.mock("@blog/content/local-ai-agents.mdx", () => ({ default: () => <p>Local agents work beside your tools.</p>, jsonLd: undefined }));++const posts: BlogPost[] = [+ { slug: "introducing-alook", title: "Human-AI Collaboration Moves to the Group Chat", date: "2026-08-01", author: "Alook", excerpt: "A shared room for people and agents.", readingTime: "5 min read" },+ { slug: "local-ai-agents", title: "Local AI agents", date: "2026-09-01", author: "Alook", excerpt: "Agents beside your tools.", readingTime: "4 min read" },+];+const events: Array<{ name: string; attributes: Record<string, string> }> = [];+const forAction = (id: string) => events.filter(event => event.attributes.action_id === id);+const ready = (id: string) => forAction(id).filter(event => event.name === "region.ready_commit");++beforeEach(() => {+ events.length = 0;+ loaders.all.mockReset().mockResolvedValue(posts);+ loaders.one.mockReset().mockImplementation(async (slug: string) => posts.find(post => post.slug === slug));+ window.history.replaceState(null, "", "/blog");+ configureTelemetry({ session_id: "blog-session" }, true);+ installTelemetrySink(event => events.push(event));+ vi.stubGlobal("matchMedia", vi.fn(() => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() })));+});+afterEach(async () => {+ await act(async () => { retireTelemetry(); clearActions(); });+ vi.unstubAllGlobals();+});++it("executes the actual index loader and renders ordered featured/recent links before reporting unknown SSR evidence", async () => {+ const navigation = beginNavigation("/blog")!;+ render(await BlogPage());+ expect(screen.getByRole("heading", { level: 1, name: "Blog" })).toBeVisible();+ expect(screen.getByRole("region", { name: "Featured article" })).toHaveTextContent("Local AI agents");+ expect(screen.getByRole("link", { name: /Human-AI Collaboration/ })).toHaveAttribute("href", "/blog/introducing-alook");+ await waitFor(() => expect(ready(navigation.id)).toHaveLength(1));+ expect(ready(navigation.id)[0]!.attributes).toMatchObject({ region: "page", route_template: "/blog", source: "unknown", freshness: "unknown", data_version: "ssr_committed" });+ expect(navigation.done).toBe(true);+});++it("renders the actual legal empty index after its loader completes", async () => {+ loaders.all.mockResolvedValueOnce([]);+ render(await BlogPage());+ expect(screen.getByText("New stories are on the way.")).toBeVisible();+ expect(screen.queryByRole("region", { name: "Featured article" })).toBeNull();+ expect(screen.getByText("No recent stories in this topic yet.")).toBeVisible();+});++it("does not certify a retained old index after the URL commits while the actual article loader is still pending", async () => {+ const index = await BlogPage();+ const view = render(index);+ let release!: (post: BlogPost) => void;+ loaders.one.mockImplementationOnce(() => new Promise<BlogPost>(resolve => { release = resolve; }));+ let navigation!: NonNullable<ReturnType<typeof beginNavigation>>;+ let article!: ReturnType<typeof BlogPostPage>;+ await act(async () => {+ navigation = beginNavigation("/blog/introducing-alook")!;+ article = BlogPostPage({ params: Promise.resolve({ slug: "introducing-alook" }) });+ });+ await act(async () => {+ window.history.pushState(null, "", "/blog/introducing-alook");+ commitNavigation(window.location.pathname, "page");+ });+ expect(screen.getByRole("heading", { level: 1, name: "Blog" })).toBeVisible();+ expect(ready(navigation.id)).toHaveLength(0);+ expect(navigation.done).toBe(false);+ await act(async () => { release(posts[0]!); view.rerender(await article); });+ expect(screen.getByRole("heading", { level: 1, name: posts[0]!.title })).toBeVisible();+ expect(screen.getByText("Shared rooms retain the team's context.")).toBeVisible();+ await waitFor(() => expect(ready(navigation.id)).toHaveLength(1));+ expect(forAction(navigation.id).filter(event => event.name === "action.finish").map(event => event.attributes.outcome)).toEqual(["success"]);+ expect(ready(navigation.id)[0]!.attributes.route_template).toBe("/blog/[slug]");+ expect(document.querySelectorAll('script[type="application/ld+json"]')).toHaveLength(2);+});++it("finishes the new article navigation but rejects a late previous article tree", async () => {+ window.history.replaceState(null, "", "/blog/introducing-alook");+ const previous = await BlogPostPage({ params: Promise.resolve({ slug: "introducing-alook" }) });+ const view = render(previous);+ let navigation!: NonNullable<ReturnType<typeof beginNavigation>>;+ await act(async () => { navigation = beginNavigation("/blog/local-ai-agents")!; });+ await act(async () => {+ window.history.pushState(null, "", "/blog/local-ai-agents");+ commitNavigation(window.location.pathname, "page");+ });+ expect(ready(navigation.id)).toHaveLength(0);+ await act(async () => { view.rerender(await BlogPostPage({ params: Promise.resolve({ slug: "local-ai-agents" }) })); });+ expect(screen.getByRole("heading", { level: 1, name: "Local AI agents" })).toBeVisible();+ expect(screen.getByText("Local agents work beside your tools.")).toBeVisible();+ expect(ready(navigation.id)).toHaveLength(1);+ const count = events.filter(event => event.name === "region.ready_commit").length;+ await act(async () => { view.rerender(previous); });+ expect(events.filter(event => event.name === "region.ready_commit")).toHaveLength(count);+});++it("uses canonical post metadata/static params and invokes actual not-found for an unknown slug", async () => {+ expect(await generateStaticParams()).toEqual(posts.map(({ slug }) => ({ slug })));+ expect(await generateMetadata({ params: Promise.resolve({ slug: "introducing-alook" }) })).toMatchObject({ title: posts[0]!.title, alternates: { canonical: "https://alook.ai/blog/introducing-alook" } });+ expect(await generateMetadata({ params: Promise.resolve({ slug: "missing" }) })).toEqual({});+ await expect(BlogPostPage({ params: Promise.resolve({ slug: "missing" }) })).rejects.toThrow("404");+});++it("settles actual content mounted before the URL only after the independent router commit", async () => {+ const content = render(await BlogPage());+ const route = render(<ObservedRouteCommit />);+ let first!: NonNullable<ReturnType<typeof beginNavigation>>;+ await act(async () => { first = beginNavigation("/blog/introducing-alook")!; });+ await act(async () => { content.rerender(await BlogPostPage({ params: Promise.resolve({ slug: "introducing-alook" }) })); });+ expect(screen.getByRole("heading", { level: 1, name: posts[0]!.title })).toBeVisible();+ expect(ready(first.id)).toHaveLength(0);+ await act(async () => {+ window.history.pushState(null, "", "/blog/introducing-alook");+ route.rerender(<ObservedRouteCommit />);+ });+ expect(forAction(first.id).filter(event => event.name === "navigation.commit")).toHaveLength(1);+ expect(ready(first.id)).toHaveLength(1);+ expect(first.done).toBe(true);++ let second!: NonNullable<ReturnType<typeof beginNavigation>>;+ await act(async () => { second = beginNavigation("/blog/local-ai-agents")!; });+ await act(async () => { content.rerender(await BlogPostPage({ params: Promise.resolve({ slug: "local-ai-agents" }) })); });+ expect(ready(second.id)).toHaveLength(0);+ await act(async () => {+ window.history.pushState(null, "", "/blog/local-ai-agents");+ route.rerender(<ObservedRouteCommit />);+ });+ expect(ready(second.id)).toHaveLength(1);+ expect(forAction(second.id).filter(event => event.name === "action.finish").map(event => event.attributes.outcome)).toEqual(["success"]);+ await act(async () => { commitNavigation(window.location.pathname, "page"); });+ expect(ready(second.id)).toHaveLength(1);+});diff --git a/src/web/blog/src/app/layout.test.ts b/src/web/blog/src/app/layout.test.tsindex 4891e9afc..16a515b90 100644--- a/src/web/blog/src/app/layout.test.ts+++ b/src/web/blog/src/app/layout.test.ts@@ -1,6 +1,8 @@import { createElement } from "react";import { describe, expect, it, vi } from "vitest";+vi.mock("@/lib/observability/regions", () => ({ ObservedRouteCommit: "observed-route-commit" }));+vi.mock("@/components/analytics-consent", () => ({AnalyticsConsent: "analytics-consent",}));@@ -52,6 +54,7 @@ describe("BlogRootLayout", () => {expect(provider.props.children).toEqual([expect.objectContaining({ type: "theme-color-sync" }),child,+ expect.objectContaining({ type: "observed-route-commit" }),expect.objectContaining({ type: "analytics-consent" }),]);});diff --git a/src/web/blog/src/app/layout.tsx b/src/web/blog/src/app/layout.tsxindex 112a8eea0..3b4496cc6 100644--- a/src/web/blog/src/app/layout.tsx+++ b/src/web/blog/src/app/layout.tsx@@ -1,3 +1,4 @@+import { ObservedRouteCommit } from "@/lib/observability/regions";import type { Metadata, Viewport } from "next";import { AnalyticsConsent } from "@/components/analytics-consent";import { caveat, dmMono, dmSans, instrumentSerif, literata, vt323 } from "@/app/fonts";@@ -33,7 +34,8 @@ export default function BlogRootLayout({<ThemeProvider attribute="class" defaultTheme="system" enableSystem><ThemeColorSync />{children}- <AnalyticsConsent />+ <ObservedRouteCommit />+ <AnalyticsConsent /></ThemeProvider></body></html>diff --git a/src/web/blog/src/instrumentation-client.dom.test.tsx b/src/web/blog/src/instrumentation-client.dom.test.tsxnew file mode 100644index 000000000..b854aa94c--- /dev/null+++ b/src/web/blog/src/instrumentation-client.dom.test.tsx@@ -0,0 +1,63 @@+import { afterEach, expect, it, vi } from "vitest";+import { initializeFaro, InternalLoggerLevel, SessionInstrumentation, VolatileSessionsManager } from "@grafana/faro-web-sdk";+import { act, render } from "@/test/react-dom-harness";+import { announceAnalyticsConsent } from "@/lib/analytics-consent";++vi.mock("next/navigation", () => ({ usePathname: () => window.location.pathname, useSearchParams: () => new URLSearchParams(window.location.search) }));++afterEach(async () => {+ await act(async () => {+ document.cookie = "alook_analytics_consent=v1.denied; path=/";+ announceAnalyticsConsent("denied");+ });+ vi.useRealTimers(); vi.unstubAllEnvs(); vi.unstubAllGlobals();+});++it("boots the actual Blog entry with the native resumed session and exports its router transition through the rendered content owner", async () => {+ vi.useFakeTimers();+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public");+ vi.stubEnv("NEXT_PUBLIC_FARO_ENVIRONMENT", "qa");+ vi.stubEnv("NEXT_PUBLIC_FARO_RELEASE", "a".repeat(40));+ Object.defineProperty(performance, "getEntriesByType", { configurable: true, value: () => [] });+ window.history.replaceState(null, "", "/blog");+ document.cookie = "alook_analytics_consent=v1.granted; path=/";+ VolatileSessionsManager.removeUserSession();+ const priorDocument = initializeFaro({+ isolate: true, preventGlobalExposure: true, internalLoggerLevel: InternalLoggerLevel.OFF,+ app: { name: "alook-web" }, transports: [], instrumentations: [new SessionInstrumentation()],+ sessionTracking: { enabled: true, persistent: false, samplingRate: 1, session: { attributes: { alook_account: "anon" } } },+ })!;+ const prior = VolatileSessionsManager.fetchUserSession()!;+ expect(prior.sessionId).toBe(priorDocument.api.getSession()!.id);+ priorDocument.instrumentations.remove(...priorDocument.instrumentations.instrumentations);+ const sent: Array<{ meta: { sdk: { name: string; version: string }; session: { id: string } }; events?: Array<{ name: string; attributes?: Record<string, string> }> }> = [];+ vi.stubGlobal("fetch", vi.fn(async (_url: unknown, options?: RequestInit) => { if (options?.body) sent.push(JSON.parse(String(options.body))); return new Response(null, { status: 204 }); }));+ const { onRouterTransitionStart } = await import("./instrumentation-client");+ const { navigationForHref } = await import("@/lib/observability/context");+ const { ObservedStaticContent, ObservedRouteCommit } = await import("@/lib/observability/regions");+ await vi.waitFor(() => expect(sent.some(body => body.events?.some(event => event.name === "session_resume"))).toBe(true), { timeout: 5000 });+ const view = render(<ObservedStaticContent key="/blog" pathname="/blog" />);+ const route = render(<ObservedRouteCommit />);+ await act(async () => { onRouterTransitionStart("/blog/introducing-alook?private=article-title"); });+ const navigation = navigationForHref("/blog/introducing-alook?private=article-title")!;+ expect(navigation).toBeDefined();+ expect(navigation.done).toBe(false);+ await act(async () => {+ view.rerender(<ObservedStaticContent key="introducing-alook" pathname="/blog/introducing-alook" />);+ });+ expect(navigation.done).toBe(false);+ await act(async () => {+ window.history.pushState(null, "", "/blog/introducing-alook?private=article-title");+ route.rerender(<ObservedRouteCommit />);+ });+ await act(async () => { await vi.advanceTimersByTimeAsync(1500); });+ const exported = sent.flatMap(body => body.events ?? []).filter(event => event.attributes?.action_id === navigation.id);+ expect(exported.map(event => event.name)).toEqual(expect.arrayContaining(["action.start", "navigation.intent", "navigation.commit", "region.read", "region.ready_commit", "action.finish"]));+ expect(exported.filter(event => event.name === "action.finish").map(event => event.attributes?.outcome)).toEqual(["success"]);+ for (const event of exported) expect(event.attributes).toMatchObject({ session_id: prior.sessionId, frontend_surface: "blog", route_template: "/blog/[slug]", navigation_id: navigation.navigationId });+ for (const body of sent) expect(body).toMatchObject({ meta: { sdk: { name: "faro-web", version: "2.12.1" }, session: { id: prior.sessionId } } });+ expect(VolatileSessionsManager.fetchUserSession()).toMatchObject({ sessionId: prior.sessionId, started: prior.started });+ expect(JSON.stringify(sent)).not.toContain("alook_account");+ expect(JSON.stringify(exported)).not.toContain("article-title");+ expect(JSON.stringify(exported)).not.toContain("introducing-alook");+});diff --git a/src/web/blog/src/instrumentation-client.ts b/src/web/blog/src/instrumentation-client.tsnew file mode 100644index 000000000..069fa0381--- /dev/null+++ b/src/web/blog/src/instrumentation-client.ts@@ -0,0 +1,4 @@+import { bootstrapObservability, onObservedRouterTransition } from "@/lib/observability/client"++bootstrapObservability("blog")+export function onRouterTransitionStart(url: string) { onObservedRouterTransition(url) }diff --git a/src/web/package.json b/src/web/package.jsonindex 4b099b695..3a5db4940 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -51,6 +51,8 @@"@dnd-kit/utilities": "^3.2.2","@emoji-mart/data": "^1.2.1","@emoji-mart/react": "^1.1.1",+ "@grafana/faro-web-sdk": "2.12.1",+ "@grafana/faro-web-tracing": "2.12.1","@gsap/react": "^2.1.2","@icons-pack/react-simple-icons": "^13.15.1","@mdx-js/loader": "^3.1.1",@@ -60,6 +62,7 @@"@number-flow/react": "^0.6.2","@opennextjs/cloudflare": "^1.20.6","@openrouter/sdk": "1.4.18",+ "@opentelemetry/api": "1.9.0","@shikijs/core": "4.5.0","@shikijs/engine-oniguruma": "4.5.0","@shikijs/langs": "4.5.0",diff --git a/src/web/src/app/(app)/invite/[token]/page.tsx b/src/web/src/app/(app)/invite/[token]/page.tsxindex 0f8a1044f..52797d553 100644--- a/src/web/src/app/(app)/invite/[token]/page.tsx+++ b/src/web/src/app/(app)/invite/[token]/page.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedQueryRegion } from "@/lib/observability/query-regions";+import { useQuery, useMutation, type Query } from "@tanstack/react-query";import { applicationKey, useApplicationOwner, runApplicationRequest } from "@/lib/application-owner";@@ -21,7 +23,7 @@ export default function InvitePage() {const source = useApplicationViewSource(`workspace-invite:${token}`);const query = useQuery({ queryKey: applicationKey(owner, "workspace-invite", token), enabled: !!token, retry: false,queryFn: ({ signal }) => runApplicationRequest(owner, (options) => getInviteInfo(token, options), signal) });- const command = useMutation({ mutationKey: applicationKey(owner, "workspace-invite", token, "accept"), gcTime: 0,+ const command = useMutation({ meta: { observabilityAction: "workspace.invite.accept" }, mutationKey: applicationKey(owner, "workspace-invite", token, "accept"), gcTime: 0,mutationFn: async ({ original, resources }: { original: ReturnType<typeof source.capture>; resources: Query[] }) => {original.assert();const result = await acceptInvite(token, { authenticationAccount: owner.userId, signal: original.signal, assertActive: original.assert, onUnauthorized: async () => { original.assert(); return false; } });@@ -31,6 +33,7 @@ export default function InvitePage() {return result;} });const info = query.data;+ useObservedQueryRegion("page", query);const error = command.error ?? query.error;const errorMsg = error instanceof Error ? error.message : "Invalid or expired invite link";const state: State = command.isPending ? "accepting" : command.isSuccess ? "done" : error ? "error" : query.isPending ? "loading" : "ready";diff --git a/src/web/src/app/(app)/studio/new/client.tsx b/src/web/src/app/(app)/studio/new/client.tsxindex fce059ffd..b5c0802b2 100644--- a/src/web/src/app/(app)/studio/new/client.tsx+++ b/src/web/src/app/(app)/studio/new/client.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedQueryRegion } from "@/lib/observability/query-regions";+import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useCallback, useEffect, useMemo } from "react";import { useQuery, useMutation } from "@tanstack/react-query";@@ -63,6 +65,7 @@ function StudioOnboardingInner({refetchInterval: 30_000, refetchIntervalInBackground: false,});const runtimes = runtimesQuery.data ?? [];+ useObservedQueryRegion("runtimes", runtimesQuery);const loadingRuntimes = runtimesQuery.isPending;const [scenarioId, setScenarioId] = useAtom(useCreateAtom<ScenarioId | null>(initialTemplate ? initialTemplate.baseScenario : null));const [memberDrafts, setMembers] = useAtom(useCreateAtom<TeamMember[]>([]));@@ -152,7 +155,7 @@ function StudioOnboardingInner({setMembers((previous) => previous.map((member, index) => index === memberIndex ? { ...member, runtimeId } : member));};- const createCommand = useMutation({ gcTime: 0, mutationKey: owner.key("studio-create"), scope: { id: JSON.stringify(owner.key("studio-create")) },+ const createCommand = useMutation({ meta: { observabilityAction: "studio.agent.create" }, gcTime: 0, mutationKey: owner.key("studio-create"), scope: { id: JSON.stringify(owner.key("studio-create")) },mutationFn: async ({ scenario, members, token }: { scenario: ScenarioId; members: TeamMember[]; token: ReturnType<typeof captureWorkspaceOwner> }) => {const assert = () => assertWorkspaceOwner(token);assert();@@ -210,7 +213,7 @@ function StudioOnboardingInner({};- const finishCommand = useMutation({ mutationKey: owner.key("studio-finish"), gcTime: 0,+ const finishCommand = useMutation({ meta: { observabilityAction: "studio.onboarding.finish" }, mutationKey: owner.key("studio-finish"), gcTime: 0,mutationFn: async (intent: ReturnType<typeof source.capture> & { resources: import("@tanstack/react-query").Query[] }) => {intent.assert();await apiFetch(`/api/workspaces/${workspaceId}/onboarded`, { ...workspaceRequestOptions(intent.token, intent.signal, intent.assert), method: "POST" });diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsxindex 7b2477cb3..a6761644f 100644--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedQueryRegion } from "@/lib/observability/query-regions"+import { useEffect, useCallback, useRef, useMemo } from "react";import { useInfiniteQuery, useMutation } from "@tanstack/react-query";import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";@@ -116,7 +118,7 @@ function ActivityRow({ task, slug, agentId, workspaceId, onRetry }: { task: Acticonst owner = useWorkspaceOwner();const source = useWorkspaceViewSource(owner, "activity-retry:" + task.id, true);- const retry = useMutation({+ const retry = useMutation({ meta: { observabilityAction: "agent.task.retry" },mutationKey: owner.key("task-retry", task.id),mutationFn: async (token: ReturnType<typeof captureWorkspaceOwner>) => {const assertActive = () => assertWorkspaceOwner(token);@@ -233,6 +235,7 @@ export default function AgentActivityPage() {});const tasks = useMemo(() => [...new Map((activity.data?.pages.toReversed().flatMap((page) => page.tasks) ?? []).map((task) => [task.id, task])).values()], [activity.data]);const loading = activity.isPending;+ useObservedQueryRegion("activity", activity, tasks.length);const hasMore = activity.hasNextPage;const loadingMore = activity.isFetchingNextPage;const scrollRef = useRef<HTMLDivElement>(null);diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsxindex ccad4488e..5fde32059 100644--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedQueryRegion } from "@/lib/observability/query-regions"+import { useAtom, useCreateAtom } from "@tanstack/react-store";import { FileDownloadButton } from "@/components/file-download-button"import { useEffect, useCallback, useMemo } from "react";@@ -88,6 +90,8 @@ function AgentEmailSurface({ agentId }: { agentId: string }) {const body = bodyQuery.data ?? (bodyQuery.isError ? { content: "(body not available)", isHtml: false } : null);const threadBodies = expandedThreadId && expandedBody.data ? { [expandedThreadId]: expandedBody.data } : {};const loading = list.isPending;+ useObservedQueryRegion("email", list, emails.length);+ useObservedQueryRegion("email_body", bodyQuery, undefined, !!selectedId);const bodyLoading = !!selectedId && bodyQuery.isPending;const switchFolder = useCallback((next: Folder) => {_setFolder(next);@@ -102,7 +106,7 @@ function AgentEmailSurface({ agentId }: { agentId: string }) {};type Input = { action: Action; token: ReturnType<typeof captureWorkspaceOwner> };type Intent = Input & { view: ReturnType<typeof source.capture>; resources: Query[] };- const native = useMutation({ gcTime: 0, mutationKey: commandKey, scope: { id: JSON.stringify(commandKey) },+ const native = useMutation({ meta: { observabilityAction: "email.command" }, gcTime: 0, mutationKey: commandKey, scope: { id: JSON.stringify(commandKey) },mutationFn: async ({ action, token, view, resources }: Intent) => {const assert = () => { assertWorkspaceOwner(token, view.signal); view.assert(); };assert();diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsxindex 439ab4e62..c97b9959b 100644--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/files/page.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedQueryRegion } from "@/lib/observability/query-regions"+import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useCallback } from "react";import { useQuery } from "@tanstack/react-query";@@ -49,6 +51,8 @@ function AgentFilesSurface({ agentId }: { agentId: string }) {const fileQuery = useQuery({ ...workspaceFileOptions(owner, agentId, runtime?.id ?? null, "read", selectedFile ?? "", subscribeWs), enabled: isOnline && !!selectedFile });const rootNodes = (rootQuery.data?.entries ?? []).map((entry) => ({ entry }));const rootLoading = isOnline && rootQuery.isPending;+ useObservedQueryRegion("files", rootQuery, rootNodes.length, isOnline);+ useObservedQueryRegion("file_preview", fileQuery, undefined, isOnline && !!selectedFile);const rootError = rootQuery.error?.message ?? null;const fileContent = fileQuery.data?.content ?? null;const fileBinary = fileQuery.data?.isBinary ?? false;diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/meetings/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/meetings/page.tsxindex cdf8f052c..328c6b9d1 100644--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/meetings/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/meetings/page.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedQueryRegion } from "@/lib/observability/query-regions"+import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useEffect } from "react";import { useParams } from "next/navigation";@@ -54,6 +56,7 @@ function AgentMeetingsView({ agentId }: { agentId: string }) {const resource = useWorkspaceMeetings(agentId);const meetings = resource.data ?? [];const loading = resource.isPending;+ useObservedQueryRegion("meetings", resource);const [createOpen, setCreateOpen] = useAtom(useCreateAtom(false));const [deleteId, setDeleteId] = useAtom(useCreateAtom<string | null>(null));const deleteTarget = meetings.find((meeting) => meeting.id === deleteId);diff --git a/src/web/src/app/(app)/w/[slug]/agents/new/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/new/page.tsxindex 6dbdcd5ee..e66f61d7f 100644--- a/src/web/src/app/(app)/w/[slug]/agents/new/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/new/page.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedQueryRegion } from "@/lib/observability/query-regions";+import { useRef, useCallback, type ComponentProps } from "react";import { useRouter } from "next/navigation";import { useAgentContext } from "@/contexts/agent-context";@@ -36,7 +38,8 @@ export default function CreateAgentPage() {queryFn: ({ signal }) => runApplicationRequest(workspace.application, (options) => fetchModelOptions(options), signal),});const modelOptions = modelQuery.data ?? EMPTY_MODELS;- const create = useMutation({+ useObservedQueryRegion("agents", modelQuery);+ const create = useMutation({ meta: { observabilityAction: "agent.create" },mutationKey: workspace.key("agents", "create-with-email"),mutationFn: async ({ data, token, agentCount }: { data: CreateAgentInput; token: ReturnType<typeof captureWorkspaceOwner>; agentCount: number }) => {assertWorkspaceOwner(token);diff --git a/src/web/src/app/(app)/w/[slug]/calendar/page.tsx b/src/web/src/app/(app)/w/[slug]/calendar/page.tsxindex d66cfdcbc..30459dc73 100644--- a/src/web/src/app/(app)/w/[slug]/calendar/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/calendar/page.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedQueryRegion } from "@/lib/observability/query-regions"+import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useQuery, useMutation, skipToken, type QueryKey } from "@tanstack/react-query";import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";@@ -144,6 +146,7 @@ export default function CalendarPage() {const eventsQuery = useQuery({ queryKey: eventsKey, queryFn: ({ signal }) => listCalendarEvents(workspaceId, range, source.request(signal)) });const events = eventsQuery.data ?? EMPTY_EVENTS;const loading = eventsQuery.isPending;+ useObservedQueryRegion("calendar", eventsQuery, events.length);const detail = useQuery({ queryKey: detailSelection?.key ?? owner.key("calendar", "range", "__none__"), queryFn: detailSelection ? ({ signal, queryKey }) => listCalendarEvents(workspaceId, { from: String(queryKey[6]), to: String(queryKey[7]) }, source.request(signal)) : skipToken, enabled: false,select: (rows: CalendarEvent[]) => rows.find((row) => row.id === detailSelection?.id && (row.occurrence_at ?? null) === detailSelection?.occurrence) ?? null,}).data ?? null;@@ -157,7 +160,7 @@ export default function CalendarPage() {try { source.assertActive(); } catch { return; }if (message.type.startsWith("calendar.")) void owner.queryClient.invalidateQueries({ queryKey: owner.key("calendar") });}), [owner, subscribeWs, source.assertActive, source]);- const calendarMutation = useMutation({ mutationFn: ({ operation }: { operation: () => Promise<unknown>; kind: "create" | "update" | "delete"; id?: string; assertActive: () => void }) => operation() });+ const calendarMutation = useMutation({ meta: { observabilityAction: "calendar.command" }, mutationFn: ({ operation }: { operation: () => Promise<unknown>; kind: "create" | "update" | "delete"; id?: string; assertActive: () => void }) => operation() });const currentMutation = calendarMutation.isPending && calendarMutation.variables.assertActive === source.assertActive;const submitting = currentMutation && calendarMutation.variables.kind === "create";const submittingEdit = currentMutation && calendarMutation.variables.kind === "update";diff --git a/src/web/src/app/(app)/w/[slug]/flags/page.tsx b/src/web/src/app/(app)/w/[slug]/flags/page.tsxindex 2f3e1f500..5345c83ee 100644--- a/src/web/src/app/(app)/w/[slug]/flags/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/flags/page.tsx@@ -1,5 +1,8 @@"use client";+import { useObservedRegion } from "@/lib/observability/regions";+import { viewEvidence } from "@/lib/observability/data-source";+import { useCallback, useRef } from "react";import { useWorkspace } from "@/contexts/workspace-context";import { type FlaggedItem } from "@/lib/api";@@ -103,6 +106,7 @@ export default function FlagsPage() {const { items, isPending: loading, hasNextPage: hasMore, isFetchingNextPage: loadingMore, fetchNextPage } = useWorkspaceFlags();const remove = useUnflagWorkspaceMessage();+ useObservedRegion("inbox", !loading, viewEvidence(items));const scrollRef = useRef<HTMLDivElement>(null);const handleScroll = useCallback(() => {const el = scrollRef.current;diff --git a/src/web/src/app/(app)/w/[slug]/help/email-setup/page.tsx b/src/web/src/app/(app)/w/[slug]/help/email-setup/page.tsxindex 385901e61..cd2903a4b 100644--- a/src/web/src/app/(app)/w/[slug]/help/email-setup/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/help/email-setup/page.tsx@@ -1,4 +1,6 @@"use client";+import { ObservedStaticContent } from "@/lib/observability/regions";+import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";@@ -118,7 +120,7 @@ const PROVIDERS = [export default function EmailSetupHelpPage() {return (- <>+ <><ObservedStaticContent /><><div className="flex items-center justify-between border-b border-border/50 px-3 sm:px-4 py-2 gap-3"><div className="flex items-center gap-3 min-w-0"><h1 className="text-sm font-medium">Email Setup Guide</h1>@@ -170,6 +172,6 @@ export default function EmailSetupHelpPage() {</Tabs></div></div>- </>+ </></>);}diff --git a/src/web/src/app/(app)/w/[slug]/home/page.tsx b/src/web/src/app/(app)/w/[slug]/home/page.tsxindex 655ba9a9e..04de0e322 100644--- a/src/web/src/app/(app)/w/[slug]/home/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/home/page.tsx@@ -1,5 +1,8 @@"use client";+import { useObservedRegion } from "@/lib/observability/regions"+import { viewEvidence, mergeEvidence } from "@/lib/observability/data-source"+import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useCallback, useEffect, useMemo, useRef } from "react";import { useMutation, useQuery } from "@tanstack/react-query";@@ -113,6 +116,7 @@ function AgentCanvas({ onAgentClick }: { onAgentClick?: (agent: Agent) => void }const router = useRouter();const { agents, runtimes, loading, activeTaskCounts, agentLinks, pendingNewAgent, clearPendingNewAgent } = useAgentContext();const owner = useWorkspaceOwner();+ useObservedRegion("agents", !loading, mergeEvidence([viewEvidence(agents), viewEvidence(agentLinks), viewEvidence(runtimes)]));const { slug, workspaceId } = owner;const source = useWorkspaceViewSource(owner, "canvas", true);const { zoomIn, zoomOut, fitView } = useReactFlow();@@ -331,7 +335,7 @@ function AgentCanvas({ onAgentClick }: { onAgentClick?: (agent: Agent) => void }}, [canvasScope, setNodes]);const linkKey = owner.key("agent-links");- const linkCommand = useMutation({ mutationKey: owner.key("agent-link-command"), scope: { id: JSON.stringify(owner.key("agent-link-command")) },+ const linkCommand = useMutation({ meta: { observabilityAction: "agent.link.command" }, mutationKey: owner.key("agent-link-command"), scope: { id: JSON.stringify(owner.key("agent-link-command")) },mutationFn: async ({ action, token }: { action: { kind: "create"; source: string; target: string } | { kind: "update"; id: string; instruction: string } | { kind: "delete"; id: string }; token: ReturnType<typeof captureWorkspaceOwner> }) => {const assert = () => assertWorkspaceOwner(token), qc = owner.queryClient;assert();diff --git a/src/web/src/app/(app)/w/[slug]/issues/page.tsx b/src/web/src/app/(app)/w/[slug]/issues/page.tsxindex 075aad913..93ec262e2 100644--- a/src/web/src/app/(app)/w/[slug]/issues/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/issues/page.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedQueryRegion } from "@/lib/observability/query-regions"+import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useArtifactClick } from "@/components/use-artifact-click";import { useCallback, useEffect, useMemo } from "react";@@ -254,6 +256,8 @@ export default function IssuesPage() {const activeTask = useQuery({ ...workspaceTaskOptions(owner, taskId ?? "__none__"), enabled: sheetOpen && !!taskId }).data ?? null;const traceTasks = useQuery({ ...workspaceTraceOptions(owner, traceId ?? "__none__"), enabled: sheetOpen && !!traceId }).data?.tasks ?? null;const loading = listQuery.isPending;+ useObservedQueryRegion("issues", listQuery, issues.length);+ useObservedQueryRegion("issue_detail", issueQuery, undefined, sheetOpen && !!selectedId);const creating = pending.some((action) => action.kind === "create");const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }));const agentsById = useMemo(() => new Map(agents.map((agent) => [agent.id, agent])), [agents]);diff --git a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsxindex abb6cf907..cdefbc02b 100644--- a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx@@ -1,5 +1,8 @@"use client";+import { useObservedRegion } from "@/lib/observability/regions"+import { viewEvidence } from "@/lib/observability/data-source"+import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useQuery } from "@tanstack/react-query";import { useMemo, useRef, useEffect, useCallback } from "react";@@ -45,6 +48,7 @@ export default function RuntimesPage() {const { runtimes, loading, handleDeleteMachine, subscribeWs, workspaceId } =useAgentContext();const owner = useWorkspaceOwner();+ useObservedRegion("runtimes", !loading, viewEvidence(runtimes));const pageSource = useWorkspaceViewSource(owner, "runtimes", true);const searchParams = useSearchParams();const router = useRouter();diff --git a/src/web/src/app/(app)/w/[slug]/settings/general-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/general-tab.tsxindex 543907b9a..6ff210d63 100644--- a/src/web/src/app/(app)/w/[slug]/settings/general-tab.tsx+++ b/src/web/src/app/(app)/w/[slug]/settings/general-tab.tsx@@ -7,6 +7,8 @@ import { useRouter } from "next/navigation";import { sanitizeSlug } from "@alook/shared";import { useWorkspaceOwner, captureWorkspaceOwner, assertWorkspaceOwner, workspaceRequestOptions } from "@/contexts/workspace-context";import { useWorkspaceViewSource } from "@/hooks/workspace/use-workspace-view-source";+import { useObservedRegion } from "@/lib/observability/regions";+import { mergeEvidence, valueEvidence } from "@/lib/observability/data-source";import { useQuery, useMutation, type Query } from "@tanstack/react-query";import { applicationWorkspacesOptions, workspaceMembersOptions } from "@/hooks/workspace/settings-query-options";@@ -32,6 +34,7 @@ export function GeneralTab() {const current = workspacesQuery.data?.find((workspace) => workspace.id === workspaceId);const memberRole = membersQuery.data?.find((member) => member.user_id === owner.application.userId)?.role ?? "";const loading = membersQuery.isPending || workspacesQuery.isPending;+ useObservedRegion("settings", !loading && !membersQuery.isError && !workspacesQuery.isError, mergeEvidence([valueEvidence(owner.queryClient, membersQuery.data), valueEvidence(owner.queryClient, workspacesQuery.data)]));const [nameDraft, setWorkspaceName] = useAtom(useCreateAtom<string | null>(null));const [slugDraft, setWorkspaceSlug] = useAtom(useCreateAtom<string | null>(null));const workspaceName = nameDraft ?? current?.name ?? "";@@ -41,7 +44,7 @@ export function GeneralTab() {const [workspaceErrors, setWorkspaceErrors] = useAtom(useCreateAtom<WorkspaceFormErrors>({}));const [deleteConfirm, setDeleteConfirm] = useAtom(useCreateAtom(""));type OriginalIntent = { token: ReturnType<typeof captureWorkspaceOwner>; view: ReturnType<typeof source.capture>; resources: Query[] };- const native = useMutation({ mutationKey: owner.key("workspace-settings-command"), scope: { id: JSON.stringify(owner.key("workspace-settings-command")) }, gcTime: 0,+ const native = useMutation({ meta: { observabilityAction: "workspace.settings.command" }, mutationKey: owner.key("workspace-settings-command"), scope: { id: JSON.stringify(owner.key("workspace-settings-command")) }, gcTime: 0,mutationFn: async ({ action, token, view, resources }: { action: { kind: "update"; name: string; slug: string } | { kind: "delete"; name: string }; token: ReturnType<typeof captureWorkspaceOwner> } & OriginalIntent) => {const assert = () => { assertWorkspaceOwner(token, view.signal); view.assert(); };const key = applicationWorkspacesOptions(owner.application).queryKey;diff --git a/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsxindex 15e144eca..b78bea1e6 100644--- a/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx+++ b/src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedQueryRegion } from "@/lib/observability/query-regions"+import { createStore, useSelector } from "@tanstack/react-store";import { useQuery, useMutation, type Query } from "@tanstack/react-query";import { useCallback, useEffect, useMemo, useLayoutEffect } from "react";@@ -48,6 +50,7 @@ export function InstructionTab() {const source = useWorkspaceViewSource(owner, "workspace-instruction", true);const key = owner.key("member-instruction");const query = useQuery({ queryKey: key, queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => getMemberMe(workspaceId, options), signal) });+ useObservedQueryRegion("settings", query);type SaveIntent = { value: string; token: ReturnType<typeof captureWorkspaceOwner>; assertView: () => void; signal: AbortSignal; resource: Query | undefined };const draft = useMemo(() => {const draftKey = JSON.stringify(owner.key("instruction-draft"));@@ -61,7 +64,7 @@ export function InstructionTab() {const edits = useSelector(draft, (state) => state);const value = edits.value ?? query.data?.global_instruction ?? "";const loading = query.isPending;- const command = useMutation({ mutationKey: [...key, "command"], scope: { id: JSON.stringify(key) }, gcTime: 0,+ const command = useMutation({ meta: { observabilityAction: "workspace.instruction.save" }, mutationKey: [...key, "command"], scope: { id: JSON.stringify(key) }, gcTime: 0,mutationFn: async ({ value, token, assertView, signal, resource: original }: SaveIntent) => {const assert = () => { assertWorkspaceOwner(token, signal); assertView(); };assert();diff --git a/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsxindex 7a960a058..52f5c19b2 100644--- a/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx+++ b/src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedQueryRegion } from "@/lib/observability/query-regions"+import { useQuery, useMutation, type Query } from "@tanstack/react-query";import { toast } from "sonner";@@ -28,12 +30,13 @@ export function MembersTab() {const currentUserId = owner.application.userId;const memberQuery = useQuery(workspaceMembersOptions(owner));const members = memberQuery.data ?? [];+ useObservedQueryRegion("settings", memberQuery, members.length);const isOwner = members.find((member) => member.user_id === currentUserId)?.role === "owner";const invitesQuery = useQuery({ ...workspaceInvitesOptions(owner), enabled: isOwner, subscribed: isOwner, gcTime: 0 });const invites = isOwner ? invitesQuery.data ?? [] : [];const loading = memberQuery.isPending || isOwner && invitesQuery.isPending;type OriginalIntent = { token: ReturnType<typeof captureWorkspaceOwner>; view: ReturnType<typeof source.capture>; resources: Query[] };- const native = useMutation({ mutationKey: owner.key("workspace-members-command"), scope: { id: JSON.stringify(owner.key("workspace-members-command")) }, gcTime: 0,+ const native = useMutation({ meta: { observabilityAction: "workspace.members.command" }, mutationKey: owner.key("workspace-members-command"), scope: { id: JSON.stringify(owner.key("workspace-members-command")) }, gcTime: 0,mutationFn: async ({ action, token, view, resources }: { action: { kind: "create-invite" } | { kind: "revoke-invite" | "remove-member"; id: string }; token: ReturnType<typeof captureWorkspaceOwner> } & OriginalIntent) => {const assert = () => { assertWorkspaceOwner(token, view.signal); view.assert(); }, qc = owner.queryClient;const key = action.kind === "remove-member" ? workspaceMembersOptions(owner).queryKey : workspaceInvitesOptions(owner).queryKey;diff --git a/src/web/src/app/(app)/w/[slug]/settings/notification-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/notification-tab.tsxindex 468abe7b3..4ac7e2b38 100644--- a/src/web/src/app/(app)/w/[slug]/settings/notification-tab.tsx+++ b/src/web/src/app/(app)/w/[slug]/settings/notification-tab.tsx@@ -1,4 +1,6 @@"use client";+import { useObservedRegion } from "@/lib/observability/regions";+import { mergeEvidence, sourceEvidence, valueEvidence } from "@/lib/observability/data-source";import { useSelector } from "@tanstack/react-store";import { useQuery, useMutation } from "@tanstack/react-query";@@ -22,7 +24,8 @@ export function NotificationTab() {});const notifSupported = permission.data?.supported ?? true;const notifDenied = permission.data?.denied ?? false;- const command = useMutation({ mutationKey: applicationKey(owner, "browser-notification-permission", "request"),+ useObservedRegion("settings", !permission.isPending, { ...mergeEvidence([sourceEvidence(preferences, "unknown"), valueEvidence(owner.queryClient, permission.data)]), count: 1 });+ const command = useMutation({ meta: { observabilityAction: "notification.permission.request" }, mutationKey: applicationKey(owner, "browser-notification-permission", "request"),mutationFn: async (original: ReturnType<typeof source.capture>) => {original.assert();const granted = await requestNotificationPermission();diff --git a/src/web/src/app/(app)/w/[slug]/settings/pet-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/pet-tab.tsxindex d9f473cd5..3cadca0e8 100644--- a/src/web/src/app/(app)/w/[slug]/settings/pet-tab.tsx+++ b/src/web/src/app/(app)/w/[slug]/settings/pet-tab.tsx@@ -1,4 +1,7 @@"use client";+import { useMemo } from "react";+import { useObservedRegion } from "@/lib/observability/regions";+import { sourceEvidence } from "@/lib/observability/data-source";import { Sparkles } from "lucide-react";@@ -21,6 +24,8 @@ export function PetTab() {const { enabled } = useHomePetSettings();const selectedPresetId = useCloudCodeMonsterPetPresetId();const selectedPreset = getCloudCodeMonsterPreset(selectedPresetId);+ const observedPreferences = useMemo(() => ({ enabled, selectedPresetId }), [enabled, selectedPresetId]);+ useObservedRegion("settings", true, sourceEvidence(observedPreferences, "unknown"));const handleEnabledChange = (checked: boolean) => writeHomePetSettings({ enabled: checked });return (diff --git a/src/web/src/app/(app)/w/[slug]/settings/usages-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/usages-tab.tsxindex 5c446e07d..85547683b 100644--- a/src/web/src/app/(app)/w/[slug]/settings/usages-tab.tsx+++ b/src/web/src/app/(app)/w/[slug]/settings/usages-tab.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedQueryRegion } from "@/lib/observability/query-regions";+import { useQuery } from "@tanstack/react-query";import { useAgentContext } from "@/contexts/agent-context";import { useWorkspaceOwner, runWorkspaceRequest } from "@/contexts/workspace-context";@@ -17,6 +19,7 @@ export function UsagesTab() {const overviewQuery = useQuery({ queryKey: owner.key("overview"), enabled: !loading,queryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => getWorkspaceOverview(owner.workspaceId, options), signal),});+ useObservedQueryRegion("settings", overviewQuery);const overview = overviewQuery.data;const overviewLoading = overviewQuery.isPending;diff --git a/src/web/src/app/(app)/w/[slug]/traces/[traceId]/page.tsx b/src/web/src/app/(app)/w/[slug]/traces/[traceId]/page.tsxindex cc9559cf6..9b0ccd0e2 100644--- a/src/web/src/app/(app)/w/[slug]/traces/[traceId]/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/traces/[traceId]/page.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedQueryRegion } from "@/lib/observability/query-regions"+import { useEffect } from "react";import { useQuery } from "@tanstack/react-query";import { workspaceTraceOptions } from "@/hooks/workspace/issue-query-options";@@ -161,6 +163,7 @@ export default function TraceDetailPage() {const traceId = params.traceId as string;const source = useWorkspaceViewSource(owner, traceId, true);const resource = useQuery(workspaceTraceOptions(owner, traceId));+ useObservedQueryRegion("trace_detail", resource);const tasks = resource.data?.tasks ?? [];const channel = resource.data?.channel ?? "default";const loading = resource.isPending;diff --git a/src/web/src/app/(app)/w/[slug]/traces/page.tsx b/src/web/src/app/(app)/w/[slug]/traces/page.tsxindex 2c46762df..3d3e17e0a 100644--- a/src/web/src/app/(app)/w/[slug]/traces/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/traces/page.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedQueryRegion } from "@/lib/observability/query-regions"+import { useCallback, useRef } from "react";import { useInfiniteQuery } from "@tanstack/react-query";import { useAgentContext } from "@/contexts/agent-context";@@ -167,6 +169,7 @@ export default function TracesPage() {seen.add(trace.trace_id); return true;});const loading = resource.isPending;+ useObservedQueryRegion("traces", resource, traces.length);const hasMore = resource.hasNextPage;const loadingMore = resource.isFetchingNextPage;const loadInitial = async () => {diff --git a/src/web/src/app/(app)/w/[slug]/unread/page.tsx b/src/web/src/app/(app)/w/[slug]/unread/page.tsxindex c27de8aca..b0c216075 100644--- a/src/web/src/app/(app)/w/[slug]/unread/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/unread/page.tsx@@ -1,5 +1,8 @@"use client";+import { useObservedRegion } from "@/lib/observability/regions";+import { viewEvidence } from "@/lib/observability/data-source";+import { useSelector } from "@tanstack/react-store";import { useApplicationOwner } from "@/lib/application-owner";import { useCallback, useRef } from "react";@@ -121,6 +124,7 @@ export default function InboxPage() {const markAll = useMarkAllInboxRead();const application = useApplicationOwner();const filterTypes = useSelector(application.preferences, (state) => state.inboxFilterTypes);+ useObservedRegion("inbox", !loading, viewEvidence(items));const scrollRef = useRef<HTMLDivElement>(null);const handleScroll = useCallback(() => {const el = scrollRef.current;diff --git a/src/web/src/app/(app)/workspaces/client.tsx b/src/web/src/app/(app)/workspaces/client.tsxindex 2b626f116..919747374 100644--- a/src/web/src/app/(app)/workspaces/client.tsx+++ b/src/web/src/app/(app)/workspaces/client.tsx@@ -1,5 +1,7 @@"use client"+import { useObservedQueryRegion } from "@/lib/observability/query-regions"+import { useMutation, useQuery, type Query } from "@tanstack/react-query"import type { Workspace } from "@alook/shared"import { applicationWorkspacesOptions } from "@/hooks/workspace/settings-query-options"@@ -26,9 +28,10 @@ export function WorkspaceListClient({const source = useApplicationViewSource("workspace-list")const options = applicationWorkspacesOptions(applicationOwner)const resource = useQuery({ ...options, initialData: initialWorkspaces, initialDataUpdatedAt: 0 })+ useObservedQueryRegion("workspaces", resource)const workspaces = resource.datatype Intent = { original: ReturnType<typeof source.capture>; resource: Query | undefined }- const command = useMutation({ mutationKey: [...options.queryKey, "create"], gcTime: 0,+ const command = useMutation({ meta: { observabilityAction: "workspace.create" }, mutationKey: [...options.queryKey, "create"], gcTime: 0,mutationFn: async ({ original, resource }: Intent) => {original.assert()const current = () => resource && applicationOwner.queryClient.getQueryCache().find({ queryKey: options.queryKey, exact: true }) === resourcediff --git a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx b/src/web/src/app/(auth)/sign-in/sign-in-client.tsxindex 744a3f06a..d77301059 100644--- a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.tsx@@ -1,5 +1,7 @@"use client"+import { startAction, finishAction } from "@/lib/observability/context"+import { ObservedStaticContent } from "@/lib/observability/regions"import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useEffect } from "react"import { useSearchParams } from "next/navigation"@@ -79,6 +81,7 @@ function SignInForm({async function handleSendCode(e: React.FormEvent) {e.preventDefault()if (retryAfter != null) return+ const observation = startAction("auth_send_code")setEmailError("")setRetryAfter(null)setLoading(true)@@ -88,6 +91,7 @@ function SignInForm({type: "sign-in",fetchOptions: rateLimitHandler,})+ finishAction(observation, error ? "error" : "success")if (error) {if (error.status !== 429) setEmailError(error.message ?? "Failed to send code")} else {@@ -96,6 +100,7 @@ function SignInForm({setStep("code")}} catch {+ finishAction(observation, "error")setEmailError("Failed to send code")}setLoading(false)@@ -105,6 +110,7 @@ function SignInForm({setCode(value)setOtpError("")if (value.length !== 6) return+ const observation = startAction("auth_verify_code")setLoading(true)try {@@ -112,6 +118,7 @@ function SignInForm({email,otp: value,})+ finishAction(observation, error ? "error" : "success")if (error) {setOtpError(error.message ?? "Invalid code")setCode("")@@ -121,6 +128,7 @@ function SignInForm({return}} catch {+ finishAction(observation, "error")setOtpError("Invalid code")setCode("")}@@ -129,6 +137,7 @@ function SignInForm({async function handleDevSignIn(e: React.FormEvent) {e.preventDefault()+ const observation = startAction("auth_dev_sign_in")setEmailError("")setLoading(true)const { error: signInErr } = await signIn.email(@@ -141,11 +150,13 @@ function SignInForm({{ onError: () => {} },)if (signUpErr) {+ finishAction(observation, "error")setEmailError(signUpErr.message ?? "Failed to sign in")setLoading(false)return}}+ finishAction(observation, "success")window.location.href = postLoginUrl}@@ -167,6 +178,7 @@ function SignInForm({return (<FieldGroup>+ <ObservedStaticContent />{accountDeleted ? (<divclassName="flex gap-3 rounded-xl bg-muted/70 p-4 text-left"diff --git a/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts b/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.tsindex 6f47e0a47..20309e232 100644--- a/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts+++ b/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts@@ -46,6 +46,7 @@ beforeEach(() => {mocks.tauri = falsemocks.emit = undefinedvi.clearAllMocks()+ mocks.social.mockResolvedValue({ error: null })})function button(id: string): HTMLButtonElement {diff --git a/src/web/src/app/(auth)/sign-in/social-sign-in.tsx b/src/web/src/app/(auth)/sign-in/social-sign-in.tsxindex e00af49ca..3a264ec38 100644--- a/src/web/src/app/(auth)/sign-in/social-sign-in.tsx+++ b/src/web/src/app/(auth)/sign-in/social-sign-in.tsx@@ -1,5 +1,6 @@"use client"+import { startAction, finishAction, type Action } from "@/lib/observability/context"import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useEffect, useRef } from "react"@@ -32,19 +33,26 @@ export function SocialSignIn({postLoginUrl: stringappleEnabled?: boolean}) {+ const observed = useRef<Action | undefined>(undefined)const controller = useRef<ReturnType<typeof createNativeOauthController> | null>(null)const [native, setNative] = useAtom(useCreateAtom<NativeOauthView | null>(null))const lastProvider = useRef<NativeOauthProvider>("github")useEffect(() => {if (!isTauri()) return- const instance = createNativeOauthController(nativeOauthBrowserDeps, setNative)+ const instance = createNativeOauthController(nativeOauthBrowserDeps, view => {+ setNative(view)+ if (["waiting", "error", "unsupported", "idle"].includes(view.phase)) finishAction(observed.current, view.phase === "error" ? "error" : view.phase === "idle" ? "cancelled" : "observed")+ })controller.current = instancevoid instance.connect()return () => { instance.dispose(); if (controller.current === instance) controller.current = null }}, [setNative])const begin = (provider: NativeOauthProvider) => {+ finishAction(observed.current, "superseded")+ observed.current = startAction("auth_social", { capability: "limited", phase: "auth" })lastProvider.current = provider- if (!isTauri()) { void signIn.social({ provider, callbackURL: postLoginUrl }); return }+ const action = observed.current+ if (!isTauri()) { void signIn.social({ provider, callbackURL: postLoginUrl }).then(result => finishAction(action, result.error ? "error" : "observed"), () => finishAction(action, "error")); return }if (controller.current) void controller.current.start(provider, safeRedirectPath(postLoginUrl))}const busy = native?.phase === "initializing" || native?.phase === "preparing" || native?.phase === "exchanging" || native?.phase === "checking_status"diff --git a/src/web/src/app/(home)/page.tsx b/src/web/src/app/(home)/page.tsxindex 7f443bcdd..58b377b99 100644--- a/src/web/src/app/(home)/page.tsx+++ b/src/web/src/app/(home)/page.tsx@@ -1,3 +1,4 @@+import { ObservedStaticContent } from "@/lib/observability/regions";import type { Metadata } from "next";import {LANDING_META_DESCRIPTION,@@ -29,5 +30,5 @@ export const metadata: Metadata = {export default async function Page() {const session = await getSession();- return <LandingPage isLoggedIn={!!session} />;+ return <><ObservedStaticContent /><LandingPage isLoggedIn={!!session} /></>;}diff --git a/src/web/src/app/c/QueryProvider.observability.dom.test.tsx b/src/web/src/app/c/QueryProvider.observability.dom.test.tsxnew file mode 100644index 000000000..a0a95669a--- /dev/null+++ b/src/web/src/app/c/QueryProvider.observability.dom.test.tsx@@ -0,0 +1,134 @@+import "fake-indexeddb/auto"+import { useLayoutEffect } from "react"+import { dehydrate, QueryClient, useIsRestoring, useQueryClient } from "@tanstack/react-query"+import { afterEach, beforeEach, expect, it, vi } from "vitest"+import { act, render, waitFor } from "@/test/react-dom-harness"+import { clearAllPersistedCaches, createIdbPersister, PERSIST_BUSTER } from "@/lib/query-persister"+import { communityKeys } from "@/lib/query-keys"+import { valueEvidence } from "@/lib/observability/data-source"+import { setTelemetryUser } from "@/lib/observability/client"+import { configureTelemetry, installTelemetrySink, retireTelemetry } from "@/lib/observability/telemetry"+import { getCommunityDbRegistry } from "@/lib/community-db/collections"+import { QueryProvider } from "./QueryProvider"++const identity = vi.hoisted(() => ({ id: "account-a" }))+vi.mock("@/lib/auth-client", () => ({ useSession: () => ({ data: { user: { id: identity.id } }, isPending: false, error: null }), currentSessionViewer: () => identity.id }))+vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))+vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))+const clients = new Map<string, QueryClient>()+const restoring = new Map<string, boolean>()+const events: Array<{ name: string; attributes: Record<string, string> }> = []+let mounted: ReturnType<typeof render> | undefined+const key = (id: string) => communityKeys.communityDbCollection(id, "profiles")+function Probe({ id }: { id: string }) {+ const client = useQueryClient(), pending = useIsRestoring()+ useLayoutEffect(() => { clients.set(id, client); restoring.set(id, pending) }, [id, client, pending])+ return <p>{id}</p>+}+function App({ id }: { id: string }) { return <QueryProvider userId={id}><Probe id={id} /></QueryProvider> }+function activate(id: string) {+ setTelemetryUser(id)+ configureTelemetry({ session_id: "session-" + id }, true)+ installTelemetrySink(event => events.push(event))+}+async function seed(id: string) {+ const client = new QueryClient()+ client.setQueryData(key(id), [{ userId: id, name: "Private " + id, discriminator: "0001", avatar: "A", avatarVersion: 0 }], { updatedAt: Date.now() - 1000 })+ await createIdbPersister(id).persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(client) })+ client.clear()+}+function holdRead(id: string) {+ const original = IDBObjectStore.prototype.get+ let release: (() => void) | undefined+ let held = false+ vi.spyOn(IDBObjectStore.prototype, "get").mockImplementation(function (this: IDBObjectStore, requestKey: IDBValidKey | IDBKeyRange) {+ const request = original.call(this, requestKey)+ if (requestKey === `alook:qc:v3:${id}:client` && !held) {+ held = true+ let success: IDBRequest["onsuccess"] = null+ Object.defineProperty(request, "onsuccess", {+ configurable: true,+ get: () => (event: Event) => { release = () => success?.call(request, event) },+ set: (handler: IDBRequest["onsuccess"]) => { success = handler },+ })+ }+ return request+ })+ return { pending: () => typeof release === "function", release: () => { expect(release).toBeTypeOf("function"); release!() } }+}+beforeEach(async () => {+ identity.id = "account-a"; clients.clear(); restoring.clear(); events.length = 0+ document.cookie = "alook_analytics_consent=v1.denied; path=/"+ retireTelemetry()+ await clearAllPersistedCaches()+ await seed("account-a"); await seed("account-b")+ activate("account-a")+})+afterEach(async () => {+ await act(async () => {+ mounted?.unmount(); mounted = undefined+ await new Promise(resolve => setTimeout(resolve, 0))+ for (const client of clients.values()) { await getCommunityDbRegistry(client)?.cleanup(); client.clear() }+ retireTelemetry()+ })+ vi.restoreAllMocks()+})++it("attributes a delayed real IDB snapshot only after the actual Provider hydrates it", async () => {+ const read = holdRead("account-a")+ mounted = render(<App id="account-a" />)+ await waitFor(() => expect(read.pending()).toBe(true))+ const client = clients.get("account-a")!+ expect(restoring.get("account-a")).toBe(true)+ expect(client.getQueryData(key("account-a"))).toBeUndefined()+ expect(events.some(event => event.name === "cache.restore.finish" && event.attributes.phase === "hydrate")).toBe(false)+ await act(async () => read.release())+ await waitFor(() => expect(restoring.get("account-a")).toBe(false))+ expect(client.getQueryData(key("account-a"))).toEqual([expect.objectContaining({ userId: "account-a" })])+ expect(valueEvidence(client, client.getQueryData(key("account-a"))).source).toBe("restored_idb")+ expect(events.filter(event => event.name === "cache.restore.finish").map(event => [event.attributes.phase, event.attributes.outcome])).toEqual([["idb_read", "hit"], ["deserialize", "hit"], ["hydrate", "success"]])+ expect(JSON.stringify(events)).not.toContain("Private")+})++it("the actual retired Provider's delayed IDB callback cannot tag or report into the replacement account", async () => {+ const read = holdRead("account-a")+ mounted = render(<App id="account-a" />)+ await waitFor(() => expect(read.pending()).toBe(true))+ const original = clients.get("account-a")!+ identity.id = "account-b"+ await act(async () => { activate("account-b"); mounted!.rerender(<App id="account-b" />) })+ await waitFor(() => expect(restoring.get("account-b")).toBe(false))+ const replacement = clients.get("account-b")!+ expect(replacement).not.toBe(original)+ const replacementData = replacement.getQueryData(key("account-b"))+ expect(valueEvidence(replacement, replacementData).source).toBe("restored_idb")+ const prior = events.filter(event => event.name.startsWith("cache.restore."))+ const builds = vi.spyOn(original.getQueryCache(), "build")+ const clears = vi.spyOn(original, "clear")+ await act(async () => read.release())+ await waitFor(() => expect(builds).toHaveBeenCalledWith(original, expect.objectContaining({ queryKey: key("account-a") }), expect.any(Object)))+ await waitFor(() => expect(clears).toHaveBeenCalled())+ await waitFor(() => expect(original.getQueryCache().getAll()).toHaveLength(0))+ expect(events.filter(event => event.name.startsWith("cache.restore."))).toEqual(prior)+ expect(replacement.getQueryData(key("account-b"))).toBe(replacementData)+ expect(replacement.getQueryData(key("account-a"))).toBeUndefined()+ expect(valueEvidence(replacement, replacementData).source).toBe("restored_idb")+})++it("regrant during a real Provider restore preserves business hydration without borrowing old telemetry admission", async () => {+ const read = holdRead("account-a")+ mounted = render(<App id="account-a" />)+ await waitFor(() => expect(read.pending()).toBe(true))+ const client = clients.get("account-a")!+ await act(async () => {+ retireTelemetry()+ configureTelemetry({ session_id: "session-regranted" }, true)+ installTelemetrySink(event => events.push(event))+ })+ events.length = 0+ await act(async () => read.release())+ await waitFor(() => expect(restoring.get("account-a")).toBe(false))+ expect(client.getQueryData(key("account-a"))).toEqual([expect.objectContaining({ userId: "account-a" })])+ expect(valueEvidence(client, client.getQueryData(key("account-a"))).source).toBe("unknown")+ expect(events.filter(event => event.name.startsWith("cache.restore."))).toEqual([])+})diff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsxindex cc6035aa3..19512959a 100644--- a/src/web/src/app/c/QueryProvider.tsx+++ b/src/web/src/app/c/QueryProvider.tsx@@ -36,6 +36,8 @@ import { CommunityDbProvider } from "@/lib/community-db/projections"import { installCommunityDbSync } from "@/lib/community-db/sync"import { profileSchema } from "@/lib/community-db/schema"import type { CurrentUser } from "@/contexts/community/current-user"+import { observeHydration, discardHydration } from "@/lib/observability/restore"+import { captureTelemetryIdentityRetirement, setTelemetryUser } from "@/lib/observability/client"function createRestoreGate() {let release!: () => void@@ -168,6 +170,8 @@ function ScopedQueryProvider({const active = useSelector(communityDb.runtime.lifecycle, (state) => state.active)const router = useRouter()useLayoutEffect(() => { communityDb.bindAuthentication(sessionViewer, persister.retireAccount) }, [communityDb, sessionViewer, persister])+ const retireTelemetryIdentity = useRef<() => void>(() => undefined)+ useLayoutEffect(() => { setTelemetryUser(userId); retireTelemetryIdentity.current = captureTelemetryIdentityRetirement() }, [userId])const identityRetired = useRef(false)const identityChanged = !session.isPending && !session.error && session.data?.user.id !== userIduseLayoutEffect(() => {@@ -183,14 +187,16 @@ function ScopedQueryProvider({}}, [communityDb, restoreGate])useLayoutEffect(() => {- if (!identityChanged || identityRetired.current) return+ if (!identityChanged) return+ if (!session.data?.user.id && sessionViewer?.() === null) retireTelemetryIdentity.current()+ if (identityRetired.current) returnidentityRetired.current = truerestoreGate.release()retireCommunityAccount(communityDb)void communityDb.retireDisk().catch(() => undefined)if (session.data?.user.id) router.refresh()else router.replace("/sign-in")- }, [communityDb, identityChanged, restoreGate, router, session.data?.user.id, userId])+ }, [communityDb, identityChanged, restoreGate, router, session.data?.user.id, sessionViewer, userId])const onRetired = useCallback(() => {if (!communityDb.runtime.lifecycle.get().active) returnretireCommunityAccount(communityDb)@@ -212,6 +218,8 @@ function ScopedQueryProvider({<PersistQueryClientProviderclient={queryClient}onSuccess={() => {+ if (communityDb.runtime.lifecycle.get().active) observeHydration(persister, queryClient)+ else discardHydration(persister)// `onSuccess` runs after hydrate and before `isRestoring` becomes// false. Freeze which canonical collections came from that restore so// later network results can never be misclassified as persisted.@@ -242,7 +250,7 @@ function ScopedQueryProvider({// A failed IndexedDB read still completes the identity handoff. The// account gate remains visible until this atomically clears any previous// viewer state, then the new account mounts against an empty live cache.- onError={settleRestoredAccount}+ onError={() => { discardHydration(persister); settleRestoredAccount() }}persistOptions={{persister,maxAge: PERSIST_MAX_AGE_MS,diff --git a/src/web/src/app/c/invite/[token]/invite-accept-client.tsx b/src/web/src/app/c/invite/[token]/invite-accept-client.tsxindex 647b0baac..67f9eb019 100644--- a/src/web/src/app/c/invite/[token]/invite-accept-client.tsx+++ b/src/web/src/app/c/invite/[token]/invite-accept-client.tsx@@ -1,5 +1,6 @@"use client"+import { useObservedQueryRegion } from "@/lib/observability/query-regions"import { createStore } from "@tanstack/react-store";import { useCallback, useEffect, useMemo } from "react"import { useQuery, useMutation } from "@tanstack/react-query"@@ -52,10 +53,11 @@ function InviteAcceptInner({ token }: { token: string }) {...options, onUnauthorized: async () => { options.assertActive?.(); return false },}), signal),})+ useObservedQueryRegion("page", query)const info = query.dataconst loading = query.isPendingconst error = query.error ? { message: query.error instanceof Error ? query.error.message : "This invite is no longer valid", dead: isDeadInvite(query.error) } : null- const command = useMutation({ mutationKey: applicationKey(owner, "community-invite", token, "join"),+ const command = useMutation({ meta: { observabilityAction: "server.invite.accept" }, mutationKey: applicationKey(owner, "community-invite", token, "join"),scope: { id: JSON.stringify(applicationKey(owner, "community-invite", token, "join")) },mutationFn: async (original: ReturnType<typeof source.capture>) => {original.assert()diff --git a/src/web/src/app/device/page.tsx b/src/web/src/app/device/page.tsxindex 798f93baf..0e98d627c 100644--- a/src/web/src/app/device/page.tsx+++ b/src/web/src/app/device/page.tsx@@ -1,5 +1,6 @@"use client"+import { useObservedRegion } from "@/lib/observability/regions"import { useAtom, useCreateAtom } from "@tanstack/react-store";import { Suspense, useEffect } from "react"import { useQuery, useMutation } from "@tanstack/react-query"@@ -47,7 +48,7 @@ function DeviceAuthPageInner() {} catch (error) { assertApplicationOwner(token, signal); throw error }},})- const command = useMutation({+ const command = useMutation({ meta: { observabilityAction: "device.authorization.command" },mutationKey: applicationKey(owner, "device-decision"),scope: { id: JSON.stringify(applicationKey(owner, "device-decision")) },mutationFn: async ({ kind, code, original }: { kind: "approve" | "deny"; code: string; original: ReturnType<typeof source.capture> }) => {@@ -68,6 +69,7 @@ function DeviceAuthPageInner() {const step: Step = currentDecision?.isSuccess ? currentDecision.data === "approve" ? "done" : "denied": verification.isFetching ? "loading" : verification.isSuccess ? "approve" : "code"+ useObservedRegion("page", !isPending && !!session && step !== "loading", { source: "unknown", version: step, freshness: "unknown", count: 1 })useEffect(() => {if (!isPending && !session) {const original = source.capture()diff --git a/src/web/src/app/landing-legacy/page.tsx b/src/web/src/app/landing-legacy/page.tsxindex 0303540b3..6d8478870 100644--- a/src/web/src/app/landing-legacy/page.tsx+++ b/src/web/src/app/landing-legacy/page.tsx@@ -1,3 +1,4 @@+import { ObservedStaticContent } from "@/lib/observability/regions";import type { Metadata } from "next";import dynamic from "next/dynamic";import { getSession } from "@/lib/session";@@ -18,5 +19,5 @@ export const metadata: Metadata = {export default async function Page() {const session = await getSession();- return <HomePage isLoggedIn={!!session} />;+ return <><ObservedStaticContent /><HomePage isLoggedIn={!!session} /></>;}diff --git a/src/web/src/app/layout.tsx b/src/web/src/app/layout.tsxindex 34a791622..95b275287 100644--- a/src/web/src/app/layout.tsx+++ b/src/web/src/app/layout.tsx@@ -1,3 +1,4 @@+import { ObservedRouteCommit } from "@/lib/observability/regions";import type { Metadata, Viewport } from "next";import { AnalyticsConsent } from "@/components/analytics-consent";import { ThemeProvider } from "@/components/theme-provider";@@ -53,7 +54,8 @@ export default function RootLayout({{children}</TooltipProvider><ToasterProvider />- <AnalyticsConsent />+ <ObservedRouteCommit />+ <AnalyticsConsent /></ThemeProvider></body></html>diff --git a/src/web/src/app/pricing/pricing-client.tsx b/src/web/src/app/pricing/pricing-client.tsxindex 9867beb8d..ab22e935a 100644--- a/src/web/src/app/pricing/pricing-client.tsx+++ b/src/web/src/app/pricing/pricing-client.tsx@@ -1,5 +1,8 @@"use client"+import { useObservedRegion } from "@/lib/observability/regions"+import { valueEvidence, mergeEvidence } from "@/lib/observability/data-source"+import { useEffect, useRef, type MutableRefObject } from "react"import { useRouter, useSearchParams } from "next/navigation"import { useQuery } from "@tanstack/react-query"@@ -37,6 +40,7 @@ function PricingContent({ signedIn, sessionPending, sessionError, viewTrackedRefconst offer = (plan: string) => paymentOffer(plan) ?? catalog.data?.offers.find((item) => item.plan.id === plan)const selected = offer(search.get("plan") ?? "")const busy = sessionPending || billing.isBusy || catalog.isPending || (signedIn && billing.isPending)+ useObservedRegion("billing", !busy && !catalog.isError && !sessionError, { ...mergeEvidence([valueEvidence(owner.queryClient, catalog.data), valueEvidence(owner.queryClient, billing.data)]), count: 1 })const unavailable = sessionError || catalog.isError || (signedIn && billing.isError)const disabled = (plan: string) => busy || unavailable || (plan !== "free" && (!offer(plan) || (signedIn && !paymentOffer(plan)) || (!summary?.isFounder && summary?.plan.id === plan) || summary?.subscription?.scheduledChange?.plan.id === plandiff --git a/src/web/src/app/privacy/page.tsx b/src/web/src/app/privacy/page.tsxindex 85cc04625..11df1eb54 100644--- a/src/web/src/app/privacy/page.tsx+++ b/src/web/src/app/privacy/page.tsx@@ -1,3 +1,4 @@+import { ObservedStaticContent } from "@/lib/observability/regions";import type { Metadata } from "next"import {PRIVACY_POLICY,@@ -22,11 +23,11 @@ export const metadata: Metadata = {export default function PrivacyPage() {return (- <main className="mx-auto max-w-3xl px-6 pt-12 pb-28 sm:pt-24">+ <><ObservedStaticContent /><main className="mx-auto max-w-3xl px-6 pt-12 pb-28 sm:pt-24"><h1 className="mb-4 text-4xl font-semibold tracking-tight sm:text-5xl">{PRIVACY_POLICY.title}</h1><PrivacyPolicyContent />- </main>+ </main></>)}diff --git a/src/web/src/app/templates/[id]/page.tsx b/src/web/src/app/templates/[id]/page.tsxindex 573d4194c..3ef11f935 100644--- a/src/web/src/app/templates/[id]/page.tsx+++ b/src/web/src/app/templates/[id]/page.tsx@@ -1,3 +1,4 @@+import { ObservedStaticContent } from "@/lib/observability/regions";import type { Metadata } from "next";import { notFound } from "next/navigation";import { getSession } from "@/lib/session";@@ -78,7 +79,7 @@ export default async function TemplateDetailPage({];return (- <>+ <><ObservedStaticContent /><><scripttype="application/ld+json"dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}@@ -88,6 +89,6 @@ export default async function TemplateDetailPage({isLoggedIn={!!session}workspaceId={sp.workspace_id}/>- </>+ </></>);}diff --git a/src/web/src/app/templates/page.tsx b/src/web/src/app/templates/page.tsxindex c8276619e..7e886703d 100644--- a/src/web/src/app/templates/page.tsx+++ b/src/web/src/app/templates/page.tsx@@ -1,3 +1,4 @@+import { ObservedStaticContent } from "@/lib/observability/regions";import type { Metadata } from "next";import { getSession } from "@/lib/session";import { TEMPLATES, TEMPLATE_CATEGORIES } from "@/lib/templates";@@ -45,7 +46,7 @@ export default async function TemplatesPage({const session = await getSession();const params = await searchParams;return (- <>+ <><ObservedStaticContent /><><scripttype="application/ld+json"dangerouslySetInnerHTML={{ __html: JSON.stringify(itemListJsonLd) }}@@ -56,6 +57,6 @@ export default async function TemplatesPage({isLoggedIn={!!session}workspaceId={params.workspace_id}/>- </>+ </></>);}diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsxindex 291a9b6be..1fee65682 100644--- a/src/web/src/components/agent-chat/agent-chat-view.tsx+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx@@ -1,5 +1,7 @@"use client";+import { useObservedRegion } from "@/lib/observability/regions";+import { viewEvidence } from "@/lib/observability/data-source";import { useArtifactClick } from "@/components/use-artifact-click";import { useMutation, useIsMutating } from "@tanstack/react-query";import { captureQueryReceipt, isQueryReceiptCurrent, type QueryReceipt } from "@/lib/query-receipt";@@ -275,7 +277,7 @@ export function AgentChatView({const chatActionKey = useMemo(() => workspaceOwner.key("chat", "action", crypto.randomUUID()), [workspaceOwner]);type ChatAction = { original: ReturnType<typeof captureChatIntent>; conversationId: string; resources: Map<string, QueryReceipt> } & ({ kind: "thread"; messageId: string } | { kind: "stop" });- const chatAction = useMutation({ mutationKey: chatActionKey, gcTime: 0, scope: { id: JSON.stringify(chatActionKey) },+ const chatAction = useMutation({ meta: { observabilityAction: "chat.control.command" }, mutationKey: chatActionKey, gcTime: 0, scope: { id: JSON.stringify(chatActionKey) },mutationFn: async (action: ChatAction) => {assertChatIntent(action.original);return runChatIntentRequest(action.original, async (options) => {@@ -480,6 +482,7 @@ export function AgentChatView({isTaskActive,});+ useObservedRegion("chat", !messagesLoading, viewEvidence(messages));if (messagesLoading) {return (<>diff --git a/src/web/src/components/agent-edit-form.tsx b/src/web/src/components/agent-edit-form.tsxindex aca166579..44175135b 100644--- a/src/web/src/components/agent-edit-form.tsx+++ b/src/web/src/components/agent-edit-form.tsx@@ -186,7 +186,7 @@ export function AgentEditForm({return { id: fresh.id };},});- const instructionMutation = useMutation({+ const instructionMutation = useMutation({ meta: { observabilityAction: "agent.instruction.save" },mutationKey: owner.key("agent-instruction-command", agent.id),scope: { id: JSON.stringify(owner.key("agent-instruction-command", agent.id)) }, gcTime: 0,mutationFn: async ({ value, token, assertView, signal, resource: original }: InstructionIntent) => {diff --git a/src/web/src/components/community/bots/bot-list-controller.ts b/src/web/src/components/community/bots/bot-list-controller.tsindex df1bbe9cb..48da94bd9 100644--- a/src/web/src/components/community/bots/bot-list-controller.ts+++ b/src/web/src/components/community/bots/bot-list-controller.ts@@ -1,4 +1,6 @@"use client"+import { useObservedRegion } from "@/lib/observability/regions"+import { mergeEvidence, viewEvidence } from "@/lib/observability/data-source"import { useCommunityRuntime } from "@/stores/community/runtime"import { createStore, useSelector, useAtom, useCreateAtom } from "@tanstack/react-store";@@ -55,6 +57,7 @@ export function useBotListController(): BotListController {window.history.pushState(null, "", `${next.pathname}${next.search}${next.hash}`)}const { machines, isLoading: machinesLoading } = useMachines()+ useObservedRegion("bots", botsResolved && (!(isLoading || machinesLoading) || bots.length > 0), { ...mergeEvidence([viewEvidence(bots), viewEvidence(machines)]), count: bots.length })const profilesByUserId = useCanonicalProfilesByUserId(bots.map((bot) => bot.id))const [createOpen, setCreateOpen] = useAtom(useCreateAtom(false))const [editingBotId, setEditingBotId] = useAtom(useCreateAtom<string | null>(null))diff --git a/src/web/src/components/community/channels/channel-sidebar-tree-owner.tsx b/src/web/src/components/community/channels/channel-sidebar-tree-owner.tsxindex 4abefff58..29a629c96 100644--- a/src/web/src/components/community/channels/channel-sidebar-tree-owner.tsx+++ b/src/web/src/components/community/channels/channel-sidebar-tree-owner.tsx@@ -1,5 +1,7 @@"use client"+import { useObservedRegion } from "@/lib/observability/regions"+import { viewEvidence } from "@/lib/observability/data-source"import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useEffect } from "react"@@ -100,6 +102,7 @@ export function ChannelSidebarTreeOwner({...sidebarProps}: ChannelSidebarTreeOwnerProps) {const tree = useChannelTree(categories)+ useObservedRegion("sidebar", true, viewEvidence(categories))return (<divdiff --git a/src/web/src/components/community/channels/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsxindex 89d950d82..46cac45b8 100644--- a/src/web/src/components/community/channels/forum-view.tsx+++ b/src/web/src/components/community/channels/forum-view.tsx@@ -1,5 +1,7 @@"use client"+import { useObservedRegion, windowEvidence } from "@/lib/observability/regions"+import { visibleVirtualItems } from "@/lib/observability/virtual-window"import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useCallback, useLayoutEffect, useRef } from "react"import { useVirtualizer } from "@tanstack/react-virtual"@@ -244,6 +246,8 @@ export function ForumView({overscan: 5,initialRect: { width: 0, height: 800 },})+ const observedPosts = visibleVirtualItems(virtualizer).flatMap(item => posts[item.index] ? [posts[item.index]] : [])+ useObservedRegion("forum", (!loading || posts.length > 0) && (!posts.length || observedPosts.length > 0), windowEvidence(observedPosts, posts))const filterTags = availableTags.length > 0? availableTags: [...new Set(posts.flatMap((post) => post.tags))]diff --git a/src/web/src/components/community/machines/machine-list.tsx b/src/web/src/components/community/machines/machine-list.tsxindex 0eb38c1ae..91e56d633 100644--- a/src/web/src/components/community/machines/machine-list.tsx+++ b/src/web/src/components/community/machines/machine-list.tsx@@ -35,6 +35,8 @@ import { machineName } from "@/lib/community/machine-name"import { MachineCard, MachineCardFrame } from "./machine-card"import { PairMachineSheet, type PairMachineSheetMode } from "./pair-machine-sheet"import { ConnectTile } from "@/components/community/onboarding-tiles/connect-tile"+import { useObservedRegion } from "@/lib/observability/regions"+import { viewEvidence } from "@/lib/observability/data-source"import { useMachines, machinesQueryFn, replaceMachines, type MachinesResponse } from "@/hooks/community/use-machines"import { useBots } from "@/hooks/community/use-bots"import { usePendingMachineTokenId } from "@/stores/community"@@ -214,6 +216,7 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {const origin = useCommunityMutationOrigin()const source = useCommunityViewSource("machine-list")const { machines, data: machinesData, isLoading: machinesLoading } = useMachines()+ useObservedRegion("machines", machinesData !== undefined && !machinesLoading, viewEvidence(machines))const capacity = machinesData?.machineCapacity ?? nullconst [limitOpen, setLimitOpen] = useAtom(useCreateAtom(false))const viewPlan = useCallback(() => {@@ -243,7 +246,7 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {staleTime: 300_000, queryFn: ({ signal }) => origin.run((options) => fetchLatestDaemonVersion({ ...options, signal })),})const latestVersion = versionQuery.data?.version ?? null- const machineCommand = useMutation({ mutationKey: ["community", "machine-command"], scope: { id: "community-machine-command" },+ const machineCommand = useMutation({ meta: { observabilityAction: "machine.command" }, mutationKey: ["community", "machine-command"], scope: { id: "community-machine-command" },mutationFn: async ({ kind, id, token, assert }: { kind: "delete" | "update"; id: string; token: ReturnType<typeof origin.begin>["token"]; assert: ReturnType<typeof source.capture> }) => {origin.assert(token)const key = communityKeys.machines()diff --git a/src/web/src/components/community/machines/pair-machine-sheet.tsx b/src/web/src/components/community/machines/pair-machine-sheet.tsxindex 93b2d894c..06967d274 100644--- a/src/web/src/components/community/machines/pair-machine-sheet.tsx+++ b/src/web/src/components/community/machines/pair-machine-sheet.tsx@@ -76,7 +76,7 @@ export function PairMachineSheet({const openKey = mode.kind === "reconnect" ? `reconnect:${mode.machineId}` : "pair"const source = useCommunityViewSource(`machine-pair:${openKey}`, open)const desktopNative = isTauri() && isDesktop()- const generation = useMutation({+ const generation = useMutation({ meta: { observabilityAction: "machine.pair.generate" },gcTime: 0,mutationKey: ["community", "machine-pair", openKey],mutationFn: async ({ token, assert }: { token: ReturnType<typeof origin.begin>["token"]; assert: ReturnType<typeof source.capture> }) => {@@ -134,7 +134,7 @@ export function PairMachineSheet({available: false, reason: nativeErrorMessage(capability.error, "Alook couldn't check Node.js and npm on this computer."), nodeVersion: null,} : null)const checkingRuntime = open && desktopNative && capability.isPending- const launch = useMutation({+ const launch = useMutation({ meta: { observabilityAction: "machine.pair.launch" },gcTime: 0,mutationKey: ["community", "machine-pair", openKey, "launch"],mutationFn: async ({ key, machineId, assert }: { key: string; machineId: string | null; assert: ReturnType<typeof source.capture> }) => {diff --git a/src/web/src/components/community/members/add-members-dialog.tsx b/src/web/src/components/community/members/add-members-dialog.tsxindex 49bb8cc19..a0fc7e5cd 100644--- a/src/web/src/components/community/members/add-members-dialog.tsx+++ b/src/web/src/components/community/members/add-members-dialog.tsx@@ -112,7 +112,7 @@ export function AddMembersDialog({const source = useCommunityViewSource("add-members:" + scopeId)const key = ["community", "member-picker", scopeId]type Intent = { userId: string; candidate: AddableCandidate; assert: ReturnType<typeof source.capture> }- const command = useMutation({+ const command = useMutation({ meta: { observabilityAction: "channel.members.add" },mutationKey: key,gcTime: 0,mutationFn: async ({ userId, assert }: Intent) => { assert(); await onAdd(userId, assert); assert() },diff --git a/src/web/src/components/community/members/member-list.tsx b/src/web/src/components/community/members/member-list.tsxindex 3969adf95..b4763dd52 100644--- a/src/web/src/components/community/members/member-list.tsx+++ b/src/web/src/components/community/members/member-list.tsx@@ -1,5 +1,6 @@"use client"+import { useObservedRegion, windowEvidence } from "@/lib/observability/regions"import { createStore, useSelector } from "@tanstack/react-store"import { useMutation, useQueryClient } from "@tanstack/react-query"import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"@@ -131,6 +132,7 @@ export function MemberList({onSetRole?: (memberId: string, role: Role) => voidonKick?: (memberId: string, assert?: MemberOriginalView) => Promise<unknown> | void}) {+ useObservedRegion("members", !loading, windowEvidence(members, members))const source = useCommunityViewSource("member-list:" + scopeId)const client = useQueryClient()const commandKey = ["community", "member-list-command", scopeId]@@ -144,7 +146,7 @@ export function MemberList({const kickTarget = members.find((member) => member.id === kickTargetId)const manageTarget = members.find((member) => member.id === manageConfirm?.memberId)type Intent = { kind: "kick" | "leave" | "remove"; memberId: string; userId: string; work: (id: string, assert?: MemberOriginalView) => Promise<unknown> | void; assert: ReturnType<typeof source.capture> }- const command = useMutation({+ const command = useMutation({ meta: { observabilityAction: "member.management.command", observabilityDelegate: true },mutationKey: commandKey,gcTime: 0,mutationFn: async (intent: Intent) => {diff --git a/src/web/src/components/community/messages/attachment-preview-sheet.tsx b/src/web/src/components/community/messages/attachment-preview-sheet.tsxindex 2e846058a..41ed69a9c 100644--- a/src/web/src/components/community/messages/attachment-preview-sheet.tsx+++ b/src/web/src/components/community/messages/attachment-preview-sheet.tsx@@ -1,5 +1,6 @@"use client"+import { useObservedQueryRegion } from "@/lib/observability/query-regions"import { useQuery } from "@tanstack/react-query"import { applicationKey, assertApplicationOwner, captureApplicationOwner, useApplicationOwner } from "@/lib/application-owner"import dynamic from "next/dynamic"@@ -185,6 +186,7 @@ export function AttachmentPreviewSheet({: content.isError ? { status: "error", content: null, error: content.error instanceof Error ? content.error.message : "Couldn’t load this attachment" }: content.data ?? { status: "loading", content: null, error: null }+ useObservedQueryRegion("file_preview", content, undefined, open && preview.status === "ready" && presentation?.previewKind === "text")const size = selected? formatAttachmentSize(selected.sizeBytes) || selected.size: ""diff --git a/src/web/src/components/community/messages/code-preview.tsx b/src/web/src/components/community/messages/code-preview.tsxindex 5d0bd1af5..4a88aa949 100644--- a/src/web/src/components/community/messages/code-preview.tsx+++ b/src/web/src/components/community/messages/code-preview.tsx@@ -1,6 +1,8 @@"use client"-import { useQuery } from "@tanstack/react-query"+import { useObservedRegion } from "@/lib/observability/regions"+import { valueEvidence } from "@/lib/observability/data-source"+import { useQuery, useQueryClient } from "@tanstack/react-query"import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useEffect, useRef, type CSSProperties } from "react"@@ -95,6 +97,8 @@ export function CodePreview({},})const highlight: CodeHighlightResult = query.data ?? { kind: "plain", lines: null, reason: null }+ const client = useQueryClient()+ useObservedRegion("file_preview", !query.isPending && !query.isError, valueEvidence(client, query.data))const highlighting = query.isFetchingconst [wrap, setWrap] = useAtom(useCreateAtom(false))const [copyState, setCopyState] = useAtom(useCreateAtom<"idle" | "copied" | "failed">("idle"))diff --git a/src/web/src/components/community/messages/create-forum-thread.tsx b/src/web/src/components/community/messages/create-forum-thread.tsxindex 62a328e24..1313107c0 100644--- a/src/web/src/components/community/messages/create-forum-thread.tsx+++ b/src/web/src/components/community/messages/create-forum-thread.tsx@@ -74,7 +74,7 @@ export function CreateForumThread({for (const mutation of client.getMutationCache().findAll({ mutationKey: ["community", "file-upload"], predicate: (mutation) => (mutation.state.variables as UploadFileArgs | undefined)?.receiptScope === scopeId })) client.getMutationCache().remove(mutation)}, [client, scopeId])useEffect(() => () => clearUploadReceipts(), [clearUploadReceipts])- const command = useMutation({ mutationKey: key, gcTime: 0,+ const command = useMutation({ meta: { observabilityAction: "forum.thread.create" }, mutationKey: key, gcTime: 0,mutationFn: async ({ markdown, title, attachments, mentionType, nonce, original }: { markdown: string; title: string; attachments: SendAttachment[]; mentionType?: MentionType; nonce: string; original: ReturnType<typeof source.capture> }) => {original()const results = await Promise.all(attachments.map(async (attachment) => {diff --git a/src/web/src/components/community/messages/message-list.tsx b/src/web/src/components/community/messages/message-list.tsxindex b73df64ab..0d75f6ff3 100644--- a/src/web/src/components/community/messages/message-list.tsx+++ b/src/web/src/components/community/messages/message-list.tsx@@ -1,6 +1,10 @@"use client"import { isConversationAccessError } from "@/lib/community/conversation-read"+import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"+import { mergeEvidence, viewEvidence } from "@/lib/observability/data-source"+import { useObservedRegion, windowEvidence } from "@/lib/observability/regions"+import { visibleVirtualItems } from "@/lib/observability/virtual-window"import { useLayoutEffect } from "react"import { useMessageListController } from "./message-list-controller"import { useHoverCapable } from "@/hooks/use-hover-capable"@@ -24,6 +28,10 @@ export function MessageList({hoverCapable,}const controller = useMessageListController(resolvedProps)+ const visible = visibleVirtualItems(controller.virtualizer).flatMap(item => { const row = controller.items[item.index]; return row?.kind === "message" ? [row.m] : [] })+ const profiles = useCanonicalProfilesByUserId(visible.flatMap(message => [message.authorId, message.replyTo?.authorId].filter((id): id is string => !!id)))+ const evidence = windowEvidence(visible, props.messages)+ useObservedRegion("messages", controller.initialPosition.contentVisible && controller.initialPosition.contentInteractive && !resolvedProps.initialLoadError && (!props.messages.length || visible.length > 0), { ...mergeEvidence([evidence, ...[...profiles.values()].map(viewEvidence)]), count: visible.length })const footerSlot = useConversationFooterSlot()const setSelectionActive = footerSlot?.setSelectionActiveuseLayoutEffect(() => {diff --git a/src/web/src/components/community/messages/message-share-dialog.tsx b/src/web/src/components/community/messages/message-share-dialog.tsxindex 68c1e8026..223720ca9 100644--- a/src/web/src/components/community/messages/message-share-dialog.tsx+++ b/src/web/src/components/community/messages/message-share-dialog.tsx@@ -156,7 +156,7 @@ export function MessageShareDialog({ m, open, onClose }: {}useQuery({ ...pngOptions, enabled: false, subscribed: open })const exportKey = ["community", "share-image", scopeId, "export"]- const command = useMutation({ mutationKey: exportKey, gcTime: 0,+ const command = useMutation({ meta: { observabilityAction: "message.export" }, mutationKey: exportKey, gcTime: 0,mutationFn: async ({ action, original }: { action: "copy" | "download"; original: ReturnType<typeof source.capture> }) => {original()const prepared = client.getQueryData<{ value: PreparedShareImageSession; filename: string }>(preparationKey)diff --git a/src/web/src/components/community/messages/pdf-preview.tsx b/src/web/src/components/community/messages/pdf-preview.tsxindex 136ddf86a..48093dc2a 100644--- a/src/web/src/components/community/messages/pdf-preview.tsx+++ b/src/web/src/components/community/messages/pdf-preview.tsx@@ -12,6 +12,8 @@ import {type PDFPageProxy,type RenderTask,} from "pdfjs-dist/legacy/build/pdf.mjs"+import { useObservedRegion } from "@/lib/observability/regions"+import { viewEvidence, type Evidence } from "@/lib/observability/data-source"import { tid } from "@/lib/community/testids"export const MAX_PDF_CANVAS_PIXELS = 4_000_000@@ -85,10 +87,12 @@ function PdfPage({document,pageNumber,availableWidth,+ evidence,}: {document: PDFDocumentProxypageNumber: numberavailableWidth: number+ evidence: Evidence}) {const containerRef = useRef<HTMLElement>(null)const canvasRef = useRef<HTMLCanvasElement>(null)@@ -167,6 +171,8 @@ function PdfPage({}}, [availableWidth, document, nearby, pageNumber, setAspectRatio, setStatus])+ useObservedRegion("file_preview", pageNumber === 1 && status === "ready", { ...evidence, count: 1 })+return (<sectionref={containerRef}@@ -195,7 +201,7 @@ function PdfPage({)}-function PdfPages({ document }: { document: PDFDocumentProxy }) {+function PdfPages({ document, evidence }: { document: PDFDocumentProxy; evidence: Evidence }) {const pagesRef = useRef<HTMLDivElement>(null)const availableWidth = useElementWidth(pagesRef)@@ -208,6 +214,7 @@ function PdfPages({ document }: { document: PDFDocumentProxy }) {document={document}pageNumber={index + 1}availableWidth={availableWidth}+ evidence={evidence}/>))}</div>@@ -285,7 +292,7 @@ export function PdfPreview({ data }: { data: Uint8Array<ArrayBuffer> }) {</div>)}{state.status === "ready" && (- <PdfPages document={state.document} />+ <PdfPages document={state.document} evidence={viewEvidence(data)} />)}</div>)diff --git a/src/web/src/components/community/messages/thread-opener.tsx b/src/web/src/components/community/messages/thread-opener.tsxindex 69fa83584..6cc3ee029 100644--- a/src/web/src/components/community/messages/thread-opener.tsx+++ b/src/web/src/components/community/messages/thread-opener.tsx@@ -1,4 +1,6 @@"use client"+import { useObservedRegion } from "@/lib/observability/regions"+import { mergeEvidence, viewEvidence } from "@/lib/observability/data-source"import { MessagesSquare, ArrowUpRight } from "lucide-react"import { Avatar } from "../avatar"@@ -68,6 +70,7 @@ export function ThreadOpener({serverId,})const authorProfile = useCanonicalCommunityProfile(msg?.authorId)+ useObservedRegion("thread_opener", !isLoading && !isError && !!msg, { ...mergeEvidence([viewEvidence(msg), viewEvidence(authorProfile)]), count: msg ? 1 : 0 })const mentionText = msg ? resolveAuthorMentionText?.(msg.authorId) ?? null : nullconst avatarMention = useMobileAvatarMention({onMention: mentionText && onInsertMentionTextdiff --git a/src/web/src/components/community/messages/use-composer-controller.ts b/src/web/src/components/community/messages/use-composer-controller.tsindex ed8819ca8..f4788a39f 100644--- a/src/web/src/components/community/messages/use-composer-controller.ts+++ b/src/web/src/components/community/messages/use-composer-controller.ts@@ -249,7 +249,7 @@ export function useComposerController(// eslint-disable-next-line react-hooks/exhaustive-deps}, [pendingFiles, editor])- const sendCommand = useMutation({ mutationKey: sendKey, gcTime: 0,+ const sendCommand = useMutation({ meta: { observabilityAction: "message.compose.send" }, mutationKey: sendKey, gcTime: 0,mutationFn: async ({ generation, scopeVersion, editor }: { generation: number; scopeVersion: number; editor: Editor }) => {const assert = () => { const current = protocol.get(); if (!current.active || current.generation !== generation || current.scopeVersion !== scopeVersion) throw new DOMException("Retired composer send", "AbortError") }assert()diff --git a/src/web/src/components/community/onboarding/community-onboarding-form.tsx b/src/web/src/components/community/onboarding/community-onboarding-form.tsxindex 480887a17..5ffa4ac42 100644--- a/src/web/src/components/community/onboarding/community-onboarding-form.tsx+++ b/src/web/src/components/community/onboarding/community-onboarding-form.tsx@@ -42,7 +42,7 @@ export function CommunityOnboardingForm() {const [customIdentity, setCustomIdentity] = useAtom(useCreateAtom(""))const commandKey = ["community", "onboarding-initialization", journeyIdentity] as constconst pending = useMutationState({ filters: { mutationKey: commandKey, status: "pending" }, select: (mutation) => mutation.mutationId })- const initialization = useMutation({+ const initialization = useMutation({ meta: { observabilityAction: "community.onboarding.initialize" },mutationKey: commandKey,scope: { id: JSON.stringify(commandKey) },mutationFn: async ({ token, profileSnapshot, assert, input }: ReturnType<typeof origin.begin> & {diff --git a/src/web/src/components/community/onboarding/onboarding-machine-dialog.tsx b/src/web/src/components/community/onboarding/onboarding-machine-dialog.tsxindex 9abad9556..da161f056 100644--- a/src/web/src/components/community/onboarding/onboarding-machine-dialog.tsx+++ b/src/web/src/components/community/onboarding/onboarding-machine-dialog.tsx@@ -64,7 +64,7 @@ export function OnboardingMachineDialog({[harness, machines],)const autoMint = useCreateAtom<AbortSignal | null>(null)- const generation = useMutation({+ const generation = useMutation({ meta: { observabilityAction: "machine.pair.generate" },mutationKey: ["community", "onboarding-machine-pair", harness], gcTime: 0,mutationFn: async ({ token, assert }: { token: ReturnType<typeof origin.begin>["token"]; assert: ReturnType<typeof source.capture> }) => {assert()diff --git a/src/web/src/components/community/settings/account-deletion-flow.tsx b/src/web/src/components/community/settings/account-deletion-flow.tsxindex 3d64ff3af..084769574 100644--- a/src/web/src/components/community/settings/account-deletion-flow.tsx+++ b/src/web/src/components/community/settings/account-deletion-flow.tsx@@ -97,7 +97,7 @@ export function AccountDeletionFlow({ email, onCancel, onDeleted }: Props) {const viewSubscription = view.subscribe(abort), accountSubscription = registry.runtime.lifecycle.subscribe(abort)return { registry, generation, controller, assertActive, options: communityRequestOptions(queryClient, token, controller.signal, assertActive), release: () => { viewSubscription.unsubscribe(); accountSubscription.unsubscribe() } }}- const request = useMutation({ mutationFn: async ({ action, body, source }: { action: "code" | "delete"; body: string; source: ReturnType<typeof capture> }) => {+ const request = useMutation({ meta: { observabilityAction: "account.deletion.command" }, mutationFn: async ({ action, body, source }: { action: "code" | "delete"; body: string; source: ReturnType<typeof capture> }) => {source.assertActive()const response = await fetch(`/api/community/users/me/account-deletion${action === "code" ? "/code" : ""}`, { method: "POST", credentials: "include", headers: { "Content-Type": "application/json" }, body, signal: source.controller.signal })if (action === "code" || !response.ok) source.assertActive()diff --git a/src/web/src/components/community/settings/server-settings-channels.tsx b/src/web/src/components/community/settings/server-settings-channels.tsxindex 754038f8c..5e65d7a7b 100644--- a/src/web/src/components/community/settings/server-settings-channels.tsx+++ b/src/web/src/components/community/settings/server-settings-channels.tsx@@ -1,5 +1,8 @@"use client"+import { useObservedRegion } from "@/lib/observability/regions"+import { viewEvidence } from "@/lib/observability/data-source"+import { useAtom, useCreateAtom } from "@tanstack/react-store"import { ChevronDown, Lock } from "lucide-react"import { Button } from "@/components/ui/button"@@ -22,6 +25,7 @@ function groupChannels(channels: AdminChannel[]) {export function ServerSettingsChannels({ serverId }: { serverId: string }) {const [collapsed, setCollapsed] = useAtom(useCreateAtom<Set<string>>(new Set<string>()))const { channels, isError, isFetching, refetch, forbidden } = useServerAdminChannels(serverId, true)+ useObservedRegion("settings", !!channels && !forbidden, { ...viewEvidence(channels), count: channels?.length ?? 0 })const retry = () => { void refetch() }if (forbidden) return <p role="alert" className="text-sm text-muted-foreground">Only server administrators can view channels.</p>diff --git a/src/web/src/components/community/settings/server-settings.tsx b/src/web/src/components/community/settings/server-settings.tsxindex 2e3c3766a..5f452d6ce 100644--- a/src/web/src/components/community/settings/server-settings.tsx+++ b/src/web/src/components/community/settings/server-settings.tsx@@ -1,5 +1,8 @@"use client"+import { useObservedRegion } from "@/lib/observability/regions"+import { viewEvidence } from "@/lib/observability/data-source"+import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useEffect, useRef } from "react"import { useVirtualizer } from "@tanstack/react-virtual"@@ -86,6 +89,8 @@ export function ServerSettings({// their tab is open, never on settings mount or via WS.const { invites, isLoading: invitesLoading } = useInvites(serverId, section === "invites")+ useObservedRegion("settings", visibleSection === "members" ? !membersLoading : visibleSection === "invites" ? !invitesLoading : visibleSection !== "channels", visibleSection === "members" ? viewEvidence(members) : visibleSection === "invites" ? viewEvidence(invites) : { source: "unknown", version: "settings_" + visibleSection, freshness: "unknown", count: 1 })+const nav: SettingsShellTab<SettingsSection>[] = [{ value: "overview", label: "Overview", icon: Settings },{ value: "members", label: "Members", icon: Users },diff --git a/src/web/src/components/community/settings/user-settings.tsx b/src/web/src/components/community/settings/user-settings.tsxindex 89082c82c..5a148dd6f 100644--- a/src/web/src/components/community/settings/user-settings.tsx+++ b/src/web/src/components/community/settings/user-settings.tsx@@ -1,5 +1,8 @@"use client"+import { useObservedRegion } from "@/lib/observability/regions"+import { useObservedQueryRegion } from "@/lib/observability/query-regions"+import { useAtom, useCreateAtom, useCreateStore } from "@tanstack/react-store";import { useEffect, useLayoutEffect } from "react"import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"@@ -85,8 +88,9 @@ export function AdvancedSettings() {const [clearError, setClearError] = useAtom(useCreateAtom<string | null>(null))const queryClient = useQueryClient()const size = useQuery({ queryKey: CACHE_SIZE_QUERY_KEY, queryFn: ({ signal }) => getPersistedCacheSizeBytes(signal), retry: false, staleTime: 0 })- const clear = useMutation({ mutationFn: clearAllPersistedCaches })+ const clear = useMutation({ meta: { observabilityAction: "cache.clear" }, mutationFn: clearAllPersistedCaches })const clearing = clear.isPending+ useObservedQueryRegion("settings", size, 1)const cacheSize = size.isPending ? "loading" : size.isError ? "unavailable" : size.dataconst view = useCreateStore({ active: true, generation: 0 })const webVersion = process.env.NEXT_PUBLIC_APP_VERSION@@ -206,6 +210,7 @@ export function UserSettings({ initialTab = "profile", billingReturn = null, onCuseEffect(() => { setTab(initialTab) }, [initialTab, setTab])const billing = useBilling(billingReturn, tab === "billing")const [deletionOpen, setDeletionOpen] = useAtom(useCreateAtom(false))+ useObservedRegion("settings", tab !== "billing" && tab !== "advanced", { source: "unknown", version: "settings_" + tab, freshness: "unknown", count: 1 })const dirty =name !== baseline.name ||diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsxindex 4ee86a64f..73ba4be69 100644--- a/src/web/src/components/community/shell/community-inbox-popover.tsx+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx@@ -1,3 +1,5 @@+import { useObservedRegion } from "@/lib/observability/regions"+import { mergeEvidence, viewEvidence } from "@/lib/observability/data-source"import { Bookmark, Check, ChevronRight, Inbox, LoaderCircle, MoreHorizontal, Trash2, X } from "lucide-react"import { stripInlineMarkup } from "@alook/shared"import { EntityIcon } from "../entity-icon"@@ -142,6 +144,7 @@ function UnreadsTab({ friendRequests, servers, dms, loading, error, onRetry, onOgetScrollOffset?: (tab: InboxTab) => numberonScrollOffsetChange?: (tab: InboxTab, scrollTop: number) => void}) {+ useObservedRegion("inbox", !loading && !error, { ...mergeEvidence([viewEvidence(servers), viewEvidence(dms), viewEvidence(friendRequests)]), count: servers.length + dms.length + friendRequests.length })const visibleDms = dmsconst visibleServers = servers.map((server) => ({server,@@ -311,6 +314,7 @@ function MentionsTab({ mentions, loading, error, onRetry, onOpenMention, onDeletgetScrollOffset?: (tab: InboxTab) => numberonScrollOffsetChange?: (tab: InboxTab, scrollTop: number) => void}) {+ useObservedRegion("inbox", !loading && !error, viewEvidence(mentions))const visibleMentions = mentionsreturn (<InboxScrollBody tab="mentions" getScrollOffset={getScrollOffset} onScrollOffsetChange={onScrollOffsetChange}>@@ -376,6 +380,7 @@ function MarkedTab({ marked, loading, onOpenMarked, onUnmark, profilesByUserId,getScrollOffset?: (tab: InboxTab) => numberonScrollOffsetChange?: (tab: InboxTab, scrollTop: number) => void}) {+ useObservedRegion("inbox", !loading, viewEvidence(marked))return (<InboxScrollBody tab="marked" getScrollOffset={getScrollOffset} onScrollOffsetChange={onScrollOffsetChange}>{loading && marked.length === 0 && <InboxRowsSkeleton />}diff --git a/src/web/src/components/community/shell/dm-sidebar-slot.tsx b/src/web/src/components/community/shell/dm-sidebar-slot.tsxindex 96d48855b..fb48e195c 100644--- a/src/web/src/components/community/shell/dm-sidebar-slot.tsx+++ b/src/web/src/components/community/shell/dm-sidebar-slot.tsx@@ -1,4 +1,6 @@"use client"+import { useObservedRegion } from "@/lib/observability/regions"+import { viewEvidence, mergeEvidence } from "@/lib/observability/data-source"import { useCommunityRuntime } from "@/stores/community/runtime"@@ -27,6 +29,7 @@ function MeSidebar() {isLoading: dmsLoading,} = useDms()const { blocked } = useFriends()+ useObservedRegion("sidebar", !dmsLoading, { ...mergeEvidence([viewEvidence(dms), viewEvidence(blocked)]), count: dms.length })const friendRequestCount = useInboxUnreads().friendRequests.lengthconst currentChannelId = useCurrentChannelId()diff --git a/src/web/src/components/community/shell/server-rail.tsx b/src/web/src/components/community/shell/server-rail.tsxindex c4a58a753..1b41cd71b 100644--- a/src/web/src/components/community/shell/server-rail.tsx+++ b/src/web/src/components/community/shell/server-rail.tsx@@ -1,4 +1,7 @@"use client"++import { useObservedRegion } from "@/lib/observability/regions"+import { viewEvidence, mergeEvidence } from "@/lib/observability/data-source"import { useCommunityRuntime } from "@/stores/community/runtime"import { useAtom, useCreateAtom } from "@tanstack/react-store";@@ -141,6 +144,7 @@ export const ServerRail = memo(function ServerRail({onOpenSettings?: (serverId: string) => voidonOpenInvitePopover?: (serverId: string) => void}) {+ useObservedRegion("rail", !serversLoading, { ...mergeEvidence([viewEvidence(servers), viewEvidence(folders)]), count: servers.length + folders.length })const expandedAtom = useCreateAtom<string[]>([])const [expanded, setExpanded] = useAtom(expandedAtom)const collapsedAtom = useCreateAtom(new Set<string>())diff --git a/src/web/src/components/community/shell/server-sidebar-slot.tsx b/src/web/src/components/community/shell/server-sidebar-slot.tsxindex 7cf6407d6..88fe26fc1 100644--- a/src/web/src/components/community/shell/server-sidebar-slot.tsx+++ b/src/web/src/components/community/shell/server-sidebar-slot.tsx@@ -1,4 +1,5 @@"use client"+import { deriveView, viewEvidence } from "@/lib/observability/data-source"import { useAtom, useCreateAtom, useSelector } from "@tanstack/react-store";import { getCommunityRuntime } from "@/stores/community/runtime"@@ -362,6 +363,7 @@ function ServerSidebar({ serverId }: { serverId: string }) {: { ...channel, unread: forumSidebar.parentUnread[channel.id] },),})), [forumSidebar.parentUnread, sidebarCategories])+ deriveView(categories, [viewEvidence(sidebarCategories), viewEvidence(forumSidebar.threads)])const sidebarDataReady = Boolean(currentServer)const channelTreeScopeKey = `server:${serverId}`diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsxindex 966483aeb..42be3da55 100644--- a/src/web/src/components/community/shell/shell-frame.tsx+++ b/src/web/src/components/community/shell/shell-frame.tsx@@ -1,4 +1,6 @@"use client"++import { commitNavigation } from "@/lib/observability/context"import { useAtom, useCreateAtom } from "@tanstack/react-store";import { getCommunityRuntime } from "@/stores/community/runtime"@@ -75,6 +77,7 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommitt}, [setCommittedFrame])useLayoutEffect(() => {commitFrame(frameHref)+ commitNavigation(frameHref)if (ownerDeleteRouteScope) {registerOwnerServerDeleteRoute(queryClient,ownerDeleteRouteScope.serverId,diff --git a/src/web/src/components/community/shell/use-community-navigation-controller.ts b/src/web/src/components/community/shell/use-community-navigation-controller.tsindex 0ea26944e..5f1cd8ccc 100644--- a/src/web/src/components/community/shell/use-community-navigation-controller.ts+++ b/src/web/src/components/community/shell/use-community-navigation-controller.ts@@ -1,5 +1,7 @@"use client"+import { beginNavigation, navigationNoop } from "@/lib/observability/context"+import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useCallback, useEffect, useLayoutEffect, useRef } from "react"import { flushSync } from "react-dom"@@ -92,7 +94,8 @@ export function useCommunityNavigationController(}, [cancelPendingNavigation])const push = useCallback((href: string) => {- if (href === publishedHref && !navigationPending) return+ if (href === publishedHref && !navigationPending) { navigationNoop(href); return }+ beginNavigation(href)supersedeNavigationIntent(gateRef.current)cancelActiveConversationNavigationProof(queryClient)pendingBaselineRevisionRef.current = committedFrame.revision@@ -108,7 +111,8 @@ export function useCommunityNavigationController(}, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setNavigationPending, setPendingHref])const pushImmediate = useCallback((href: string) => {- if (href === publishedHref && !navigationPending) return+ if (href === publishedHref && !navigationPending) { navigationNoop(href); return }+ beginNavigation(href)supersedeNavigationIntent(gateRef.current)pendingBaselineRevisionRef.current = committedFrame.revisionpendingBaselineLeafRef.current = committedFrame.leafKey@@ -122,7 +126,8 @@ export function useCommunityNavigationController(}, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, router, setNavigationPending, setPendingHref])const replace = useCallback((href: string) => {- if (href === publishedHref && !navigationPending) return+ if (href === publishedHref && !navigationPending) { navigationNoop(href); return }+ beginNavigation(href)supersedeNavigationIntent(gateRef.current)cancelActiveConversationNavigationProof(queryClient)pendingBaselineRevisionRef.current = committedFrame.revision@@ -140,10 +145,12 @@ export function useCommunityNavigationController(setPendingHref(null)const operation = commitLatestNavigationIntent(gateRef.current, resolve, (href) => {if (href === publishedHref) {+ navigationNoop(href)setNavigationPending(false)setPendingHref(null)return}+ beginNavigation(href)setPendingHref(href)router.push(href)})diff --git a/src/web/src/components/community/social/friends-page.tsx b/src/web/src/components/community/social/friends-page.tsxindex 9a96f619c..e8ed37eb6 100644--- a/src/web/src/components/community/social/friends-page.tsx+++ b/src/web/src/components/community/social/friends-page.tsx@@ -1,4 +1,6 @@"use client"+import { useObservedRegion } from "@/lib/observability/regions"+import { mergeEvidence, viewEvidence } from "@/lib/observability/data-source"import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { useQuery, useQueryClient } from "@tanstack/react-query"@@ -67,6 +69,7 @@ export function FriendsPage({onBlock?: (id: string) => voidonDm?: (userId: string) => void}) {+ useObservedRegion("friends", !loading, { ...mergeEvidence([viewEvidence(friends), viewEvidence(pending), viewEvidence(blocked)]), count: friends.length + pending.length + blocked.length })const profileQueryClient = useQueryClient()const [filter, setFilter] = useAtom(useCreateAtom(""))const filteredFriends = useMemo(() => {diff --git a/src/web/src/components/community/social/invite-dialog.tsx b/src/web/src/components/community/social/invite-dialog.tsxindex 8a398d250..eb5cb08a5 100644--- a/src/web/src/components/community/social/invite-dialog.tsx+++ b/src/web/src/components/community/social/invite-dialog.tsx@@ -175,7 +175,7 @@ export function InviteDialog({type SendIntent = { userId: string; token: string; author: { id: string; name: string; avatar: string }; assert: ReturnType<typeof view.capture> }const sendKey = ["community", "invite-send", serverId]- const sender = useMutation({+ const sender = useMutation({ meta: { observabilityAction: "invitation.send" },mutationKey: sendKey,gcTime: 0,mutationFn: async ({ userId, token, author, assert }: SendIntent) => {@@ -194,7 +194,7 @@ export function InviteDialog({})const pending = useMutationState({ filters: { mutationKey: sendKey, status: "pending" }, select: (mutation) => mutation.state.variables as SendIntent | undefined })const invitingUserIds = new Set(pending.filter((intent) => intent?.assert.signal === view.signal).map((intent) => intent!.userId))- const copier = useMutation({+ const copier = useMutation({ meta: { observabilityAction: "invitation.copy" },gcTime: 0,mutationFn: async ({ token, assert }: { token: string; assert: ReturnType<typeof view.capture> }) => {assert()diff --git a/src/web/src/components/custom-email-form.tsx b/src/web/src/components/custom-email-form.tsxindex 0a7685106..bc7f6b60f 100644--- a/src/web/src/components/custom-email-form.tsx+++ b/src/web/src/components/custom-email-form.tsx@@ -227,7 +227,7 @@ export function CustomEmailForm({ agentId, workspaceId, onDataChange, getDataRefqueryFn: ({ signal }) => runWorkspaceRequest(owner, (options) => listEmailAccounts(agentId!, workspaceId, options), signal),});type Command = { kind: "create"; data: CustomEmailData } | { kind: "delete" | "sync"; id: string };- const command = useMutation({ mutationKey: [...queryKey, "command"], scope: { id: JSON.stringify(queryKey) },+ const command = useMutation({ meta: { observabilityAction: "email.account.command" }, mutationKey: [...queryKey, "command"], scope: { id: JSON.stringify(queryKey) },gcTime: 0,mutationFn: async ({ action, token, assertView, signal, resource: original }: { action: Command; token: ReturnType<typeof captureWorkspaceOwner>; assertView: () => void; signal: AbortSignal; resource: Query | undefined }) => {const assert = () => { assertWorkspaceOwner(token, signal); assertView(); };diff --git a/src/web/src/components/ui/tabs.tsx b/src/web/src/components/ui/tabs.tsxindex f4168b163..c538ef182 100644--- a/src/web/src/components/ui/tabs.tsx+++ b/src/web/src/components/ui/tabs.tsx@@ -1,5 +1,6 @@"use client"+import { ObservedRegionVisibility } from "@/lib/observability/regions"import { Tabs as TabsPrimitive } from "@base-ui/react/tabs"import { cva, type VariantProps } from "class-variance-authority"@@ -74,6 +75,7 @@ function TabsContent({ className, ...props }: TabsPrimitive.Panel.Props) {<TabsPrimitive.Paneldata-slot="tabs-content"className={cn("flex-1 text-sm outline-none", className)}+ render={(panel, state) => <div {...panel}><ObservedRegionVisibility visible={!state.hidden}>{panel.children}</ObservedRegionVisibility></div>}{...props}/>)diff --git a/src/web/src/contexts/agent-context.tsx b/src/web/src/contexts/agent-context.tsxindex a2b7d2c2e..7acb33f1f 100644--- a/src/web/src/contexts/agent-context.tsx+++ b/src/web/src/contexts/agent-context.tsx@@ -1,5 +1,7 @@"use client"+import { deriveView, valueEvidence, withSource } from "@/lib/observability/data-source"+import { isAbortError } from "@/lib/errors"import { publishWorkspaceChatEvent } from "@/lib/workspace-chat-events"import { captureQueryReceipt, withQueryReceipt, reconcileQueryReceipt } from "@/lib/query-receipt"@@ -120,7 +122,7 @@ export function useAgentContext({ poll = false }: { poll?: boolean } = {}): Agenconst detailsQuery = useQuery({ ...owner.queries.tasks, enabled: hasActiveTasks, subscribed: hasActiveTasks, refetchInterval: poll && hasActiveTasks ? 15_000 : false })const pendingNewAgent = useSelector(owner.ui, (state) => state.pendingNewAgent)const workspace = owner.workspace- const mutation = useMutation({+ const mutation = useMutation({ meta: { observabilityAction: "agent.update" },mutationFn: async ({ operation, token }: { operation: (options: ApiRequestOptions) => Promise<unknown>; token: ReturnType<typeof captureWorkspaceOwner> }) => {assertWorkspaceOwner(token)try {@@ -132,7 +134,7 @@ export function useAgentContext({ poll = false }: { poll?: boolean } = {}): Agen})const pinMutationKey = [...owner.queries.pins.queryKey, "change"]type PinChange = { kind: "pin" | "unpin" | "reorder-pins" | "reorder-unpinned"; ids: string[]; token: ReturnType<typeof captureWorkspaceOwner> }- const pinMutation = useMutation({+ const pinMutation = useMutation({ meta: { observabilityAction: "agent.rail.command" },mutationKey: pinMutationKey,scope: { id: JSON.stringify(pinMutationKey) },mutationFn: async (action: PinChange) => {@@ -268,6 +270,9 @@ export function useAgentContext({ poll = false }: { poll?: boolean } = {}): Agenconst pins = useMemo(() => new Map(pinData?.pins.map((pin) => [pin.agent_id, { created_at: pin.created_at, position: pin.position }])), [pinData])const unpinnedOrder = useMemo(() => new Map(pinData?.sidebar_order.map((entry) => [entry.agent_id, entry.position])), [pinData])const loading = results.slice(0, 4).some((result) => result.isPending)+ deriveView(agents, [valueEvidence(owner.workspace.queryClient, results[0]?.data)])+ deriveView(runtimes, [valueEvidence(owner.workspace.queryClient, results[1]?.data)])+ deriveView(agentLinks, [valueEvidence(owner.workspace.queryClient, results[3]?.data)])return useMemo(() => ({...operations, workspaceId: owner.workspace.workspaceId, agents, runtimes,agentLinks, activeTaskCounts, activeTaskDetails, pendingNewAgent,@@ -280,9 +285,11 @@ function AgentBootstrap({ owner }: { owner: AgentOwner }) {const { workspace } = ownerif (!workspace.lifecycle.get().active || !workspace.application.lifecycle.get().active) returnif ("workspaceId" in message && message.workspaceId && message.workspaceId !== workspace.workspaceId) return- publishWorkspaceChatEvent(workspace, message)- publishWorkspaceIssueEvent(workspace, message)- owner.dispatch(message)+ withSource(workspace.queryClient, "ws", () => {+ publishWorkspaceChatEvent(workspace, message)+ publishWorkspaceIssueEvent(workspace, message)+ owner.dispatch(message)+ })switch (message.type) {case "runtime.registered": case "runtime.deleted": void owner.reload(); breakcase "runtime.status":diff --git a/src/web/src/contexts/channel-context.tsx b/src/web/src/contexts/channel-context.tsxindex 6f6828b0c..2cbb9a80c 100644--- a/src/web/src/contexts/channel-context.tsx+++ b/src/web/src/contexts/channel-context.tsx@@ -59,7 +59,7 @@ export function useChannel() {const commandKey = [...owner.key, "command"]type Action = { kind: "create"; name: string } | { kind: "rename"; id: string; name: string } | { kind: "delete"; id: string } | { kind: "reorder"; ids: string[] }type Intent = { action: Action; token: ReturnType<typeof captureWorkspaceOwner>; view: ReturnType<typeof source.capture>; resource: Query | undefined; selection: number; targetName?: string }- const native = useMutation({ mutationKey: commandKey, scope: { id: JSON.stringify(commandKey) }, gcTime: 0,+ const native = useMutation({ meta: { observabilityAction: "workspace.channel.command" }, mutationKey: commandKey, scope: { id: JSON.stringify(commandKey) }, gcTime: 0,mutationFn: async ({ action, token, view, resource, selection, targetName }: Intent) => {const assert = () => { assertWorkspaceOwner(token, view.signal); view.assert() }const original = () => resource && qc.getQueryCache().find({ queryKey: owner.key, exact: true }) === resourcediff --git a/src/web/src/contexts/workspace-context.tsx b/src/web/src/contexts/workspace-context.tsxindex 0ee39a084..9c0fb652e 100644--- a/src/web/src/contexts/workspace-context.tsx+++ b/src/web/src/contexts/workspace-context.tsx@@ -1,5 +1,7 @@"use client"+import { commandObservation } from "@/lib/observability/context"+import { UnauthorizedError } from "@/lib/errors"import { useEffect, useLayoutEffect, useState, type ReactNode } from "react"import { createStore, createStoreContext } from "@tanstack/react-store"@@ -41,7 +43,7 @@ export function assertWorkspaceOwner(token: ReturnType<typeof captureWorkspaceOw}}export function workspaceRequestOptions(token: ReturnType<typeof captureWorkspaceOwner>, signal?: AbortSignal, assertActive = () => assertWorkspaceOwner(token, signal)): ApiRequestOptions & { assertActive: () => void } {- return { authenticationAccount: token.owner.application.userId, signal, assertActive, onUnauthorized: () => { assertActive(); return invalidateApplicationAuthentication(token.application, signal) } }+ return { observation: commandObservation(token), authenticationAccount: token.owner.application.userId, signal, assertActive, onUnauthorized: () => { assertActive(); return invalidateApplicationAuthentication(token.application, signal) } }}export async function runWorkspaceRequest<T>(owner: WorkspaceOwner, load: (options: ApiRequestOptions) => Promise<T>, signal?: AbortSignal) {const token = captureWorkspaceOwner(owner)diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.tsindex 013e4446d..24d6c55ae 100644--- a/src/web/src/hooks/community/community-ws/registry.ts+++ b/src/web/src/hooks/community/community-ws/registry.ts@@ -1,5 +1,8 @@import { getCommunityRuntime } from "@/stores/community/runtime"+import { telemetryId } from "@/lib/observability/context"+import { withSource } from "@/lib/observability/data-source"+import { emitTelemetry } from "@/lib/observability/telemetry"import type { CommunityWsEvent } from "@alook/shared"import type { CommunityWsReconcilePolicy } from "@/lib/analytics"@@ -162,7 +165,8 @@ export function dispatchCommunityWsEvents(messageEvent: creates[0]!,})}- runCommunityWsProjectionTransaction(context.queryClient, (projection) => {+ const receipts: Array<{ id: string; start: number; type: CommunityEventType }> = []+ try { withSource(context.queryClient, "ws", () => runCommunityWsProjectionTransaction(context.queryClient, (projection) => {const handlerContext: CommunityWsHandlerContext = {...context,projection,@@ -181,8 +185,12 @@ export function dispatchCommunityWsEvents(&& getCommunityRuntime(context.queryClient).ws.actions.isChannelAccessRevoked(channelId, serverId, parentChannelId ?? undefined)) continueif (channelId && serverId) getCommunityRuntime(context.queryClient).ws.actions.observeChannelScope(serverId, channelId, parentChannelId)const entry = communityWsRegistry[event.type] as RegistryEntry<typeof event.type>- entry.handler(event, handlerContext)- projectCommunityWsEventToDb(context.queryClient, event)+ const receipt = { id: telemetryId(), start: performance.now(), type: event.type }+ receipts.push(receipt)+ withSource(context.queryClient, "ws", () => {+ entry.handler(event, handlerContext)+ projectCommunityWsEventToDb(context.queryClient, event)+ }, receipt)if (["community:server.delete","community:channel.delete",@@ -192,7 +200,11 @@ export function dispatchCommunityWsEvents(scheduleAccountAttentionReconcile(context.queryClient)}}- })+ })) } catch (error) {+ for (const receipt of receipts) emitTelemetry("ws.event_applied", { ws_event_id: receipt.id, event_type: receipt.type, duration_ms: performance.now() - receipt.start, source: "ws", outcome: "partial", eligibility: "unknown" })+ throw error+ }+ for (const receipt of receipts) emitTelemetry("ws.event_applied", { ws_event_id: receipt.id, event_type: receipt.type, duration_ms: performance.now() - receipt.start, source: "ws", outcome: "success", eligibility: "eligible" })}export const communityWsReconnectPolicies = Array.from(new Set(diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.tsindex 68288c97c..773ee09d0 100644--- a/src/web/src/hooks/community/mutations/channels.ts+++ b/src/web/src/hooks/community/mutations/channels.ts@@ -94,7 +94,7 @@ function settleTree(origin: ReturnType<typeof useCommunityMutationOrigin>, queryexport function useCreateChannel() {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()- return useCommunityCommandMutation<CreateChannelResult, Error, CreateChannelArgs>(origin, {+ return useCommunityCommandMutation<CreateChannelResult, Error, CreateChannelArgs>(origin, { meta: { observabilityAction: "channel.create" },scope: { id: "community-tree-commands" },mutationFn: async (args) => {const id = tempChannelId()@@ -134,7 +134,7 @@ export type RenameChannelResult = { id: string; name: string }export function useRenameChannel() {const origin = useCommunityMutationOrigin()const queryClient = useQueryClient()- return useCommunityCommandMutation<RenameChannelResult, Error, RenameChannelArgs>(origin, {+ return useCommunityCommandMutation<RenameChannelResult, Error, RenameChannelArgs>(origin, { meta: { observabilityAction: "channel.rename" },scope: { id: "community-tree-commands" },mutationFn: async (args) => {const original = args.original@@ -193,7 +193,7 @@ export function useRenameChannel() {*/export function useMoveChannel() {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()- return useCommunityCommandMutation<void, Error, MoveChannelArgs>(origin, {+ return useCommunityCommandMutation<void, Error, MoveChannelArgs>(origin, { meta: { observabilityAction: "channel.move" },scope: { id: "community-tree-commands" },mutationFn: (args) => persistTreeChange(origin, queryClient, args, (db) => {if (db.collections.channels.has(args.channelId)) db.collections.channels.update(args.channelId, (row) => { row.categoryId = args.categoryId })@@ -210,7 +210,7 @@ export type DeleteChannelArgs = { serverId: string; channelId: string }export function useDeleteChannel() {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()- return useCommunityCommandMutation<void, Error, DeleteChannelArgs>(origin, {+ return useCommunityCommandMutation<void, Error, DeleteChannelArgs>(origin, { meta: { observabilityAction: "channel.delete" },scope: { id: "community-tree-commands" },mutationFn: (args) => persistTreeChange(origin, queryClient, args, (db) => {if (db.collections.channels.has(args.channelId)) db.collections.channels.delete(args.channelId)@@ -237,7 +237,7 @@ const tempCategoryId = () => `tmp_cat_${nanoid()}`export function useCreateCategory() {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()- return useCommunityCommandMutation<CreateCategoryResult, Error, CreateCategoryArgs>(origin, {+ return useCommunityCommandMutation<CreateCategoryResult, Error, CreateCategoryArgs>(origin, { meta: { observabilityAction: "category.create" },scope: { id: "community-tree-commands" },mutationFn: async (args) => {const id = tempCategoryId()@@ -267,7 +267,7 @@ export type UpdateCategoryArgs = {export function useUpdateCategory() {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()- return useCommunityCommandMutation<void, Error, UpdateCategoryArgs>(origin, {+ return useCommunityCommandMutation<void, Error, UpdateCategoryArgs>(origin, { meta: { observabilityAction: "category.update" },scope: { id: "community-tree-commands" },mutationFn: (args) => persistTreeChange(origin, queryClient, args, (db) => {if (args.name !== undefined && db.collections.categories.has(args.categoryId)) db.collections.categories.update(args.categoryId, (row) => { row.name = args.name!.trim() })@@ -284,7 +284,7 @@ export type DeleteCategoryArgs = { serverId: string; categoryId: string }export function useDeleteCategory() {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()- return useCommunityCommandMutation<void, Error, DeleteCategoryArgs>(origin, {+ return useCommunityCommandMutation<void, Error, DeleteCategoryArgs>(origin, { meta: { observabilityAction: "category.delete" },scope: { id: "community-tree-commands" },mutationFn: (args) => persistTreeChange(origin, queryClient, args, (db) => {if (db.collections.categories.has(args.categoryId)) db.collections.categories.delete(args.categoryId)@@ -301,7 +301,7 @@ export type ReorderCategoriesArgs = { serverId: string; categoryIds: string[] }export function useReorderCategories() {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()- return useCommunityCommandMutation<void, Error, ReorderCategoriesArgs>(origin, {+ return useCommunityCommandMutation<void, Error, ReorderCategoriesArgs>(origin, { meta: { observabilityAction: "category.reorder" },scope: { id: "community-tree-commands" },mutationFn: (args) => persistTreeChange(origin, queryClient, args, (db) => {args.categoryIds.forEach((id, position) => { if (db.collections.categories.get(id)?.serverId === args.serverId) db.collections.categories.update(id, (row) => { row.position = position }) })@@ -318,7 +318,7 @@ export type ReorderChannelsArgs = { serverId: string; channelIds: string[] }export function useReorderChannels() {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()- return useCommunityCommandMutation<void, Error, ReorderChannelsArgs>(origin, {+ return useCommunityCommandMutation<void, Error, ReorderChannelsArgs>(origin, { meta: { observabilityAction: "channel.reorder" },scope: { id: "community-tree-commands" },mutationFn: (args) => persistTreeChange(origin, queryClient, args, (db) => {args.channelIds.forEach((id, position) => { if (db.collections.channels.get(id)?.serverId === args.serverId) db.collections.channels.update(id, (row) => { row.position = position }) })diff --git a/src/web/src/hooks/community/mutations/dm.ts b/src/web/src/hooks/community/mutations/dm.tsindex 286c2a4f3..981d2f2cb 100644--- a/src/web/src/hooks/community/mutations/dm.ts+++ b/src/web/src/hooks/community/mutations/dm.ts@@ -21,7 +21,7 @@ export function useCreateOrGetDm() {const origin = useCommunityMutationOrigin()const queryClient = useQueryClient()type Intent = CreateOrGetDmArgs & { original: ReturnType<typeof origin.begin>["token"] }- const native = useMutation<CreateOrGetDmResult, Error, Intent>({+ const native = useMutation<CreateOrGetDmResult, Error, Intent>({ meta: { observabilityAction: "dm.open" },mutationFn: async ({ userId, original, assertActive }) => {// Unified create door (route/disc create-door step): POST /channels with// {type:"dm", userId} → get-or-create DM by peer identity.diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.tsindex 84c7bb146..ad8a1e12a 100644--- a/src/web/src/hooks/community/mutations/forum.ts+++ b/src/web/src/hooks/community/mutations/forum.ts@@ -49,7 +49,7 @@ export function useCreateForumThread() {const origin = useCommunityMutationOrigin()const queryClient = useQueryClient()type Intent = CreateForumThreadArgs & { original: ReturnType<typeof origin.begin>["token"]; resources: Query[] }- const native = useMutation<CreateForumThreadResult, Error, Intent>({+ const native = useMutation<CreateForumThreadResult, Error, Intent>({ meta: { observabilityAction: "forum.thread.create" },mutationFn: async ({ nonce, channelId, name, content, attachments, mentionType, original: token, resources, assertActive }) => {const assert = () => { origin.assert(token); assertActive?.() }assert()@@ -113,7 +113,7 @@ export function useUpdatePostTags() {&& next.threadId === args.threadId && next.openerMessageId === args.openerMessageId})}, [queryClient])- const native = useMutation<{ tags: string[] }, Error, Intent>({+ const native = useMutation<{ tags: string[] }, Error, Intent>({ meta: { observabilityAction: "forum.tags.update" },mutationKey: ["community", "forum-tag-command"], gcTime: 0,mutationFn: async (args) => {const registry = origin.registry!, assert = () => { origin.assert(args.original); args.view(); args.assertActive?.() }@@ -202,7 +202,7 @@ export function useDeleteForumThread() {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()const source = useCommunityViewSource("forum-post-delete")type Intent = DeleteForumThreadArgs & { original: ReturnType<typeof origin.begin>["token"]; view: ReturnType<typeof source.capture>; resources: Query[] }- const native = useMutation<void, Error, Intent>({+ const native = useMutation<void, Error, Intent>({ meta: { observabilityAction: "forum.thread.delete" },mutationKey: ["community", "forum-post-delete"], gcTime: 0,scope: { id: "community-forum-post-commands" },mutationFn: async (args) => {diff --git a/src/web/src/hooks/community/mutations/friends.ts b/src/web/src/hooks/community/mutations/friends.tsindex 249b34e5f..5053f8215 100644--- a/src/web/src/hooks/community/mutations/friends.ts+++ b/src/web/src/hooks/community/mutations/friends.ts@@ -1,4 +1,5 @@"use client"+import { resolveActionName } from "@/lib/observability/actions"import { useQueryClient } from "@tanstack/react-query"import { useCommunityCommandMutation } from "../use-community-command-mutation"@@ -18,7 +19,7 @@ type Command = { path: string; method: "POST" | "DELETE"; body?: string; friendsfunction useFriendCommand<Args extends object>(action: string, build: (args: Args) => Command) {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()- return useCommunityCommandMutation<void, Error, Args>(origin, {+ return useCommunityCommandMutation<void, Error, Args>(origin, { meta: { observabilityAction: resolveActionName("friend.command", { kind: action }) },mutationKey: action === "accept" || action === "reject" ? ["community", "friend-request", action] : ["community", "friends", action],gcTime: action === "accept" || action === "reject" ? Infinity : 0,onMutate: (args) => {diff --git a/src/web/src/hooks/community/mutations/invites.ts b/src/web/src/hooks/community/mutations/invites.tsindex 88ab2b504..17850c82d 100644--- a/src/web/src/hooks/community/mutations/invites.ts+++ b/src/web/src/hooks/community/mutations/invites.ts@@ -16,7 +16,7 @@ type ResolveInviteArgs = { currentUserId: string; assert: OriginalView }export function useResolveOrCreateInvite(serverId: string) {const client = useQueryClient(), origin = useCommunityMutationOrigin()type Intent = ResolveInviteArgs & { original: ReturnType<typeof origin.begin>["token"] }- const native = useMutation({+ const native = useMutation({ meta: { observabilityAction: "server.invite.resolve" },mutationKey: ["community", "invite-resolve", serverId],scope: { id: "community-invite-command" },gcTime: 0,@@ -55,7 +55,7 @@ export type RevokeInviteArgs = { serverId: string; code: string; assertActive?:export function useRevokeInvite() {const client = useQueryClient(), origin = useCommunityMutationOrigin()type Intent = RevokeInviteArgs & { original: ReturnType<typeof origin.begin>["token"]; resource: Query | undefined }- const native = useMutation({+ const native = useMutation({ meta: { observabilityAction: "server.invite.revoke" },mutationKey: ["community", "invite-revoke"],scope: { id: "community-invite-command" }, gcTime: 0,mutationFn: async ({ serverId, code, original, resource, assertActive }: Intent) => {diff --git a/src/web/src/hooks/community/mutations/members.ts b/src/web/src/hooks/community/mutations/members.tsindex e99e9fcbb..bc26abbba 100644--- a/src/web/src/hooks/community/mutations/members.ts+++ b/src/web/src/hooks/community/mutations/members.ts@@ -16,7 +16,7 @@ export type KickMemberArgs = { serverId: string; memberId: string; assertActive?function useMemberCommand<TInput extends KickMemberArgs>(kind: "role" | "kick") {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()type Intent = { kind: typeof kind; input: SetMemberRoleArgs | KickMemberArgs; original: ReturnType<typeof origin.begin>["token"]; resources: Query[] }- const native = useMutation({+ const native = useMutation({ meta: { observabilityAction: "server.member.command" },mutationKey: ["community", "member-command"], scope: { id: "community-member-command" }, gcTime: 0,mutationFn: async ({ kind, input, original, resources }: Intent) => {origin.assert(original)diff --git a/src/web/src/hooks/community/mutations/message-memberships.ts b/src/web/src/hooks/community/mutations/message-memberships.tsindex c9c4a439c..4785a0682 100644--- a/src/web/src/hooks/community/mutations/message-memberships.ts+++ b/src/web/src/hooks/community/mutations/message-memberships.ts@@ -17,7 +17,7 @@ function current(assert?: OriginalView) { try { assert?.(); return true } catchfunction usePinCommand(action: "pin" | "unpin") {const origin = useCommunityMutationOrigin(), client = useQueryClient()type Intent = PinMessageArgs & { original: ReturnType<typeof origin.begin>["token"]; resource: Query | undefined }- const native = useMutation<void, Error, Intent>({+ const native = useMutation<void, Error, Intent>({ meta: { observabilityAction: action === "pin" ? "message.pin" : "message.unpin" },mutationKey: ["community", "pin-command", action], scope: { id: "community-pin-commands" }, gcTime: 0,mutationFn: async ({ channelId, messageId, original, resource, assertActive }) => {const assert = () => { origin.assert(original); assertActive?.() }@@ -44,7 +44,7 @@ export function useUnpinMessage() { return usePinCommand("unpin") }function useMarkCommand<T extends { messageId: string; channelId?: string; assertActive?: OriginalView }>(marked: boolean) {const origin = useCommunityMutationOrigin(), client = useQueryClient()type Intent = T & { original: ReturnType<typeof origin.begin>["token"]; resources: Array<Query> }- const native = useMutation<void, Error, Intent>({+ const native = useMutation<void, Error, Intent>({ meta: { observabilityAction: marked ? "message.mark" : "message.unmark" },mutationKey: ["community", "mark-command", marked], scope: { id: "community-mark-commands" }, gcTime: 0,mutationFn: async ({ messageId, channelId, original, resources, assertActive }) => {const assert = () => { origin.assert(original); assertActive?.() }diff --git a/src/web/src/hooks/community/mutations/message-reactions.ts b/src/web/src/hooks/community/mutations/message-reactions.tsindex 164c6fb2f..de4486597 100644--- a/src/web/src/hooks/community/mutations/message-reactions.ts+++ b/src/web/src/hooks/community/mutations/message-reactions.ts@@ -26,7 +26,7 @@ function useReactionIntent(intent: "toggle" | "add") {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()const assert = (args: Intent) => { origin.assert(args.token); args.assertActive?.() }const pending = useCallback((args: ReactionArgs) => queryClient.getMutationCache().findAll({ mutationKey: key, status: "pending", predicate: (mutation) => same(mutation.state.variables as Intent, args) }).map((mutation) => mutation.state.variables as Intent), [queryClient])- const mutation = useMutation<void, Error, Intent>({+ const mutation = useMutation<void, Error, Intent>({ meta: { observabilityAction: intent === "add" ? "message.reaction.add" : "message.reaction.toggle" },mutationKey: key, scope: { id: "community-reaction-commands" }, gcTime: 0,onMutate: async (args) => {await origin.registry?.readydiff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex fe7395884..04a211e7e 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -76,7 +76,7 @@ export function useEditMessage() {const origin = useCommunityMutationOrigin()const queryClient = useQueryClient()type Intent = EditMessageArgs & { original: ReturnType<typeof origin.begin>["token"] }- const native = useMutation<void, Error, Intent>({+ const native = useMutation<void, Error, Intent>({ meta: { observabilityAction: "message.edit" },scope: { id: "community-message-field-commands" },mutationFn: async ({ channelId, messageId, content, original: token, assertActive }) => {origin.assert(token); assertActive?.()@@ -211,7 +211,7 @@ export function useSendMessage() {SendMessageResult,Error,Intent- >({+ >({ meta: { observabilityAction: "channel.message.send" },mutationFn: async ({ channelId, content, replyToId, replyTo, mentionType, attachments, nonce, original: token, assertActive }) => {origin.assert(token); assertActive?.()// Server receives only the attachment IDS (reserve-by-id); the rest of the@@ -323,7 +323,7 @@ export function useSendDmMessage() {SendMessageResult,Error,Intent- >({+ >({ meta: { observabilityAction: "dm.message.send" },mutationFn: async ({ dmId, content, replyToId, replyTo, attachments, nonce, original: token, assertActive }) => {origin.assert(token); assertActive?.()const attachmentIds = attachments?.map((a) => a.id)@@ -413,7 +413,7 @@ export type CreateThreadResult = { id: string }export function useCreateThread() {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()type Intent = CreateThreadArgs & { original: ReturnType<typeof origin.begin>["token"]; resource: ReturnType<ReturnType<typeof queryClient.getQueryCache>["find"]> }- const native = useMutation<CreateThreadResult, Error, Intent>({+ const native = useMutation<CreateThreadResult, Error, Intent>({ meta: { observabilityAction: "message.thread.create" },mutationFn: async (args) => {const token = args.originalorigin.assert(token); args.assertActive?.()@@ -448,7 +448,7 @@ export function useMarkAllInboxRead() {snapshot?: AttentionOptimisticSnapshot}type Original = ReturnType<typeof origin.begin>["token"]- const mutation = useMutation<DomainResult[], Error, Original, MarkAllContext>({+ const mutation = useMutation<DomainResult[], Error, Original, MarkAllContext>({ meta: { observabilityAction: "inbox.read_all" },scope: { id: "community-inbox-read-all" },mutationFn: async (original) => {const requests = [@@ -558,7 +558,7 @@ export function useDeleteMention() {token?: AccountUnreadDismissTokenattentionSnapshot?: AttentionItemsOptimisticSnapshot}- >({+ >({ meta: { observabilityAction: "mention.dismiss" },scope: { id: "community-mention-delete" },mutationFn: async ({ input: { mentionId }, original }) => {return origin.request<{ revision: number }>(original,diff --git a/src/web/src/hooks/community/mutations/notifications.ts b/src/web/src/hooks/community/mutations/notifications.tsindex 842f536a1..8d0c28d2e 100644--- a/src/web/src/hooks/community/mutations/notifications.ts+++ b/src/web/src/hooks/community/mutations/notifications.ts@@ -20,7 +20,7 @@ function useNotificationCommand(kind: "server" | "channel") {const source = useCommunityViewSource("notification-setting:" + kind)type Input = SetServerNotifLevelArgs | SetChannelNotifArgstype Intent = { input: Input; id: string; original: ReturnType<typeof origin.begin>["token"]; view: ReturnType<typeof source.capture>; resources: Query[] }- const native = useMutation<void, Error, Intent>({+ const native = useMutation<void, Error, Intent>({ meta: { observabilityAction: kind === "server" ? "notification.server.update" : "notification.channel.update" },mutationKey: ["community", "notification-setting-command", kind],scope: { id: "community-notification-setting-commands" },gcTime: 0,diff --git a/src/web/src/hooks/community/mutations/profile.ts b/src/web/src/hooks/community/mutations/profile.tsindex a6a2d911a..fc63c15ee 100644--- a/src/web/src/hooks/community/mutations/profile.ts+++ b/src/web/src/hooks/community/mutations/profile.ts@@ -37,7 +37,7 @@ export type UpdateProfileResult = {export function useUpdateProfile() {const origin = useCommunityMutationOrigin()type Intent = UpdateProfileArgs & { original: ReturnType<typeof origin.begin>["token"] }- const native = useMutation<UpdateProfileResult, Error, Intent>({+ const native = useMutation<UpdateProfileResult, Error, Intent>({ meta: { observabilityAction: "profile.update" },mutationKey: ["community", "profile-command"], scope: { id: "community-profile-command" }, gcTime: 0,mutationFn: async ({ original, assertActive, ...patch }) => {origin.assert(original); assertActive?.()@@ -68,7 +68,7 @@ export type UploadUserAvatarResult = { url: string; avatarVersion: number }export function useUploadUserAvatar() {const origin = useCommunityMutationOrigin()type Intent = UploadUserAvatarArgs & { original: ReturnType<typeof origin.begin>["token"] }- const native = useMutation<UploadUserAvatarResult, Error, Intent>({+ const native = useMutation<UploadUserAvatarResult, Error, Intent>({ meta: { observabilityAction: "profile.avatar.upload" },mutationKey: ["community", "profile-avatar-command"], scope: { id: "community-profile-command" }, gcTime: 0,mutationFn: async ({ file, original, assertActive }) => {origin.assert(original); assertActive?.()diff --git a/src/web/src/hooks/community/mutations/server-rail.ts b/src/web/src/hooks/community/mutations/server-rail.tsindex fff3c820f..8772e0178 100644--- a/src/web/src/hooks/community/mutations/server-rail.ts+++ b/src/web/src/hooks/community/mutations/server-rail.ts@@ -17,7 +17,7 @@ const mutationKey = ["community", "server-rail", "change"] as constexport function useServerRailCommit() {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()const pending = useIsMutating({ mutationKey, exact: true }) > 0- const mutation = useCommunityCommandMutation<ServerRailCommitResponse, Error, ServerRailCommitArgs>(origin, {+ const mutation = useCommunityCommandMutation<ServerRailCommitResponse, Error, ServerRailCommitArgs>(origin, { meta: { observabilityAction: "server.rail.reorder" },mutationKey,scope: { id: "server-rail-commit" },mutationFn: async ({ commands, assertUI, original, resources }) => {diff --git a/src/web/src/hooks/community/mutations/servers.ts b/src/web/src/hooks/community/mutations/servers.tsindex b53c7c3e5..509d434d3 100644--- a/src/web/src/hooks/community/mutations/servers.ts+++ b/src/web/src/hooks/community/mutations/servers.ts@@ -33,7 +33,7 @@ export type CreateServerResult = { server: { id: string } }export function useCreateServer() {const origin = useCommunityMutationOrigin()const queryClient = useQueryClient()- return useCommunityCommandMutation<CreateServerResult, Error, CreateServerArgs>(origin, {+ return useCommunityCommandMutation<CreateServerResult, Error, CreateServerArgs>(origin, { meta: { observabilityAction: "server.create" },mutationFn: async ({ name, original }) => {return origin.request<CreateServerResult>(original, "/api/community/servers", {method: "POST",@@ -56,7 +56,7 @@ export type JoinServerResult = { serverId: string }export function useJoinServer() {const origin = useCommunityMutationOrigin()const queryClient = useQueryClient()- return useCommunityCommandMutation<JoinServerResult, Error, JoinServerArgs>(origin, {+ return useCommunityCommandMutation<JoinServerResult, Error, JoinServerArgs>(origin, { meta: { observabilityAction: "server.join" },mutationFn: async ({ inviteCode, original }) => {let token = inviteCode.trim()try {@@ -101,7 +101,7 @@ export function useLeaveServer() {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()const unreadProjection = getActiveAccountUnreadProjection(queryClient)const assertLeaveSuccess = useCallback((args: CommunityCommandArgs<LeaveServerArgs>) => origin.assertOwner(args.original), [origin])- return useCommunityCommandMutation<void, Error, LeaveServerArgs, { token: AccountUnreadScopeToken; proof: CommunityLiveSnapshotToken }>(origin, {+ return useCommunityCommandMutation<void, Error, LeaveServerArgs, { token: AccountUnreadScopeToken; proof: CommunityLiveSnapshotToken }>(origin, { meta: { observabilityAction: "server.leave" },scope: { id: "community-server-membership" },onMutate: async (args) => {const token = args.original@@ -142,7 +142,7 @@ export function useLeaveServer() {export function useDeleteServer(callbacks: DeleteServerCallbacks) {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()const unreadProjection = getActiveAccountUnreadProjection(queryClient)- return useCommunityCommandMutation<void, Error, DeleteServerArgs, { token: AccountUnreadScopeToken; proof: CommunityLiveSnapshotToken } & DeleteServerCallbacks>(origin, {+ return useCommunityCommandMutation<void, Error, DeleteServerArgs, { token: AccountUnreadScopeToken; proof: CommunityLiveSnapshotToken } & DeleteServerCallbacks>(origin, { meta: { observabilityAction: "server.delete" },scope: { id: "community-server-membership" },onMutate: async (args) => {const token = args.original@@ -196,7 +196,7 @@ export type UpdateServerArgs = {export function useUpdateServer() {const origin = useCommunityMutationOrigin()const queryClient = useQueryClient()- return useCommunityCommandMutation<void, Error, UpdateServerArgs>(origin, {+ return useCommunityCommandMutation<void, Error, UpdateServerArgs>(origin, { meta: { observabilityAction: "server.update" },scope: { id: "community-server-fields" },mutationFn: async (args) => {const original = args.original, registry = origin.registry@@ -239,7 +239,7 @@ export type UploadServerIconResult = { url: string }export function useUploadServerIcon() {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()- return useCommunityCommandMutation<UploadServerIconResult, Error, UploadServerIconArgs>(origin, {+ return useCommunityCommandMutation<UploadServerIconResult, Error, UploadServerIconArgs>(origin, { meta: { observabilityAction: "server.icon.upload" },scope: { id: "community-server-fields" },mutationFn: async (args) => {const { serverId, file, original } = argsdiff --git a/src/web/src/hooks/community/mutations/uploads.ts b/src/web/src/hooks/community/mutations/uploads.tsindex 836730cdd..862d96a1d 100644--- a/src/web/src/hooks/community/mutations/uploads.ts+++ b/src/web/src/hooks/community/mutations/uploads.ts@@ -124,7 +124,7 @@ function uploadPath(target: UploadTarget): string | null {export function useUploadFile(options: { gcTime?: number } = {}) {const origin = useCommunityMutationOrigin()type Intent = UploadFileArgs & { original: ReturnType<typeof origin.begin>["token"] }- const native = useMutation<UploadFileResult, Error, Intent>({+ const native = useMutation<UploadFileResult, Error, Intent>({ meta: { observabilityAction: "attachment.upload" },mutationKey: ["community", "file-upload"], gcTime: options.gcTime ?? 0,mutationFn: async ({ target, file, thumbnailBlob, width, height, original, assertActive }) => {origin.assert(original); assertActive?.()diff --git a/src/web/src/hooks/community/observability-consumers.dom.test.tsx b/src/web/src/hooks/community/observability-consumers.dom.test.tsxnew file mode 100644index 000000000..995601a9b--- /dev/null+++ b/src/web/src/hooks/community/observability-consumers.dom.test.tsx@@ -0,0 +1,56 @@+import { createElement, type PropsWithChildren } from "react"+import { beforeEach, expect, it, vi } from "vitest"+import { act, renderHook, waitFor } from "@/test/react-dom-harness"+import { CommunityTestProvider } from "@/test/community-owner-fixture"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { useMachines } from "./use-machines"+import { useCreateOrGetDm } from "./mutations/dm"+import { useResolveOrCreateInvite } from "./mutations/invites"+import { useMarkMessage, useUnmarkMessage } from "./mutations/message-memberships"+import { useUploadUserAvatar } from "./mutations/profile"+import { useJoinServer } from "./mutations/servers"+import { useSetBotNotificationSetting } from "./use-notification-settings"+import { communityKeys } from "@/lib/query-keys"+import { tagValue, viewEvidence } from "@/lib/observability/data-source"+import { configureTelemetry, retireTelemetry } from "@/lib/observability/telemetry"++const api = vi.fn()+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => api(...args), toastApiError: vi.fn() }))+beforeEach(() => { api.mockReset() })+it("projects the native machines query and retains its actual cache evidence", async () => {+ const { client, registry } = await createCommunityQueryOwner()+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client, registry }, children)+ configureTelemetry({ session_id: "machines-session" }, true)+ try {+ const rendered = renderHook(() => useMachines({ enabled: false }), { wrapper })+ expect(rendered.result.current.machines).toEqual([])+ const data = { machines: [{ id: "machine-a", hostname: "host" }] }+ tagValue(client, data, "network")+ act(() => client.setQueryData(communityKeys.machines(), data))+ await waitFor(() => expect(rendered.result.current.machines).toBe(data.machines))+ expect(viewEvidence(rendered.result.current.machines).source).toBe("network")+ expect(api).not.toHaveBeenCalled()+ rendered.unmount()+ } finally { retireTelemetry() }+})+it("preserves exact native mutation actions and original scoped requests for consumer commands", async () => {+ const { client, registry } = await createCommunityQueryOwner()+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client, registry }, children)+ api.mockImplementation(async (path: string, options?: RequestInit) => path.endsWith("/invites") ? options?.method === "POST" ? { invite: { token: "invite-a", uses: 0, maxUses: null, expiresAt: null } } : { invites: [] } : path.endsWith("/avatar") ? { url: "/avatar.png", avatarVersion: 2 } : path.endsWith("/join") ? { serverId: "server-a" } : { conversation: { id: "dm-a" } })+ const rendered = renderHook(() => ({ dm: useCreateOrGetDm(), invite: useResolveOrCreateInvite("server-a"), mark: useMarkMessage(), unmark: useUnmarkMessage(), avatar: useUploadUserAvatar(), join: useJoinServer(), notification: useSetBotNotificationSetting() }), { wrapper })+ const assert = Object.assign(vi.fn(), { signal: new AbortController().signal })+ await act(async () => {+ expect(await rendered.result.current.dm.mutateAsync({ userId: "peer-a" })).toEqual({ conversation: { id: "dm-a" } })+ expect(await rendered.result.current.invite.mutateAsync({ currentUserId: "viewer", assert })).toMatchObject({ token: "invite-a" })+ await rendered.result.current.mark.mutateAsync({ messageId: "message-a", channelId: "channel-a" })+ await rendered.result.current.unmark.mutateAsync({ messageId: "message-a" })+ expect(await rendered.result.current.avatar.mutateAsync({ file: new File(["avatar"], "avatar.png") })).toMatchObject({ avatarVersion: 2 })+ await rendered.result.current.join.mutateAsync({ inviteCode: "invite-a" })+ await rendered.result.current.notification.mutateAsync({ botId: "bot-a", scope: { kind: "channel", id: "channel-a" }, level: "mentions" })+ })+ expect(client.getMutationCache().getAll().map(mutation => mutation.options.meta?.observabilityAction).sort()).toEqual(["bot.notification.update", "dm.open", "message.mark", "message.unmark", "profile.avatar.upload", "server.invite.resolve", "server.join"])+ expect(api.mock.calls.every(([, options]) => options.authenticationAccount === "viewer" && typeof options.assertActive === "function")).toBe(true)+ expect(api).toHaveBeenCalledWith("/api/community/messages/message-a/marks", expect.objectContaining({ method: "PUT", body: JSON.stringify({ channelId: "channel-a" }) }))+ expect(api).toHaveBeenCalledWith("/api/community/bots/bot-a/notifications/channel/channel-a", expect.objectContaining({ method: "PUT", body: JSON.stringify({ level: "mentions" }) }))+ rendered.unmount()+})diff --git a/src/web/src/hooks/community/use-account-sign-out.ts b/src/web/src/hooks/community/use-account-sign-out.tsindex a4f2f124f..d9d58a265 100644--- a/src/web/src/hooks/community/use-account-sign-out.ts+++ b/src/web/src/hooks/community/use-account-sign-out.ts@@ -17,7 +17,7 @@ export function useAccountSignOut() {assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)return { registry, token, authenticationGeneration: registry.authenticationView.get().generation }}, [queryClient, registry])- const native = useMutation({ mutationKey: ["community", "sign-out"], scope: { id: "account-sign-out" }, gcTime: 0, mutationFn: async ({ registry, token }: ReturnType<typeof capture>) => {+ const native = useMutation({ meta: { observabilityAction: "account.sign_out" }, mutationKey: ["community", "sign-out"], scope: { id: "account-sign-out" }, gcTime: 0, mutationFn: async ({ registry, token }: ReturnType<typeof capture>) => {const assertActive = () => assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)assertActive()const generation = registry.authenticationView.get().generationdiff --git a/src/web/src/hooks/community/use-billing.ts b/src/web/src/hooks/community/use-billing.tsindex c7a5a5f68..072ae1686 100644--- a/src/web/src/hooks/community/use-billing.ts+++ b/src/web/src/hooks/community/use-billing.ts@@ -1,5 +1,7 @@"use client"+import { useObservedQueryRegion } from "@/lib/observability/query-regions"+import { emitTelemetry } from "@/lib/observability/telemetry"import { useEffect, useLayoutEffect, useCallback, useMemo } from "react"import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"import { BillingSummarySchema, BillingRedirectResponseSchema } from "@alook/shared"@@ -71,6 +73,7 @@ export function useBilling(returnFrom: BillingReturn = null, enabled = false, apstaleTime: 30_000, refetchOnWindowFocus: true,refetchInterval: state.polling ? 2_000 : false, retry: false,})+ useObservedQueryRegion("billing", query, undefined, enabled)const invalidateDependents = useCallback(() => {if (!registry) returnvoid qc.invalidateQueries({ queryKey: communityKeys.bots() })@@ -96,6 +99,7 @@ export function useBilling(returnFrom: BillingReturn = null, enabled = false, apreturn}capture().assert()+ emitTelemetry("business.result", { action_name: "billing_return", phase: "auth", outcome: returnFrom === "cancel" ? "cancelled" : "observed", capability: "limited" })ui.setState((state) => ({ ...state, handledReturn: returnFrom, returnComplete: false, returnStartedAt: Date.now(), polling: returnFrom !== "cancel" }))void qc.invalidateQueries({ queryKey: key, exact: true })invalidateDependents()@@ -118,10 +122,11 @@ export function useBilling(returnFrom: BillingReturn = null, enabled = false, apif (previous !== null && previous !== projection) invalidateDependents()const settled = returnFrom === "checkout" && !query.data.isFounder && query.dataUpdatedAt >= ui.get().returnStartedAt&& query.data.subscription?.status === "active" && query.data.subscription.plan.id === query.data.plan.id+ if (settled && !ui.get().returnComplete) emitTelemetry("business.result", { action_name: "billing_return", outcome: "success", phase: "primary" })ui.setState((state) => ({ ...state, observedPlan: projection, ...(settled ? { returnComplete: true, polling: false } : {}) }))}, [enabled, returnFrom, query.data, query.dataUpdatedAt, qc, ui, capture, registry, invalidateDependents])type Original = ReturnType<typeof captureView>- const redirect = useMutation({+ const redirect = useMutation({ meta: { observabilityAction: "billing.redirect" },mutationKey: [...key, "redirect"], retry: false,mutationFn: async ({ action, original }: { action: BillingAction; original: Original }) => {original.assertView()@@ -159,7 +164,7 @@ export function useBilling(returnFrom: BillingReturn = null, enabled = false, apvoid query.refetch({ cancelRefetch: false })}}- const cancelMutation = useMutation({+ const cancelMutation = useMutation({ meta: { observabilityAction: "billing.change.cancel" },mutationKey: [...key, "cancel-change"], retry: false,mutationFn: async (original: Original) => {original.assertView()diff --git a/src/web/src/hooks/community/use-bot-bug-report.ts b/src/web/src/hooks/community/use-bot-bug-report.tsindex 541a2d82c..bb27b38a0 100644--- a/src/web/src/hooks/community/use-bot-bug-report.ts+++ b/src/web/src/hooks/community/use-bot-bug-report.ts@@ -271,7 +271,7 @@ export function useBotBugReport({ agentId, open }: { agentId: string; open: boolconst attempt = useCreateStore({ nonce: null as string | null, expiredReportId: null as string | null })const intent = useSelector(attempt, (state) => state)const createKey = ["community", "bug-report-create", agentId] as const- const creation = useMutation({+ const creation = useMutation({ meta: { observabilityAction: "bot.bug_report.submit" },mutationKey: createKey,mutationFn: async ({ nonce, token, assert }: { nonce: string; token: ReturnType<typeof origin.begin>["token"]; assert: ReturnType<typeof source.capture> }) => {assert()diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.tsindex 6542adbe5..b066805b7 100644--- a/src/web/src/hooks/community/use-bots.ts+++ b/src/web/src/hooks/community/use-bots.ts@@ -1,5 +1,7 @@"use client"+import { deriveView, valueEvidence, viewEvidence } from "@/lib/observability/data-source"+import { resolveActionName } from "@/lib/observability/actions"import { useQuery,useMutation,useQueryClient,type UseQueryResult,type Query,type QueryKey,type MutateOptions } from "@tanstack/react-query"import type { ApiRequestOptions } from "@/lib/api/client"import {@@ -84,6 +86,7 @@ function botProfilePatch(bot: Pick<BotSummary, "id" | "name" | "image" | "avatar}export function useBots(): UseQueryResult<BotsResourceResponse> & { bots: BotSummary[] } {+ const queryClient = useQueryClient()const query = useQuery({queryKey: communityKeys.bots(),queryFn: async ({ client, signal }): Promise<BotsResourceResponse> => {@@ -94,8 +97,9 @@ export function useBots(): UseQueryResult<BotsResourceResponse> & { bots: BotSumconst profiles = useCanonicalProfilesByUserId(query.data?.bots.map((bot) => bot.id) ?? [])const bots = useMemo(() => (query.data?.bots ?? []).map((bot) => {const profile = readCommunityProfile(profiles.get(bot.id), bot.id)- return { ...bot, name: profile.name, description: profile.aboutMe, image: profile.avatar, avatarVersion: profile.avatarVersion, presence: profile.presence }- }), [profiles, query.data?.bots])+ return deriveView({ ...bot, name: profile.name, description: profile.aboutMe, image: profile.avatar, avatarVersion: profile.avatarVersion, presence: profile.presence }, [valueEvidence(queryClient, query.data), viewEvidence(profile)])+ }), [profiles, query.data, queryClient])+ deriveView(bots, [valueEvidence(queryClient, query.data), ...bots.map(viewEvidence)])return { ...query, bots }}@@ -117,7 +121,7 @@ const noBotKeys = () => []function useBotCommand<TInput extends BotViewInput, TResult>(kind: string, execute: (input: TInput, context: BotCommandContext) => Promise<TResult>, keys: (input: TInput) => QueryKey[]) {const client = useQueryClient(), origin = useBotMutationOrigin()type Intent = { input: TInput; original: ReturnType<typeof origin.begin>["token"]; resources: Query[] }- const native = useMutation<TResult, Error, Intent>({+ const native = useMutation<TResult, Error, Intent>({ meta: { observabilityAction: resolveActionName("bot.command", { kind }) },mutationKey: [...communityKeys.bots(), kind],scope: { id: "community-bot-command" },gcTime: 0,diff --git a/src/web/src/hooks/community/use-channel-members.ts b/src/web/src/hooks/community/use-channel-members.tsindex d6e24b985..a0a92d208 100644--- a/src/web/src/hooks/community/use-channel-members.ts+++ b/src/web/src/hooks/community/use-channel-members.ts@@ -1,5 +1,7 @@"use client"+import { deriveView, valueEvidence, viewEvidence } from "@/lib/observability/data-source"+import { useNativeMutationFacade } from "@/hooks/use-native-mutation-facade"import { useCallback,useMemo } from "react"@@ -102,14 +104,16 @@ export function useChannelMembers(channelId: string, enabled = true, serverId?:const member = byUser.get(participant.userId)if (!member?.memberId) return []const profile = readCommunityProfile(profiles.get(participant.userId), participant.userId)- return [{ id: member.memberId, userId: participant.userId, name: member.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: member.role as CommunityRole, sub: "", status: member.viewer ? "online" : profile.presence, statusEmoji: profile.statusEmoji ?? null, statusText: profile.statusText ?? "", source: participant.source ?? "explicit", isCreator: participant.isCreator ?? false }]+ return [deriveView({ id: member.memberId, userId: participant.userId, name: member.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: member.role as CommunityRole, sub: "", status: member.viewer ? "online" : profile.presence, statusEmoji: profile.statusEmoji ?? null, statusText: profile.statusText ?? "", source: participant.source ?? "explicit", isCreator: participant.isCreator ?? false }, [viewEvidence(member), viewEvidence(participant), viewEvidence(profile)])]})}, [profiles, memberships, roster])+ deriveView(members, [valueEvidence(client, query.data), ...members.map(viewEvidence)], members.length)const data = useMemo(() => query.data ? { members } : undefined, [query.data, members])return { ...query, data, members } as UseQueryResult<{ members: ChannelMember[] }> & { members: ChannelMember[] }}export function useAddableMembers(serverId: string, channelId: string, enabled = true): UseQueryResult<{ members: AddableMember[] }> & { members: AddableMember[] } {+ const client = useQueryClient()const active = enabled && !!serverId && !!channelIdconst query = useQuery({ queryKey: communityKeys.channelAddableMembers(channelId), queryFn: (context) => addableMembersQueryFn(serverId, channelId, context), enabled: active, subscribed: active })const ids = useMemo(() => query.data?.members ?? [], [query.data?.members])@@ -126,6 +130,7 @@ export function useAddableMembers(serverId: string, channelId: string, enabled =return [{ userId: identity.userId, name: member.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion }]})}, [ids, profiles, memberships, roster])+ deriveView(members, [valueEvidence(client, query.data), ...members.map(viewEvidence)], members.length)const data = useMemo(() => query.data ? { members } : undefined, [query.data, members])return { ...query, data, members } as UseQueryResult<{ members: AddableMember[] }> & { members: AddableMember[] }}@@ -136,7 +141,7 @@ export function useChannelMemberCommand(channelId: string, kind: "add" | "removeconst origin = useCommunityMutationOrigin(), client = useQueryClient()const source = useCommunityViewSource(`channel-member-command:${channelId}`)type Intent = ChannelMemberCommandInput & { view: ReturnType<typeof source.capture>; original: ReturnType<typeof origin.begin>["token"]; resources: ReturnType<ReturnType<typeof client.getQueryCache>["findAll"]> }- const native = useMutation({+ const native = useMutation({ meta: { observabilityAction: kind === "add" ? "channel.member.add" : "channel.member.remove" },mutationKey: ["community", "channel-member-command", channelId], scope: { id: "channel-member-command:" + channelId },mutationFn: async ({ userId, original, resources, assertActive, view }: Intent) => {const assert = Object.assign(() => { origin.assert(original); view(); assertActive?.() }, { signal: assertActive?.signal ?? view.signal })diff --git a/src/web/src/hooks/community/use-community-command-mutation.ts b/src/web/src/hooks/community/use-community-command-mutation.tsindex af7fe1627..f80958806 100644--- a/src/web/src/hooks/community/use-community-command-mutation.ts+++ b/src/web/src/hooks/community/use-community-command-mutation.ts@@ -12,7 +12,7 @@ export function communityCommandInput<Input extends object>({ original: _origina}export function useCommunityCommandMutation<Data = unknown, Error = globalThis.Error, Input extends object = object, Result = unknown>(origin: Origin, options: UseMutationOptions<Data, Error, CommunityCommandArgs<Input>, Result>, assertSuccess?: (args: CommunityCommandArgs<Input>) => void) {- const native = useMutation<Data, Error, CommunityCommandArgs<Input>, Result>({ gcTime: 0, ...options,+ const native = useMutation<Data, Error, CommunityCommandArgs<Input>, Result>({ meta: { observabilityAction: "community.command" }, gcTime: 0, ...options,onSuccess: async (data, args, result, context) => { try { origin.assert(args.original) } catch { return } await options.onSuccess?.(data, args, result, context) },onError: async (error, args, result, context) => { try { origin.assert(args.original) } catch { return } await options.onError?.(error, args, result, context) },onSettled: async (data, error, args, result, context) => { try { origin.assert(args.original) } catch { return } await options.onSettled?.(data, error, args, result, context) },diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.tsindex 569fb7dca..48fdbb529 100644--- a/src/web/src/hooks/community/use-dms.ts+++ b/src/web/src/hooks/community/use-dms.ts@@ -1,4 +1,6 @@"use client"++import { deriveView, viewEvidence } from "@/lib/observability/data-source"import { getCommunityDbRegistry } from "@/lib/community-db/collections"@@ -144,6 +146,7 @@ export function useDms(enabled = true): UseQueryResult<{ ids: string[] }> & { dm}}))}, [attentionScopes, dbDms, profilesByUserId])+ deriveView(dms, [viewEvidence(dbDms), viewEvidence(attentionScopes), ...dms.map(dm => viewEvidence(profilesByUserId.get(dm.userId)))])return {...query,dms,diff --git a/src/web/src/hooks/community/use-forum-feed.pending-tags.dom.test.ts b/src/web/src/hooks/community/use-forum-feed.pending-tags.dom.test.tsnew file mode 100644index 000000000..6da0b4d57--- /dev/null+++ b/src/web/src/hooks/community/use-forum-feed.pending-tags.dom.test.ts@@ -0,0 +1,81 @@+import { createElement, type PropsWithChildren } from "react"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { act, renderHook, waitFor } from "@/test/react-dom-harness"+import { CommunityTestProvider } from "@/test/community-owner-fixture"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { communityKeys } from "@/lib/query-keys"+import { useForumFeed } from "./use-forum-feed"+import { useUpdatePostTags } from "./mutations/forum"+import type { ForumFeedTransportPage } from "./forum-feed-window"++const api = vi.hoisted(() => vi.fn())+vi.mock("@/lib/api/client", () => ({ apiFetch: api, toastApiError: vi.fn() }))+beforeEach(() => { api.mockReset(); localStorage.clear() })++async function setup(selected = "archived") {+ const owner = await createCommunityQueryOwner()+ let backendTags = ["bug", selected]+ let resolve!: (value: { tags: string[] }) => void, reject!: (error: Error) => void+ const held = new Promise<{ tags: string[] }>((done, fail) => { resolve = done; reject = fail })+ const page = (): ForumFeedTransportPage => ({+ serverId: "server_1", parentType: "forum", hasMore: false,+ threads: [{ id: "post", name: "Post", creatorId: "author", messageCount: 1, parentMessageId: "opener", createdAt: "2026-10-04T00:00:00Z", activityAt: "2026-10-04T00:00:00Z", lastMessageAt: null }],+ included: { parentMessages: [{ id: "opener", channelId: "forum_1", seq: 1, content: "Post", authorId: "author", authorName: "Author", authorImage: null, authorAvatarVersion: 0 }], firstMessages: [], participants: [], tags: backendTags.map((tag) => ({ messageId: "opener", tag })) },+ })+ api.mockImplementation((path: string, options?: { method?: string }) => {+ if (options?.method === "PUT") return held+ if (path.endsWith("/messages/tags")) return Promise.resolve({ tags: [...backendTags] })+ if (path.includes("/threads?")) return Promise.resolve(page())+ throw new Error(`Unexpected request: ${path}`)+ })+ localStorage.setItem("alook:forum-tag:forum_1", selected)+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, retainOwner: true }, children)+ const view = renderHook(() => ({ feed: useForumFeed("server_1", "forum_1"), command: useUpdatePostTags() }), { wrapper })+ await waitFor(() => expect(view.result.current.feed.posts.map(({ id }) => id)).toEqual(["post"]))+ const refreshCatalog = () => owner.client.refetchQueries({ queryKey: communityKeys.forumTags("forum_1"), exact: true })+ const setTags = (tags: string[]) => { backendTags = tags }+ const begin = async (forumChannelId = "forum_1") => {+ let request!: Promise<unknown>+ act(() => { request = view.result.current.command.mutateAsync({ serverId: "server_1", forumChannelId, threadId: "post", openerMessageId: "opener", previousTags: ["bug", selected], tags: ["bug"] }).catch((error) => error) })+ await waitFor(() => expect(api.mock.calls.some(([, options]) => options?.method === "PUT")).toBe(true))+ return { request }+ }+ return { ...owner, view, refreshCatalog, setTags, resolve, reject, begin }+}++describe("Forum selection during native tag commands", () => {+ it.each(["success", "rollback"] as const)("keeps Archived selected while its last post is pending, then handles %s", async (outcome) => {+ const h = await setup()+ const { request } = await h.begin()+ await waitFor(() => expect(h.view.result.current.command.isPending).toBe(true))+ await waitFor(() => expect(h.view.result.current.feed.posts).toEqual([]))+ h.setTags(["bug"])+ await act(async () => { await h.refreshCatalog() })+ await waitFor(() => expect(h.view.result.current.feed.availableTags).toEqual(["bug"]))+ expect(h.view.result.current.feed.tag).toBe("archived")+ expect(h.view.result.current.feed.posts).toEqual([])+ expect(api.mock.calls.filter(([path]) => path.includes("/threads?")).every(([path]) => new URL(path, "https://local").searchParams.get("tag") === "archived")).toBe(true)+ if (outcome === "success") {+ await act(async () => { h.resolve({ tags: ["bug"] }); await request })+ await waitFor(() => expect(h.view.result.current.feed.tag).toBe("All"))+ await waitFor(() => expect(h.view.result.current.feed.posts.map(({ id }) => id)).toEqual(["post"]))+ expect(localStorage.getItem("alook:forum-tag:forum_1")).toBeNull()+ } else {+ h.setTags(["bug", "archived"])+ await act(async () => { await h.refreshCatalog(); h.reject(new Error("403")); await request })+ await waitFor(() => expect(h.view.result.current.command.isPending).toBe(false))+ expect(h.view.result.current.feed.tag).toBe("archived")+ await waitFor(() => expect(h.view.result.current.feed.posts.map(({ id }) => id)).toEqual(["post"]))+ }+ })++ it("still recovers a missing ordinary tag while another forum's command is pending", async () => {+ const h = await setup("removed")+ const { request } = await h.begin("forum_2")+ await waitFor(() => expect(h.view.result.current.command.isPending).toBe(true))+ h.setTags(["bug"])+ await act(async () => { await h.refreshCatalog() })+ await waitFor(() => expect(h.view.result.current.feed.tag).toBe("All"))+ await act(async () => { h.resolve({ tags: ["bug"] }); await request })+ })+})diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.tsindex 08b823426..c59541ac7 100644--- a/src/web/src/hooks/community/use-forum-feed.ts+++ b/src/web/src/hooks/community/use-forum-feed.ts@@ -1,8 +1,9 @@"use client"+import { deriveView, valueEvidence, viewEvidence } from "@/lib/observability/data-source"import { useCallback, useEffect, useMemo } from "react"import { createStore, useAtom, useCreateAtom } from "@tanstack/react-store"-import { useInfiniteQuery, useQueryClient, type Query } from "@tanstack/react-query"+import { useInfiniteQuery, useIsMutating, useQueryClient, type Query } from "@tanstack/react-query"import { compareAsciiSqliteBinary, DEFAULT_MESSAGE_PAGE_SIZE } from "@alook/shared"import { apiFetch } from "@/lib/api/client"import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"@@ -80,29 +81,34 @@ export function mapForumFeedPages(pages: ForumFeedPage[], messages: ReadonlyMap<if (byId.has(window.id)) continueconst thread = channels.get(window.id), opener = window.openerMessageId ? messages.get(window.openerMessageId) : undefinedif (!thread || !opener || thread.parentMessageId !== opener.id || !forumFeedMatchesTags(filter, thread.tags)) continue- byId.set(thread.id, {+ byId.set(thread.id, deriveView({id: thread.id, name: opener.content?.trim() ? opener.content : thread.name || "Post", messageCount: thread.messageCount ?? 0, lastMessageAt: thread.lastMessageAt ?? "",parent: { authorId: opener.authorId, authorName: opener.authorName ?? "", text: thread.preview ?? "" }, authorId: opener.authorId ?? thread.creatorId ?? "",authorAvatar: opener.authorAvatar ?? avatarInitial(opener.authorName ?? ""), authorAvatarVersion: opener.authorAvatarVersion ?? 0,openerMessageId: opener.id, ...(opener.createdAt === undefined ? {} : { openerCreatedAt: opener.createdAt }), ...(opener.seq === undefined ? {} : { parentSeq: opener.seq }), tags: thread.tags, preview: thread.preview ?? "",participants: window.participantIds.map((id) => { const profile = readCommunityProfile(profiles.get(id), id); return { id, name: profile.name, avatar: profile.avatar, avatarVersion: profile.avatarVersion } }), participantCount: thread.participantCount ?? 0,- })+ }, [viewEvidence(thread), viewEvidence(opener), ...window.participantIds.map(id => viewEvidence(profiles.get(id)))]))}return [...byId.values()].sort((a, b) => compareAsciiSqliteBinary(channels.get(b.id)?.createdAt ?? "", channels.get(a.id)?.createdAt ?? "") || compareAsciiSqliteBinary(b.id, a.id))}-export function useForumFeed(_serverId: string, channelId: string) {+export function useForumFeed(serverId: string, channelId: string) {const queryClient = useQueryClient(), messages = useCanonicalMessagesById(), channels = useCanonicalChannelsById(), profiles = useCanonicalProfilesByUserId()const readTag = () => { try { return readForumTagSelection(window.localStorage, channelId) } catch { return "All" } }const [selection, setSelection] = useAtom(useCreateAtom({ channelId, tag: readTag() }))const tag = selection.channelId === channelId ? selection.tag : readTag()const selectTag = useCallback((next: string) => { setSelection({ channelId, tag: next }); try { writeForumTagSelection(window.localStorage, channelId, next) } catch {} }, [channelId, setSelection])const tagsQuery = useForumTags(channelId, true)- useEffect(() => { if (tagsQuery.isSuccess && tag !== "All" && validateForumTagSelection(tag, tagsQuery.data.tags) === "All") selectTag("All") }, [tag, tagsQuery.isSuccess, tagsQuery.data, selectTag])+ const pendingTagCommands = useIsMutating({ mutationKey: ["community", "forum-tag-command"], exact: true, predicate: (mutation) => {+ const args = mutation.state.variables as { serverId?: string; forumChannelId?: string } | undefined+ return args?.serverId === serverId && args.forumChannelId === channelId+ } })+ useEffect(() => { if (!pendingTagCommands && tagsQuery.isSuccess && tag !== "All" && validateForumTagSelection(tag, tagsQuery.data.tags) === "All") selectTag("All") }, [pendingTagCommands, tag, tagsQuery.isSuccess, tagsQuery.data, selectTag])const selectedTag = tag === "All" ? null : tagconst queryKey = communityKeys.forumFeed(channelId, selectedTag)const query = useInfiniteQuery({ queryKey, queryFn: forumFeedPageQueryFn(channelId, selectedTag, queryClient), initialPageParam: null as string | null, getNextPageParam: (lastPage) => lastPage.hasMore ? lastPage.nextCursor : undefined,retry: conversationReadRetryPolicy(queryClient.defaultQueryOptions({ queryKey }).retry), networkMode: "always" })const posts = useMemo(() => mapForumFeedPages(query.data?.pages ?? [], messages ?? new Map(), channels, profiles, selectedTag), [query.data?.pages, messages, channels, profiles, selectedTag])+ deriveView(posts, [valueEvidence(queryClient, query.data), ...posts.map(viewEvidence)], posts.length)return { ...query, posts, tag, selectTag, availableTags: tagsQuery.data?.tags ?? [], hasMoreOlder: query.hasNextPage, isFetchingOlder: query.isFetchingNextPage, fetchOlder: () => { void query.fetchNextPage() } }}diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.tsindex 3c1ab341a..12b34de1b 100644--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts@@ -1,4 +1,5 @@"use client"+import { deriveView, valueEvidence, viewEvidence } from "@/lib/observability/data-source"import { useAtom,useCreateAtom } from "@tanstack/react-store"import { useTrustedRestoredForumProjection } from "@/lib/community-db/projections"import { getCommunityRuntime } from "@/stores/community/runtime"@@ -827,6 +828,7 @@ export function useForumSidebarThreads(return () => globalThis.clearTimeout(timeout)}, [projection.threads, retainId, serverNowMs, setClockNowMs])+ deriveView(projection.threads, [registry ? viewEvidence(canonical?.threads) : valueEvidence(queryClient, query.data), viewEvidence(attentionScopes)])return {...query,threads: projection.threads,diff --git a/src/web/src/hooks/community/use-friends.ts b/src/web/src/hooks/community/use-friends.tsindex 400f0c965..c4c49c557 100644--- a/src/web/src/hooks/community/use-friends.ts+++ b/src/web/src/hooks/community/use-friends.ts@@ -1,8 +1,10 @@"use client"++import { collectionEvidence, deriveView, valueEvidence, viewEvidence } from "@/lib/observability/data-source"import { getCommunityDbRegistry } from "@/lib/community-db/collections"import type { QueryFunctionContext } from "@tanstack/react-query"-import { useQuery, keepPreviousData, type UseQueryResult } from "@tanstack/react-query"+import { useQueryClient, useQuery, keepPreviousData, type UseQueryResult } from "@tanstack/react-query"import { useMemo } from "react"import { apiFetch } from "@/lib/api/client"import {@@ -107,6 +109,8 @@ export function useFriends(): UseQueryResult<{ ids: string[] }> & {pending: PendingRequest[]blocked: BlockedUser[]} {+ const client = useQueryClient()+ const registry = getCommunityDbRegistry(client)const query = useQuery({queryKey: communityKeys.friends(),queryFn: friendsQueryFn,@@ -125,12 +129,11 @@ export function useFriends(): UseQueryResult<{ ids: string[] }> & {}return { friends, pending, blocked }}, [rows, profilesByUserId, query.data?.ids])- return {- ...query,- friends,- pending,- blocked,- }+ const evidence = [valueEvidence(client, query.data), ...(registry ? [collectionEvidence(client, "friendships", rows.map(row => row.id), rows)] : []), ...rows.map(row => viewEvidence(profilesByUserId.get(row.userId)))]+ deriveView(friends, evidence)+ deriveView(pending, evidence)+ deriveView(blocked, evidence)+ return { ...query, friends, pending, blocked }}/**diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.tsindex ed62e5080..ae4933d34 100644--- a/src/web/src/hooks/community/use-inbox.ts+++ b/src/web/src/hooks/community/use-inbox.ts@@ -3,6 +3,7 @@ import { useSelector } from "@tanstack/react-store"import { getCommunityDbRegistry } from "@/lib/community-db/collections"+import { deriveView, viewEvidence, valueEvidence } from "@/lib/observability/data-source"import { useMemo } from "react"import {keepPreviousData,@@ -247,13 +248,9 @@ export function useInboxAttention() {for (const mention of mentions) conversations.add(mention.channelId ?? mention.id)const exactAttentionCount = conversations.size + friendRequests.length- return {- servers,- dms,- mentions,- friendRequests,- exactAttentionCount,- }+ const inputs = [viewEvidence(query.scopes), viewEvidence(query.items), ...query.scopes.flatMap(scope => [viewEvidence(channelsById.get(scope.channelId)), viewEvidence(serversById.get(scope.serverId ?? ""))]), ...mentions.map(row => viewEvidence(messagesById?.get(row.m.id)))]+ for (const values of [servers, dms, mentions, friendRequests]) deriveView(values, inputs, values.length)+ return deriveView({ servers, dms, mentions, friendRequests, exactAttentionCount }, inputs, exactAttentionCount)}, [channelsById,dmProjection,@@ -336,6 +333,7 @@ export function useInboxMarked(enabled: boolean): UseQueryResult<MarkedWindowResreturn message ? [{ ...marked, m: message }] : []})}, [canonicalMessages, query.data?.marked, markedAccess, pendingMarks])+ deriveView(marked, [valueEvidence(queryClient, query.data), ...marked.map(row => viewEvidence(row.m))], marked.length)return { ...query, marked }}diff --git a/src/web/src/hooks/community/use-machines.ts b/src/web/src/hooks/community/use-machines.tsindex 9babce5b0..603578c64 100644--- a/src/web/src/hooks/community/use-machines.ts+++ b/src/web/src/hooks/community/use-machines.ts@@ -1,6 +1,7 @@"use client"-import { useQuery, type QueryFunctionContext, type UseQueryResult, type UseQueryOptions } from "@tanstack/react-query"+import { deriveView, valueEvidence } from "@/lib/observability/data-source"+import { useQueryClient, useQuery, type QueryFunctionContext, type UseQueryResult, type UseQueryOptions } from "@tanstack/react-query"import { isPresenceOnline } from "@alook/shared"import { communityRequestOptions } from "@/lib/community-db/sync"import { apiFetch } from "@/lib/api/client"@@ -74,13 +75,13 @@ export const machinesQueryFn = (context: QueryFunctionContext) =>export function useMachines(options?: Pick<UseQueryOptions<MachinesResponse>, "enabled" | "subscribed" | "refetchInterval">): UseQueryResult<MachinesResponse> & {machines: MachineSummary[]} {+ const client = useQueryClient()const query = useQuery({queryKey: communityKeys.machines(),queryFn: machinesQueryFn,...options,})- return {- ...query,- machines: query.data?.machines ?? (EMPTY_MACHINES as MachineSummary[]),- }+ const machines = query.data?.machines ?? (EMPTY_MACHINES as MachineSummary[])+ deriveView(machines, [valueEvidence(client, query.data)])+ return { ...query, machines }}diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex 4413fdbcd..78db9a3dd 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -1,4 +1,5 @@"use client"+import { deriveView, mergeEvidence, valueEvidence, viewEvidence } from "@/lib/observability/data-source"import { useAtom, useCreateAtom } from "@tanstack/react-store";import { getCommunityDbRegistry } from "@/lib/community-db/collections"@@ -163,7 +164,7 @@ async function fetchMessagesTransport(if (isMessageSurfaceReceipt(surfaceReceipt)) {options?.onSurfaceReceipt?.(surfaceReceipt)}- return page+ return deriveView(page, [viewEvidence(transport)])}export const channelMessagesQueryFn =@@ -847,8 +848,11 @@ function useMessagesInner(const messages = useMemo<Msg[]>(() => {if (!query.data) return []const byId = new Map((canonicalRows ?? []).map((message) => [message.id, message]))- return mergeMessagesPages(query.data.pages).flatMap((window) => { const message = byId.get(window.id); return message ? [message] : [] })- }, [query.data, canonicalRows])+ const selected = mergeMessagesPages(query.data.pages).flatMap((window) => { const message = byId.get(window.id); return message ? [message] : [] })+ const root = valueEvidence(queryClient, query.data)+ const window = root.source === "unknown" ? mergeEvidence(query.data.pages.map(viewEvidence)) : root+ return deriveView(selected, [window, ...selected.map(viewEvidence)])+ }, [query.data, canonicalRows, queryClient])const latestSeq = useMemo<number>(() => {if (!query.data) return 0@@ -1020,6 +1024,7 @@ export function useMessages(messageMatchesTag(message, opts.tag)),[canonicalBase, opts.tag, overlay],)+ deriveView(messages, messages.length ? [viewEvidence(dbMessages), viewEvidence(base.messages), ...messages.map(viewEvidence)] : [viewEvidence(base.data === undefined ? dbMessages : base.messages)])useEffect(() => {if (!channelId || base.data === undefined) returncommitConversationNavigationProof(queryClient, channelId, accessEpoch)@@ -1111,6 +1116,7 @@ export function useDmMessages(() => materializeMessageStream(canonicalBase, overlay),[canonicalBase, overlay],)+ deriveView(messages, messages.length ? [viewEvidence(dbMessages), viewEvidence(base.messages), ...messages.map(viewEvidence)] : [viewEvidence(base.data === undefined ? dbMessages : base.messages)])useEffect(() => {if (!dmId || base.data === undefined) returncommitConversationNavigationProof(queryClient, dmId, accessEpoch)diff --git a/src/web/src/hooks/community/use-notification-settings.ts b/src/web/src/hooks/community/use-notification-settings.tsindex 26c2742ce..587133da3 100644--- a/src/web/src/hooks/community/use-notification-settings.ts+++ b/src/web/src/hooks/community/use-notification-settings.ts@@ -179,7 +179,7 @@ export function useSetBotNotificationSetting() {const origin = useCommunityMutationOrigin(), source = useCommunityViewSource("bot-notification-setting")type Input = { botId: string; scope: BotNotificationScope; level: string | null; assertActive?: (() => void) & { signal: AbortSignal } }type Intent = Input & { original: ReturnType<typeof origin.begin>["token"]; view: ReturnType<typeof source.capture>; resources: Query[] }- const native = useMutation({+ const native = useMutation({ meta: { observabilityAction: "bot.notification.update" },mutationKey: ["community", "bot-notification-setting-command"], scope: { id: "community-bot-notification-setting-commands" }, gcTime: 0,mutationFn: async ({ botId, scope, level, original, view, resources, assertActive }: Intent) => {const assert = () => { origin.assert(original); view(); assertActive?.() }diff --git a/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.tsindex 0296b153a..9e8ecafd7 100644--- a/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts@@ -6,6 +6,119 @@ beforeEach(installMessageScrollFixture)afterEach(restoreMessageScrollFixture)describe("locked native adapter and existing message scroll owner", () => {+ it("keeps an explicit tail scroll when wrapped offscreen rows receive their later native measurements", () => {+ scrollFixture.width = 639+ scrollFixture.height = 736+ scrollFixture.firstPrefix = 193+ const h = mount({ items: Array.from({ length: 28 }, (_, i) => message(`m${i}`)), tailPaddingEnd: 40 })+ act(() => h.root.scrollTo({ top: 0 }))+ runFrames()+ scrollFixture.width = 265+ scrollFixture.height = 727+ scrollFixture.firstPrefix = 233+ for (const item of h.input.items) scrollFixture.bodyHeights.set(item.m.id, 190)+ h.update({ tailPaddingEnd: 48 })+ expect(h.root.scrollTop).toBe(0)+ act(() => h.root.scrollTo({ top: h.root.scrollHeight }))+ runFrames()+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)+ resize()+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)+ expect(scrollFixture.latest.belowCount).toBe(0)+ })+ it("keeps a newly selected content origin across a pending width measurement and later footer render", () => {+ scrollFixture.width = 905+ scrollFixture.height = 783+ scrollFixture.firstPrefix = 193+ const h = mount({ items: Array.from({ length: 28 }, (_, i) => message(`m${i}`)), tailPaddingEnd: 48 })+ h.move(300)+ scrollFixture.width = 390+ scrollFixture.height = 736+ scrollFixture.firstPrefix = 213+ for (const item of h.input.items) scrollFixture.bodyHeights.set(item.m.id, 154)+ h.stage({ tailPaddingEnd: 40 })+ act(() => h.root.scrollTo({ top: 0 }))+ resize(2)+ expect(h.root.scrollTop).toBe(0)+ const before = { height: h.root.clientHeight, total: h.root.scrollHeight, top: bodyTop(h.root, "m0") }+ runFrames(8)+ h.stage({ items: [...h.input.items] })+ resize()+ expect(h.root.clientHeight).toBe(before.height)+ expect(h.root.scrollHeight).toBe(before.total)+ expect(h.root.scrollTop).toBe(0)+ expect(bodyTop(h.root, "m0")).toBe(before.top)+ })+ it.each(["programmatic", "wheel"])("keeps the absolute content origin after responsive hero growth and %s top positioning without typing", input => {+ scrollFixture.width = 906+ scrollFixture.firstPrefix = 193+ const h = mount()+ h.move(0)+ scrollFixture.width = 390+ scrollFixture.firstPrefix = 213+ h.stage({ items: [...h.input.items] })+ if (input === "wheel") fireEvent.wheel(h.root, { deltaY: -20 })+ act(() => h.root.scrollTo({ top: 0 }))+ resize(2)+ const before = { height: h.root.clientHeight, total: h.root.scrollHeight, top: h.root.scrollTop, body: bodyTop(h.root, "m0") }+ expect(before.top).toBe(0)+ expect(before.body).toBe(213)+ runFrames()+ expect(h.root.clientHeight).toBe(before.height)+ expect(h.root.scrollHeight).toBe(before.total)+ expect(h.root.scrollTop).toBe(0)+ expect(bodyTop(h.root, "m0")).toBe(before.body)+ })+ it("keeps an existing short-list pin at the new maximum after responsive body growth", () => {+ scrollFixture.width = 906+ scrollFixture.firstPrefix = 193+ const h = mount({ items: [message("m0")], hasMoreOlder: false })+ expect(h.root.scrollHeight).toBe(h.root.clientHeight)+ expect(h.root.scrollTop).toBe(0)+ scrollFixture.width = 390+ scrollFixture.firstPrefix = 213+ scrollFixture.bodyHeights.set("m0", 800)+ h.stage({ items: [...h.input.items] })+ resize()+ expect(h.root.scrollHeight).toBeGreaterThan(h.root.clientHeight)+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)+ expect(scrollFixture.latest.belowCount).toBe(0)+ })+ it.each(["wheel", "target"])("retires a short-list pin when %s takes ownership before overflow", input => {+ const h = mount({ items: [message("m0"), message("m1")], hasMoreOlder: false })+ expect(h.root.scrollHeight).toBe(h.root.clientHeight)+ if (input === "wheel") fireEvent.wheel(h.root, { deltaY: -20 })+ else h.stage({ scrollToMessageId: "m0" })+ scrollFixture.bodyHeights.set("m1", 900)+ h.stage({ items: [...h.input.items] })+ resize()+ expect(h.root.scrollHeight).toBeGreaterThan(h.root.clientHeight)+ expect(h.root.scrollTop).toBeLessThan(100)+ expect(bodyTop(h.root, "m0")).toBeGreaterThanOrEqual(0)+ })+ it("keeps the existing first-message body when history is prepended at the content origin", () => {+ const h = mount()+ h.move(0)+ const before = bodyTop(h.root, "m0")+ act(() => scrollFixture.latest.captureOlderPageAnchor())+ h.update({ isFetchingOlder: true })+ h.update({ items: [message("older"), ...h.input.items], isFetchingOlder: false })+ expect(bodyTop(h.root, "m0")).toBeCloseTo(before, 0)+ })+ it.each(["m0", "m1"])("keeps a settled %s target when a short list later grows beyond the viewport", id => {+ const positioned = vi.fn()+ const h = mount({ items: [message("m0"), message("m1"), message("m2")], hasMoreOlder: false, onScrollTargetPositioned: positioned })+ h.update({ scrollToMessageId: id })+ resize()+ expect(positioned).toHaveBeenCalledWith(id)+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ expect(h.root.scrollHeight).toBe(h.root.clientHeight)+ scrollFixture.bodyHeights.set("m2", 900)+ h.update({ items: [...h.input.items] })+ expect(h.root.scrollHeight).toBeGreaterThan(h.root.clientHeight)+ expect(h.root.scrollTop).toBeLessThan(100)+ expect(bodyTop(h.root, id)).toBeGreaterThanOrEqual(0)+ })it("unifies native total and DOM max while keeping 40/48px rail clearance", () => {const h = mount()expect(scrollFixture.latest.readPositionReady).toBe(true)@@ -139,7 +252,8 @@ describe("locked native adapter and existing message scroll owner", () => {expect(bodyTop(h.root, "m5")).toBeCloseTo(top, 0)expect(offset).not.toHaveBeenCalled()})- it("settles same-anchor hero growth once after native layout", () => {+ it.each([0, 11])("settles same-anchor hero growth once with a %ipx scrollbar after native layout", gutter => {+ vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockImplementation(() => scrollFixture.width - gutter)scrollFixture.bodyHeights.set("m0", 1200)const h = mount()h.move(400)@@ -292,6 +406,44 @@ describe("locked native adapter and existing message scroll owner", () => {expect(offset).toHaveBeenCalledTimes(calls)}})+ it.each([0, 11])("keeps a settled tail with a %ipx scrollbar through width wrapping and later native row measurements", gutter => {+ vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockImplementation(() => scrollFixture.width - gutter)+ scrollFixture.width = 639+ scrollFixture.height = 736+ const h = mount({ tailPaddingEnd: 40 })+ scrollFixture.width = 266+ scrollFixture.height = 727+ for (const item of h.input.items) scrollFixture.bodyHeights.set(item.m.id, 190)+ h.stage({ tailPaddingEnd: 48 })+ resize()+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBe(0)+ scrollFixture.bodyHeights.set("m13", 420)+ resize()+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBe(0)+ expect(scrollFixture.latest.belowCount).toBe(0)+ })+ it("preserves an away reader through width wrapping without an end command", () => {+ scrollFixture.width = 639+ const h = mount({ tailPaddingEnd: 40 })+ h.move(300)+ const top = bodyTop(h.root, "m2")+ scrollFixture.width = 266+ for (const item of h.input.items) scrollFixture.bodyHeights.set(item.m.id, 190)+ h.update({ tailPaddingEnd: 48 })+ expect(bodyTop(h.root, "m2")).toBe(top)+ })+ it("retires width-triggered native end positioning when the user takes over", () => {+ scrollFixture.width = 639+ const h = mount({ tailPaddingEnd: 40 })+ scrollFixture.width = 266+ h.stage({ tailPaddingEnd: 48 })+ resize(2)+ h.move(300)+ const before = h.root.scrollTop+ scrollFixture.bodyHeights.set("m13", 420)+ resize()+ expect(h.root.scrollTop).toBe(before)+ })it("preserves a two-pixel DM tail distance through consecutive composer resizes", () => {const h = mount()scrollFixture.height -= 100@@ -453,6 +605,16 @@ describe("locked native adapter and existing message scroll owner", () => {runFrames(1)expect(offset).not.toHaveBeenCalled()})+ it("keeps the content viewport anchor while native border-box delivery is pending with a scrollbar", () => {+ vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockImplementation(() => scrollFixture.width - 11)+ const h = mount()+ h.move(h.root.scrollHeight - scrollFixture.height - 2)+ scrollFixture.height += 100+ runFrames(1)+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBe(2)+ resize(0)+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBe(2)+ })it.each([0, 2, 8, 100, 300])("preserves the %ipx footer policy before native RO when composer growth does not clamp", async distance => {const h = mount()h.move(h.root.scrollHeight - scrollFixture.height - distance)diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.tsindex ba7f09f72..fd11dc67c 100644--- a/src/web/src/hooks/community/use-scroll-anchor.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.ts@@ -253,17 +253,22 @@ export function useScrollAnchor({prefix: numberitemStart: numberclientHeight: number+ clientWidth: number+ outerHeight: number+ outerWidth: numberscrollHeight: numberscrollTop: numbertotal: numberpaddingEnd: number- exactlyPinned: boolean+ pinEligible: booleanisScrolling: boolean}const scrollRef = useRef<HTMLDivElement>(null)const virtualizerRef = useRef<ReactVirtualizer<HTMLDivElement, Element> | null>(null)const positionOwnerRef = useRef({ epoch: 0, kind: "initial" as Kind, active: true, nativeIndex: false })const [ownerKind, setOwnerKind] = useAtom(useCreateAtom<Kind>("initial"))+ const [nativeOriginKey, setNativeOriginKey] = useAtom(useCreateAtom<string | number | bigint | null>(null))+ const nativeOriginKeyRef = useRef<string | number | bigint | null>(null)const [readPositionReady, setReadPositionReady] = useAtom(useCreateAtom(false))const [shortGap, setShortGap] = useAtom(useCreateAtom(0))const [paginationDirection, setPaginationDirection] = useAtom(useCreateAtom<"older" | "newer" | null>(null))@@ -302,6 +307,12 @@ export function useScrollAnchor({const tailKeyRef = useRef<string | null>(null)const messages = useMemo(() => extractScrollAnchorMessages(items), [items])const tailId = messages.at(-1)?.id ?? null+ const holdNativeOrigin = useCallback((key: string | number | bigint | null) => {+ nativeOriginKeyRef.current = key+ setNativeOriginKey(key)+ const native = virtualizerRef.current+ if (key !== null && native) native.setOptions({ ...native.options, anchorTo: "start" })+ }, [setNativeOriginKey])const cancelFrame = useCallback(() => {if (initialSettleFrameRef.current !== null) window.cancelAnimationFrame(initialSettleFrameRef.current)initialSettleFrameRef.current = null@@ -329,12 +340,13 @@ export function useScrollAnchor({clearBudget()semanticIntentRef.current = nullacceptedGeometryRef.current = null+ holdNativeOrigin(null)geometrySampleRef.current = nullpresentIntentEpochRef.current = nullreadReadyRef.current = falsesetReadPositionReady(false)return owner.epoch- }, [cancelFrame, clearBudget, setOwnerKind, setReadPositionReady])+ }, [cancelFrame, clearBudget, holdNativeOrigin, setOwnerKind, setReadPositionReady])const retireInitialPosition = useCallback(() => {initialRetiredRef.current = truestateRef.current = { ...stateRef.current, didInitialScroll: true, didDividerConverge: true }@@ -377,7 +389,8 @@ export function useScrollAnchor({+ (index === items.length - 1 && hasMoreNewer ? 56 : 0),measureElement: measureMessageRow,getItemKey: (index) => items[index].key,- anchorTo: ownerKind === "idle" && readPositionReady && !awaitingTarget ? "end" : "start",+ anchorTo: ownerKind === "idle" && readPositionReady && !awaitingTarget+ && (nativeOriginKey === null || nativeOriginKey !== items[0]?.key || paginationDirection !== null) ? "end" : "start",followOnAppend: false,scrollEndThreshold: 1,scrollMargin: 0,@@ -453,6 +466,7 @@ export function useScrollAnchor({if (owner.kind === "initial" && !initialScrollReadyRef.current) returnsemanticIntentRef.current = nullowner.nativeIndex = false+ if (intent.type !== "end" && root.scrollTop <= 1) holdNativeOrigin(currentItemsRef.current[0]?.key ?? null)owner.kind = "idle"setOwnerKind("idle")readReadyRef.current = true@@ -468,7 +482,7 @@ export function useScrollAnchor({initialSettleFrameRef.current = window.requestAnimationFrame(settle)}initialSettleFrameRef.current = window.requestAnimationFrame(settle)- }, [clearBudget, setOwnerKind, setReadPositionReady, settlePresentation])+ }, [clearBudget, holdNativeOrigin, setOwnerKind, setReadPositionReady, settlePresentation])const startIntent = useCallback((type: Intent["type"], id: string | null, behavior: ScrollBehavior = "auto", notifyTarget = false) => {const owner = positionOwnerRef.current@@ -540,11 +554,13 @@ export function useScrollAnchor({const owner = positionOwnerRef.currentconst previous = acceptedGeometryRef.currentconst pendingViewportRect = viewportTransition && previous?.epoch === owner.epoch- && previous.clientHeight !== root?.clientHeight- && Math.abs((native?.scrollRect?.height ?? 0) - previous.clientHeight) <= 1+ && (previous.clientHeight !== root?.clientHeight || previous.clientWidth !== root?.clientWidth)+ && Math.abs((native?.scrollRect?.height ?? 0) - previous.outerHeight) <= 1+ && Math.abs((native?.scrollRect?.width ?? 0) - previous.outerWidth) <= 1if (!owner.active || !root || !native || root.clientHeight <= 0|| Math.abs((native.scrollOffset ?? 0) - root.scrollTop) > 1- || (!pendingViewportRect && Math.abs((native.scrollRect?.height ?? 0) - root.clientHeight) > 1)) return null+ || (!pendingViewportRect && (Math.abs((native.scrollRect?.height ?? 0) - root.offsetHeight) > 1+ || Math.abs((native.scrollRect?.width ?? 0) - root.offsetWidth) > 1))) return nullconst total = native.getTotalSize()const max = Math.max(0, root.scrollHeight - root.clientHeight)if (root.scrollTop < 0 || root.scrollTop > max + 1) return null@@ -563,9 +579,12 @@ export function useScrollAnchor({|| Math.abs(wrapperRect.top - viewport.top + root.scrollTop - fold.start) > 1) return nullreturn {epoch: owner.epoch, key: fold.key, prefix: bodyRect.top - wrapperRect.top,- itemStart: fold.start, clientHeight: root.clientHeight,+ itemStart: fold.start, clientHeight: root.clientHeight, clientWidth: root.clientWidth,+ outerHeight: root.offsetHeight, outerWidth: root.offsetWidth,scrollHeight: root.scrollHeight, scrollTop: root.scrollTop,- total, paddingEnd: native.options.paddingEnd ?? 0, exactlyPinned: max - root.scrollTop <= 1,+ total, paddingEnd: native.options.paddingEnd ?? 0,+ pinEligible: max - root.scrollTop <= 1 && !userScrolledAwayRef.current+ && nativeOriginKeyRef.current !== currentItemsRef.current[0]?.key,isScrolling: native.isScrolling,}}, [])@@ -573,24 +592,28 @@ export function useScrollAnchor({const previous = acceptedGeometryRef.currentconst previousFold = previous && virtualizerRef.current?.getVirtualItems().find((item) => item.key === previous.key)const scrolledAfterResize = scrollEvent && previous?.epoch === next.epoch+ && previous.clientWidth === next.clientWidth&& (previous.clientHeight !== next.clientHeight || previous.paddingEnd !== next.paddingEnd)&& previous.scrollTop <= Math.max(0, next.scrollHeight - next.clientHeight) + 1&& previous.scrollTop !== next.scrollTopif (positionOwnerRef.current.kind === "idle" && readReadyRef.current&& (!previous || scrolledAfterResize || (previous.epoch === next.epoch- && previous.clientHeight === next.clientHeight && previous.scrollHeight === next.scrollHeight+ && previous.clientHeight === next.clientHeight && previous.clientWidth === next.clientWidth+ && previous.scrollHeight === next.scrollHeight&& previous.total === next.total && previous.paddingEnd === next.paddingEnd&& previousFold?.start === previous.itemStart&& (previous.key !== next.key || previous.prefix === next.prefix)))) {const unchangedPosition = previous?.epoch === next.epoch- && previous.clientHeight === next.clientHeight && previous.scrollHeight === next.scrollHeight+ && previous.clientHeight === next.clientHeight && previous.clientWidth === next.clientWidth+ && previous.scrollHeight === next.scrollHeight&& virtualizerRef.current?.scrollOffset === previous.scrollTop&& Math.abs(previous.scrollTop - next.scrollTop) <= 1acceptedGeometryRef.current = {...next, isScrolling: next.isScrolling && unchangedPosition ? previous.isScrolling : next.isScrolling,}+ holdNativeOrigin(next.scrollTop <= 1 && !next.pinEligible ? currentItemsRef.current[0]?.key ?? null : null)}- }, [])+ }, [holdNativeOrigin])const reconcileGeometry = useCallback((viewportOnly = false) => {const root = scrollRef.current@@ -600,6 +623,7 @@ export function useScrollAnchor({if (viewportOnly && (owner.kind !== "idle" || !readReadyRef.current|| acceptedGeometryRef.current?.epoch !== owner.epoch|| (acceptedGeometryRef.current.clientHeight === root.clientHeight+ && acceptedGeometryRef.current.clientWidth === root.clientWidth&& acceptedGeometryRef.current.paddingEnd === (native.options.paddingEnd ?? 0)))) return falseconst total = native.getTotalSize()const gap = Math.max(0, root.clientHeight - (total - (native.options.paddingStart ?? 0)))@@ -614,7 +638,7 @@ export function useScrollAnchor({const max = Math.max(0, root.scrollHeight - root.clientHeight)const previous = acceptedGeometryRef.currentconst viewportResized = !!next && previous?.epoch === owner.epoch- && (previous.clientHeight !== next.clientHeight || previous.paddingEnd !== next.paddingEnd)+ && (previous.clientHeight !== next.clientHeight || previous.clientWidth !== next.clientWidth || previous.paddingEnd !== next.paddingEnd)const clampedByResize = viewportResized && !previous.isScrolling && previous.scrollTop > max&& Math.abs(root.scrollTop - max) <= 1if (input.touch || input.pointers.size > 0 || (native.isScrolling && !clampedByResize)@@ -628,15 +652,19 @@ export function useScrollAnchor({geometrySampleRef.current = { value, frames: sample?.value === value ? sample.frames + 1 : 1 }if (!viewportResized && geometrySampleRef.current.frames < 2) return truelet offset = root.scrollTop+ let originHeld = falseif (previous?.epoch === owner.epoch && readReadyRef.current) {- const prefixDelta = previous.key === next.key && !previous.exactlyPinned ? next.prefix - previous.prefix : 0+ originHeld = !previous.pinEligible && previous.scrollTop <= 1+ && previous.key === currentItemsRef.current[0]?.key && previous.itemStart <= 1+ const prefixDelta = previous.key === next.key && !previous.pinEligible && !originHeld ? next.prefix - previous.prefix : 0offset += prefixDelta- if (previous.clientHeight !== next.clientHeight || previous.paddingEnd !== next.paddingEnd) {+ if (originHeld) offset = previous.scrollTop+ else if (previous.clientHeight !== next.clientHeight || previous.clientWidth !== next.clientWidth || previous.paddingEnd !== next.paddingEnd) {const previousFold = virtualItems.find((candidate) => candidate.key === previous.key)if (previousFold) {const totalDelta = next.total - previous.total - (next.paddingEnd - previous.paddingEnd)const adjustedPreviousOffset = previous.scrollTop- + (previous.exactlyPinned ? totalDelta : previousFold.start - previous.itemStart)+ + (previous.pinEligible ? totalDelta : previousFold.start - previous.itemStart)const resized = resolveViewportResizeAnchor({previousClientHeight: previous.clientHeight,nextClientHeight: next.clientHeight,@@ -650,18 +678,24 @@ export function useScrollAnchor({}offset = Math.max(0, Math.min(offset, max))acceptedGeometryRef.current = {- ...next, scrollTop: offset, exactlyPinned: max - offset <= 1,+ ...next, scrollTop: offset, pinEligible: !originHeld && next.pinEligible && max - offset <= 1,isScrolling: clampedByResize ? previous.isScrolling : next.isScrolling,}+ holdNativeOrigin(originHeld || (offset <= 1 && !acceptedGeometryRef.current.pinEligible) ? currentItemsRef.current[0]?.key ?? null : null)wasAtEndRef.current = max - offset <= NEAR_BOTTOM_PXif (input.handover) {input.handover = falsereadReadyRef.current = truesetReadPositionReady(true)}+ if (viewportResized && previous.pinEligible && previous.clientWidth !== next.clientWidth) {+ owner.nativeIndex = true+ native.scrollToEnd({ behavior: "auto" })+ return true+ }if (Math.abs(offset - root.scrollTop) > 0.5) native.scrollToOffset(offset, { behavior: "auto" })return false- }, [observeGeometry, readGeometry, setReadPositionReady, setShortGap])+ }, [holdNativeOrigin, observeGeometry, readGeometry, setReadPositionReady, setShortGap])reconcileViewportRef.current = () => { reconcileGeometry(true) }const scheduleGeometry = useCallback(() => {@@ -681,8 +715,27 @@ export function useScrollAnchor({const onScroll = () => {const input = userInputRef.currentconst previous = acceptedGeometryRef.current+ const native = virtualizerRef.current+ if (positionOwnerRef.current.kind === "idle" && readReadyRef.current+ && previous?.epoch === positionOwnerRef.current.epoch && previous.scrollTop > 1+ && root.scrollTop <= 1 && root.scrollHeight - root.clientHeight > 1+ && Math.abs((native?.scrollOffset ?? 0) - root.scrollTop) <= 1) {+ acceptedGeometryRef.current = null+ holdNativeOrigin(currentItemsRef.current[0]?.key ?? null)+ } else if (positionOwnerRef.current.kind === "idle" && readReadyRef.current+ && previous?.epoch === positionOwnerRef.current.epoch && previous.scrollTop <= 1+ && nativeOriginKeyRef.current === currentItemsRef.current[0]?.key && root.scrollTop > 1+ && root.scrollHeight - root.clientHeight - root.scrollTop <= 1+ && previous.clientHeight === root.clientHeight && previous.clientWidth === root.clientWidth+ && previous.scrollHeight === root.scrollHeight && previous.total === native?.getTotalSize()+ && previous.paddingEnd === (native?.options.paddingEnd ?? 0)+ && Math.abs((native?.scrollOffset ?? 0) - root.scrollTop) <= 1) {+ acceptedGeometryRef.current = null+ holdNativeOrigin(null)+ }const unchanged = previous?.epoch === positionOwnerRef.current.epoch- && previous.clientHeight === root.clientHeight && previous.scrollHeight === root.scrollHeight+ && previous.clientHeight === root.clientHeight && previous.clientWidth === root.clientWidth+ && previous.scrollHeight === root.scrollHeight&& virtualizerRef.current?.scrollOffset === previous.scrollTop&& Math.abs(previous.scrollTop - root.scrollTop) <= 1if (!unchanged) input.scrollAt = performance.now()@@ -698,6 +751,8 @@ export function useScrollAnchor({userInputRef.current.at = performance.now()userScrolledAwayRef.current = truereleasePosition(true)+ userScrolledAwayRef.current = true+ if (root.scrollTop <= 1) holdNativeOrigin(currentItemsRef.current[0]?.key ?? null)}const onWheel = (event: WheelEvent) => { if (event.deltaY !== 0) onUserIntent() }const onKeyDown = (event: KeyboardEvent) => {@@ -756,7 +811,7 @@ export function useScrollAnchor({userInputRef.current.touch = falseuserInputRef.current.pointers.clear()}- }, [observeGeometry, readGeometry, reconcileGeometry, releasePosition, scheduleGeometry])+ }, [holdNativeOrigin, observeGeometry, readGeometry, reconcileGeometry, releasePosition, scheduleGeometry])const capturePageAnchor = useCallback((direction: "older" | "newer") => {if (positionOwnerRef.current.kind === "idle" && readReadyRef.current) {diff --git a/src/web/src/hooks/community/use-server-members.ts b/src/web/src/hooks/community/use-server-members.tsindex d7d434aed..1ad59806d 100644--- a/src/web/src/hooks/community/use-server-members.ts+++ b/src/web/src/hooks/community/use-server-members.ts@@ -1,5 +1,7 @@"use client"+import { deriveView, valueEvidence, viewEvidence } from "@/lib/observability/data-source"+import { useEffect, useMemo } from "react"import { createStore, useSelector } from "@tanstack/react-store"import { useInfiniteQuery, useMutationState, useQueryClient, replaceEqualDeep, type InfiniteData, type Query, type QueryKey, type QueryClient } from "@tanstack/react-query"@@ -429,9 +431,10 @@ export function useServerMembers(serverId: string | null): UseServerMembers {const row = byUser.get(identity.userId)if (!row || row.memberId !== identity.id) return []const profile = readCommunityProfile(profiles.get(identity.userId), identity.userId)- return [{ id: identity.id, userId: identity.userId, name: row.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: row.role as CommunityRole, status: row.viewer ? "online" as const : profile.presence, sub: "", statusEmoji: profile.statusEmoji, statusText: profile.statusText }]+ return [deriveView({ id: identity.id, userId: identity.userId, name: row.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: row.role as CommunityRole, status: row.viewer ? "online" as const : profile.presence, sub: "", statusEmoji: profile.statusEmoji, statusText: profile.statusText }, [viewEvidence(row), viewEvidence(profile)])]})}, [identities, memberships, profiles])+ deriveView(members, [valueEvidence(queryClient, data), ...members.map(viewEvidence)], members.length)const active = searching ? search : infiniteconst pendingKicks = useMutationState({ filters: { mutationKey: ["community", "member-command"], status: "pending" }, select: (mutation) => {const variables = mutation.state.variables as { kind: string; input: { serverId: string; memberId: string } }diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.tsindex ec084c731..2ba24c4ff 100644--- a/src/web/src/hooks/community/use-servers.ts+++ b/src/web/src/hooks/community/use-servers.ts@@ -1,4 +1,5 @@"use client"+import { deriveView, viewEvidence } from "@/lib/observability/data-source"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"import { conversationReadRetryPolicy, withConversationReadDeadline } from "@/lib/community/conversation-read"import { useSelector } from "@tanstack/react-store"@@ -200,6 +201,7 @@ export function useServers(): UseQueryResult<string[]> & { servers: Server[]; isreturn unread === server.unread && mentions === server.mentions ? server : { ...server, unread, mentions }})}, [attentionScopes, dbRail?.servers, serverAccess])+ deriveView(servers, [viewEvidence(dbRail?.servers), viewEvidence(attentionScopes)])void structuralGenerationconst state = registry?.runtime.ws.get()return {@@ -419,7 +421,8 @@ export function useServer(changed = truereturn { ...category, channels }})- return changed ? { ...source, categories } : source+ deriveView(categories, [viewEvidence(source.categories), viewEvidence(attentionScopes)])+ return changed ? deriveView({ ...source, categories }, [viewEvidence(source), viewEvidence(categories)]) : source}, [attentionScopes, dbServer, serverId])return {...query,diff --git a/src/web/src/hooks/use-agent-chat.ts b/src/web/src/hooks/use-agent-chat.tsindex d7de380f0..95eb65575 100644--- a/src/web/src/hooks/use-agent-chat.ts+++ b/src/web/src/hooks/use-agent-chat.ts@@ -145,8 +145,8 @@ export function useAgentChat(const chatData = useChatData(workspaceOwner, chatViewIdentity, targetConvId);const chatActions = chatData.actions;const { conversation, setConversation, messages, setMessages, artifacts, activeTask, setActiveTask, taskMessages, hasMore, setHasMore, previousConversations, setPreviousConversations, hasMoreConversations, setHasMoreConversations } = chatData;- const { mutateAsync: mutateChatCommand } = useMutation({ mutationKey: workspaceOwner.key("chat", "command"), gcTime: 0, mutationFn: (operation: () => Promise<unknown>) => operation() });- const withChatOrigin = useCallback(<T,>(operation: (options: ApiRequestOptions) => Promise<T>, options?: ApiRequestOptions, mutation = false): Promise<T> => {+ const { mutateAsync: mutateChatCommand } = useMutation({ meta: { observabilityAction: "chat.command" }, mutationKey: workspaceOwner.key("chat", "command"), gcTime: 0, mutationFn: ({ operation }: { operation: () => Promise<unknown>; kind: "persist" | "read" }) => operation() });+ const withChatOrigin = useCallback(<T,>(operation: (options: ApiRequestOptions) => Promise<T>, options?: ApiRequestOptions, mutation: false | "persist" | "read" = false): Promise<T> => {const intent = captureChatIntent(workspaceOwner, chatActions.view);const controller = new AbortController();const signal = options?.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;@@ -159,7 +159,7 @@ export function useAgentChat(catch (error) { assertActive(); throw error; }finally { for (const subscription of subscriptions) subscription.unsubscribe(); }};- return mutation ? mutateChatCommand(load) as Promise<T> : load();+ return mutation ? mutateChatCommand({ operation: load, kind: mutation }) as Promise<T> : load();}, [workspaceOwner, chatActions.view, mutateChatCommand]);const chatInit = useCallback(async (...args: Parameters<typeof chatInitApi>) => { const tickets = captureChatLoad(workspaceOwner); const data = await withChatOrigin((options) => chatInitApi(args[0], args[1], args[2], options), args[3], false); return settleChatLoad(workspaceOwner, data, tickets); }, [withChatOrigin, workspaceOwner]);const checkFreshness = useCallback((...args: Parameters<typeof checkFreshnessApi>) => withChatOrigin((options) => checkFreshnessApi(args[0], args[1], options), args[2], false), [withChatOrigin]);@@ -215,12 +215,12 @@ export function useAgentChat(const index = data?.pageParams.indexOf(args[2].before) ?? -1;return data?.pages[index < 0 ? data.pages.length - 1 : index] ?? { conversations: [], has_more: false };}, [workspaceOwner, chatActions, chatViewIdentity]);- const sendMessage = useCallback((...args: Parameters<typeof sendMessageApi>) => withChatOrigin((options) => sendMessageApi(args[0], args[1], args[2], args[3], args[4], options), args[5], true), [withChatOrigin]);+ const sendMessage = useCallback((...args: Parameters<typeof sendMessageApi>) => withChatOrigin((options) => sendMessageApi(args[0], args[1], args[2], args[3], args[4], options), args[5], "persist"), [withChatOrigin]);const getTask = useCallback(async (...args: Parameters<typeof getTaskApi>) => { const source = chatReadSource(workspaceOwner, chatActions.view, chatViewIdentity, args[2]); const options = chatTaskOptions(source, args[0]); const release = observeChatRead(source, new QueryObserver(workspaceOwner.queryClient, { ...options, enabled: false })); try { await workspaceOwner.queryClient.fetchQuery(options); } finally { release(); } source.assertActive(); return workspaceOwner.queryClient.getQueryData<Task>(options.queryKey)!; }, [workspaceOwner, chatActions.view, chatViewIdentity]);const getTaskMessages = useCallback(async (...args: Parameters<typeof getTaskMessagesApi>) => { const source = chatReadSource(workspaceOwner, chatActions.view, chatViewIdentity, args[3]); const options = chatTaskMessagesOptions(source, args[0]); const release = observeChatRead(source, new QueryObserver(workspaceOwner.queryClient, { ...options, enabled: false })); try { await workspaceOwner.queryClient.fetchQuery(options); } finally { release(); } source.assertActive(); return (workspaceOwner.queryClient.getQueryData<TaskMessageResponse[]>(options.queryKey) ?? []).filter((row) => args[2] === undefined || row.seq > args[2]); }, [workspaceOwner, chatActions.view, chatViewIdentity]);const listArtifacts = useCallback(async (...args: Parameters<typeof listArtifactsApi>) => { const source = chatReadSource(workspaceOwner, chatActions.view, chatViewIdentity, args[2]); const options = chatArtifactOptions(source, args[0]); const release = observeChatRead(source, new QueryObserver(workspaceOwner.queryClient, { ...options, enabled: false })); try { await workspaceOwner.queryClient.fetchQuery(options); } finally { release(); } source.assertActive(); return workspaceOwner.queryClient.getQueryData<ChatExtras>(options.queryKey)?.artifacts ?? []; }, [workspaceOwner, chatActions.view, chatViewIdentity]);const getActiveTask = useCallback(async (...args: Parameters<typeof getActiveTaskApi>) => { const source = chatReadSource(workspaceOwner, chatActions.view, chatViewIdentity, args[2]); const options = chatActiveTaskOptions(source, args[0]); const release = observeChatRead(source, new QueryObserver(workspaceOwner.queryClient, { ...options, enabled: false })); try { await workspaceOwner.queryClient.fetchQuery(options); } finally { release(); } source.assertActive(); const currentId = workspaceOwner.queryClient.getQueryData<{ id: string | null }>(options.queryKey)?.id; return currentId ? readChatTask(source, currentId) : undefined; }, [workspaceOwner, chatActions.view, chatViewIdentity]);- const markInboxRead = useCallback((...args: Parameters<typeof markInboxReadApi>) => withChatOrigin((options) => markInboxReadApi(args[0], args[1], options), args[2], true), [withChatOrigin]);+ const markInboxRead = useCallback((...args: Parameters<typeof markInboxReadApi>) => withChatOrigin((options) => markInboxReadApi(args[0], args[1], options), args[2], "read"), [withChatOrigin]);const listFlaggedMessageIds = useCallback(async (...args: Parameters<typeof listFlaggedMessageIdsApi>) => { const source = chatReadSource(workspaceOwner, chatActions.view, chatViewIdentity, args[2]); const options = chatFlagsOptions(source, args[1]); const release = observeChatRead(source, new QueryObserver(workspaceOwner.queryClient, { ...options, enabled: false })); let ids; try { ids = await workspaceOwner.queryClient.fetchQuery(options); } finally { release(); } source.assertActive(); return { message_ids: ids.ids }; }, [workspaceOwner, chatActions.view, chatViewIdentity]);const [messagesLoading, setMessagesLoading] = useAtom(useCreateAtom(true));const [napMarkers, setNapMarkers] = useAtom(useCreateAtom<NapMarker[]>([]));@@ -1553,7 +1553,7 @@ export function useAgentChat(const sendIdentity = useMemo(() => crypto.randomUUID(), []);const sendKey = workspaceOwner.key("chat", "send", sendIdentity);const sending = useIsMutating({ mutationKey: sendKey, exact: true }) > 0;- const sendCommand = useMutation<void, Error, SendIntent>({+ const sendCommand = useMutation<void, Error, SendIntent>({ meta: { observabilityAction: "chat.message.send" },mutationKey: sendKey, gcTime: 0,mutationFn: async ({ original: intent, conversation, content, files, quote, retryId, rawInput, skillName }) => {const assertActive = () => assertChatIntent(intent);@@ -1627,7 +1627,7 @@ export function useAgentChat(const sessionCommandKey = useMemo(() => workspaceOwner.key("chat", "session-command", crypto.randomUUID()), [workspaceOwner]);type SessionIntent = { original: ReturnType<typeof captureChatIntent>; conversation: Conversation; channel: string; agentName: string } & ({ kind: "nap" } | { kind: "retry"; taskId: string });- const sessionCommand = useMutation({ mutationKey: sessionCommandKey, gcTime: 0, scope: { id: JSON.stringify(sessionCommandKey) },+ const sessionCommand = useMutation({ meta: { observabilityAction: "chat.session.command" }, mutationKey: sessionCommandKey, gcTime: 0, scope: { id: JSON.stringify(sessionCommandKey) },mutationFn: async (intent: SessionIntent) => {assertChatIntent(intent.original);if (intent.kind === "retry") {diff --git a/src/web/src/hooks/use-application-sign-out.ts b/src/web/src/hooks/use-application-sign-out.tsindex db3e0ea81..16d47c409 100644--- a/src/web/src/hooks/use-application-sign-out.ts+++ b/src/web/src/hooks/use-application-sign-out.ts@@ -7,7 +7,7 @@ import { applicationKey, assertApplicationOwner, captureApplicationOwner, retireexport function useApplicationSignOut() {const owner = useApplicationOwner()- const native = useMutation({ mutationKey: applicationKey(owner, "sign-out"), scope: { id: "account-sign-out" }, gcTime: 0, mutationFn: async (token: ReturnType<typeof captureApplicationOwner>) => {+ const native = useMutation({ meta: { observabilityAction: "account.sign_out" }, mutationKey: applicationKey(owner, "sign-out"), scope: { id: "account-sign-out" }, gcTime: 0, mutationFn: async (token: ReturnType<typeof captureApplicationOwner>) => {assertApplicationOwner(token)const controller = new AbortController()const subscription = owner.lifecycle.subscribe(() => {diff --git a/src/web/src/hooks/use-file-attachments.ts b/src/web/src/hooks/use-file-attachments.tsindex 23e3e6425..536b6e143 100644--- a/src/web/src/hooks/use-file-attachments.ts+++ b/src/web/src/hooks/use-file-attachments.ts@@ -67,7 +67,7 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {};}, [protocol]);type Preparation = { drafts: readonly AttachmentDraftFile[]; generation: number; policy: "legacy" | "community"; scope?: string; signal: AbortSignal };- const preparation = useMutation({ mutationKey: key, scope: { id }, gcTime: 0,+ const preparation = useMutation({ meta: { observabilityAction: "attachment.prepare" }, mutationKey: key, scope: { id }, gcTime: 0,mutationFn: async ({ drafts, generation, policy, scope, signal }: Preparation) => {const eligible = () => protocol.get().active && protocol.get().generation === generation && !signal.aborted;if (!eligible()) return;diff --git a/src/web/src/hooks/use-message-flags.ts b/src/web/src/hooks/use-message-flags.tsindex b6c21e2d1..05469d8b0 100644--- a/src/web/src/hooks/use-message-flags.ts+++ b/src/web/src/hooks/use-message-flags.ts@@ -25,7 +25,7 @@ export function useMessageFlags(owner: WorkspaceOwner, view: ChatView, conversat},})const { begin, rollback, refresh } = useFlagCount()- const mutation = useMutation({ scope: { id: `${owner.application.userId}:${owner.workspaceId}:flags:${conversationId}` },+ const mutation = useMutation({ meta: { observabilityAction: "message.flag.toggle" }, scope: { id: `${owner.application.userId}:${owner.workspaceId}:flags:${conversationId}` },mutationFn: async ({ messageId, intent }: { messageId: string; intent: ReturnType<typeof captureChatIntent> }) => {assertChatIntent(intent)await owner.queryClient.cancelQueries({ queryKey: key, exact: true })diff --git a/src/web/src/hooks/workspace/use-agent-permission-command.ts b/src/web/src/hooks/workspace/use-agent-permission-command.tsindex 2d15423cc..608dfaec0 100644--- a/src/web/src/hooks/workspace/use-agent-permission-command.ts+++ b/src/web/src/hooks/workspace/use-agent-permission-command.ts@@ -27,7 +27,7 @@ export function useAgentPermissionCommand(owner: WorkspaceOwner, agentId: stringconst key = owner.key("agent-permission-command", agentId)const source = useWorkspaceViewSource(owner, `agent-permissions:${agentId}`, true)type NativeIntent = Command & { view: ReturnType<typeof source.capture>; resources: Query[] }- const native = useMutation({ mutationKey: key, scope: { id: JSON.stringify(key) },+ const native = useMutation({ meta: { observabilityAction: "agent.permission.command" }, mutationKey: key, scope: { id: JSON.stringify(key) },mutationFn: async ({ action, token, view, resources, assertActive }: NativeIntent) => {const assert = () => { assertWorkspaceOwner(token, assertActive?.signal ?? view.signal); view.assert(); assertActive?.() }const qc = owner.queryClient, whitelistKey = owner.key("agent-whitelist", agentId), accessKey = owner.key("agent-access", agentId), agentsKey = owner.key("agents")diff --git a/src/web/src/hooks/workspace/use-chat-data.ts b/src/web/src/hooks/workspace/use-chat-data.tsindex f80b02b4b..64f9fbfbe 100644--- a/src/web/src/hooks/workspace/use-chat-data.ts+++ b/src/web/src/hooks/workspace/use-chat-data.ts@@ -1,5 +1,6 @@"use client"+import { deriveView, valueEvidence, sourceEvidence } from "@/lib/observability/data-source"import { useCallback, useMemo, useLayoutEffect } from "react"import { createStore, useSelector } from "@tanstack/react-store"import { useQueries, useQuery, skipToken, type InfiniteData, type UseQueryResult } from "@tanstack/react-query"@@ -45,6 +46,7 @@ export function useChatData(owner: WorkspaceOwner, identity: string, targetConvereturn row ? [row] : []})}, [conversationIds, messageQueries, optimistic, refs])+ deriveView(messages, [...messageQueries.map(value => valueEvidence(owner.queryClient, value)), ...(optimistic.size ? [sourceEvidence(optimistic, "local_mutation")] : [])], messages.length)const extrasKey = chatExtrasKey(owner, conversationId ?? "__none__")const extras = useQuery<ChatExtras>({ queryKey: extrasKey, queryFn: skipToken, enabled: false }).dataconst taskKey = owner.key("chat", "active-task", conversationId ?? "__none__")diff --git a/src/web/src/hooks/workspace/use-inbox.ts b/src/web/src/hooks/workspace/use-inbox.tsindex 0f16337a6..80c511040 100644--- a/src/web/src/hooks/workspace/use-inbox.ts+++ b/src/web/src/hooks/workspace/use-inbox.ts@@ -1,5 +1,7 @@"use client"+import { deriveView, valueEvidence } from "@/lib/observability/data-source"+import { useCallback,useMemo } from "react"import { useSelector } from "@tanstack/react-store"import { infiniteQueryOptions,useInfiniteQuery,useMutation,type InfiniteData } from "@tanstack/react-query"@@ -42,13 +44,14 @@ export function useWorkspaceInbox(enabled = true) {const query = useInfiniteQuery({ ...options, enabled: enabled && hydrated })const items = useMemo(() => firstRows(query.data?.pages), [query.data])const refresh = useCallback(() => workspace.queryClient.invalidateQueries({ queryKey: workspace.key("inbox") }), [workspace])+ deriveView(items, [valueEvidence(workspace.queryClient, query.data)])return { ...query, items, refresh }}export function useMarkAllInboxRead() {const workspace = useWorkspaceOwner()const qc = workspace.queryClientconst mutationKey = workspace.key("inbox", "read-all")- return useMutation({+ return useMutation({ meta: { observabilityAction: "inbox.read_all" },mutationKey,scope: { id: JSON.stringify(mutationKey) },mutationFn: () => runWorkspaceRequest(workspace, (options) => markAllInboxRead(workspace.workspaceId, options)),@@ -80,6 +83,7 @@ export function useWorkspaceFlags(enabled = true) {const options = workspaceFlagOptions(workspace)const query = useInfiniteQuery({ ...options, enabled })const items = useMemo(() => firstRows(query.data?.pages), [query.data])+ deriveView(items, [valueEvidence(workspace.queryClient, query.data)])return { ...query, items }}export function useUnflagWorkspaceMessage() {@@ -87,7 +91,7 @@ export function useUnflagWorkspaceMessage() {const qc = workspace.queryClientconst options = workspaceFlagOptions(workspace)const mutationKey = workspace.key("flagged-items", "remove")- return useMutation({+ return useMutation({ meta: { observabilityAction: "message.flag.remove" },mutationKey, scope: { id: JSON.stringify(mutationKey) },mutationFn: (messageId: string) => runWorkspaceRequest(workspace, (request) => unflagMessage(workspace.workspaceId, messageId, request)),onMutate: async (messageId) => {diff --git a/src/web/src/hooks/workspace/use-issue-command.ts b/src/web/src/hooks/workspace/use-issue-command.tsindex e622726ae..31ae412b6 100644--- a/src/web/src/hooks/workspace/use-issue-command.ts+++ b/src/web/src/hooks/workspace/use-issue-command.ts@@ -31,7 +31,7 @@ export function useIssueCommand(owner: WorkspaceOwner) {const key = owner.key("issue-command")const source = useWorkspaceViewSource(owner, "issue-command", true)type NativeIntent = IssueIntent & { view: ReturnType<typeof source.capture>; resources: Query[] }- const native = useMutation({ mutationKey: key, scope: { id: JSON.stringify(key) }, gcTime: 0,+ const native = useMutation({ meta: { observabilityAction: "issue.command" }, mutationKey: key, scope: { id: JSON.stringify(key) }, gcTime: 0,mutationFn: async ({ action, token, view, resources, assertActive }: NativeIntent) => {const qc = owner.queryClient, assert = () => { assertWorkspaceOwner(token, assertActive?.signal ?? view.signal); view.assert(); assertActive?.() }assert()diff --git a/src/web/src/hooks/workspace/use-runtime-command.ts b/src/web/src/hooks/workspace/use-runtime-command.tsindex 1562b9deb..d89a32f2a 100644--- a/src/web/src/hooks/workspace/use-runtime-command.ts+++ b/src/web/src/hooks/workspace/use-runtime-command.ts@@ -17,7 +17,7 @@ export function useRuntimeCommand(owner: WorkspaceOwner) {const key = owner.key("runtime-command")const source = useWorkspaceViewSource(owner, "runtime-command", true)type NativeIntent = RuntimeIntent & { view: ReturnType<typeof source.capture>; resources: Query[] }- const native = useMutation({ mutationKey: key, scope: { id: JSON.stringify(key) },+ const native = useMutation({ meta: { observabilityAction: "runtime.command" }, mutationKey: key, scope: { id: JSON.stringify(key) },mutationFn: async ({ kind, id, token, view, resources, assertActive }: NativeIntent) => {const assert = () => { assertWorkspaceOwner(token, assertActive?.signal ?? view.signal); view.assert(); assertActive?.() }, qc = owner.queryClient, resourceKey = owner.key("runtimes")assert()diff --git a/src/web/src/hooks/workspace/use-workspace-meetings.ts b/src/web/src/hooks/workspace/use-workspace-meetings.tsindex 0d855031e..be4774e4e 100644--- a/src/web/src/hooks/workspace/use-workspace-meetings.ts+++ b/src/web/src/hooks/workspace/use-workspace-meetings.ts@@ -20,7 +20,7 @@ export function useWorkspaceMeetings(agentId: string) {const options = workspaceMeetingsOptions(owner, agentId)const query = useQuery(options)const mutationKey = [...options.queryKey, "change"]- const mutation = useMutation({+ const mutation = useMutation({ meta: { observabilityAction: "meeting.command" },mutationKey,scope: { id: JSON.stringify(mutationKey) },mutationFn: async (action: MeetingAction) => {diff --git a/src/web/src/instrumentation-client.ts b/src/web/src/instrumentation-client.tsindex 590e546b4..b7f047154 100644--- a/src/web/src/instrumentation-client.ts+++ b/src/web/src/instrumentation-client.ts@@ -8,6 +8,10 @@// NEXT_PUBLIC_PERF_TRACE=1 in a non-production build.import { installReactScan } from "@/lib/perf/react-scan-install"+import { bootstrapObservability, onObservedRouterTransition } from "@/lib/observability/client"++bootstrapObservability("web")+export function onRouterTransitionStart(url: string) { onObservedRouterTransition(url) }// Fire-and-forget: the guard inside is synchronous, only the dynamic// react-scan import is async. Any failure is swallowed so instrumentation candiff --git a/src/web/src/lib/api/artifacts.ts b/src/web/src/lib/api/artifacts.tsindex f9fce192b..410c02bd1 100644--- a/src/web/src/lib/api/artifacts.ts+++ b/src/web/src/lib/api/artifacts.ts@@ -1,3 +1,4 @@+import { readApiResponse } from "./client";import type { Artifact } from "@alook/shared";import type { ApiRequestOptions } from "./client";import { apiFetch, apiFetchResponse, wsQuery } from "./client";@@ -7,8 +8,8 @@ export const listArtifacts = (conversationId: string, workspaceId: string, optioexport const getArtifactContent = async (id: string, workspaceId: string, options?: ApiRequestOptions): Promise<string> => {const params = new URLSearchParams({ workspace_id: workspaceId });- const res = await apiFetchResponse(`/api/artifacts/${id}/content?${params}`, options);- const text = await res.text();+ const res = await apiFetchResponse(`/api/artifacts/${id}/content?${params}`, options, true);+ const text = await readApiResponse<string>(res, "text", options);options?.assertActive?.();if (options?.signal?.aborted) throw new DOMException("Retired artifact content", "AbortError");return text;diff --git a/src/web/src/lib/api/client.ts b/src/web/src/lib/api/client.tsindex 8a4ce4c8e..31d93f1dd 100644--- a/src/web/src/lib/api/client.ts+++ b/src/web/src/lib/api/client.ts@@ -1,5 +1,6 @@import { createStore } from "@tanstack/store";import { ApiError, UnauthorizedError, isAbortError } from "@/lib/errors";+import { startRequest, requestHeaders, requestRejected, finishRequest, readObservedResponse, runObservedFetch, type RequestObservation } from "@/lib/observability/requests";const API_BASE = "";export const ACCOUNT_DELETED_SIGN_IN_PATH = "/sign-in?account_deleted=1";@@ -68,13 +69,27 @@ export function redirectToSignIn(accountId?: string | null) {window.location.assign(new URL("/sign-in", window.location.origin));}-export type ApiRequestOptions = RequestInit & { assertActive?: () => void; onUnauthorized?: () => Promise<boolean>; authenticationAccount?: string };+export type ApiRequestOptions = RequestInit & { assertActive?: () => void; onUnauthorized?: () => Promise<boolean>; authenticationAccount?: string; observation?: Parameters<typeof startRequest>[1] extends infer O ? O extends { observation?: infer P } ? P : never : never };-export async function apiFetchResponse(path: string, options?: ApiRequestOptions): Promise<Response> {- const { assertActive, onUnauthorized, authenticationAccount, ...request } = options ?? {};+export async function apiFetchResponse(path: string, options?: ApiRequestOptions, bodyExpected = false): Promise<Response> {+ const observation = startRequest(path, options);+ try {+ const response = await fetchQualifiedResponse(path, options, observation);+ if (!bodyExpected) finishRequest(observation, "success", "headers", "eligible");+ return response;+ } catch (error) {+ finishRequest(observation, isAbortError(error) ? "cancelled" : "error", "headers");+ throw error;+ }+}++async function fetchQualifiedResponse(path: string, options?: ApiRequestOptions, observation?: RequestObservation): Promise<Response> {+ const { assertActive, onUnauthorized, authenticationAccount, observation: _observation, ...request } = options ?? {};const assertEligible = () => {+ try {assertActive?.();if (request.signal?.aborted) throw new DOMException("Cancelled request", "AbortError");+ } catch (error) { requestRejected(observation); throw error }};assertEligible();if (MOCK_NETWORK_ENABLED) {@@ -90,11 +105,11 @@ export async function apiFetchResponse(path: string, options?: ApiRequestOptionsassertEligible();const headers = new Headers(request.headers);if (!headers.has("Content-Type") && !(typeof FormData !== "undefined" && request.body instanceof FormData)) headers.set("Content-Type", "application/json");- res = await fetch(API_BASE + path, {+ res = await runObservedFetch(observation, () => fetch(API_BASE + path, {...request,credentials: "include",headers,- });+ }));} catch (err) {assertEligible();if (err instanceof TypeError) {@@ -103,6 +118,7 @@ export async function apiFetchResponse(path: string, options?: ApiRequestOptionsthrow err;}+ requestHeaders(observation, res);assertEligible();if (res.status === 401) {@@ -149,11 +165,12 @@ export async function apiFetchResponse(path: string, options?: ApiRequestOptions}export async function apiFetch<T>(path: string, options?: ApiRequestOptions): Promise<T> {- const res = await apiFetchResponse(path, options);- if (res.status === 204) return undefined as T;- const data = await res.json() as T;- options?.assertActive?.();- if (options?.signal?.aborted) throw new DOMException("Cancelled request", "AbortError");+ const res = await apiFetchResponse(path, options, true);+ if (res.status === 204) return readObservedResponse(res, async () => undefined as T);+ const data = await readObservedResponse(res, () => res.json() as Promise<T>, () => {+ options?.assertActive?.();+ if (options?.signal?.aborted) throw new DOMException("Cancelled request", "AbortError");+ });return data;}@@ -194,3 +211,10 @@ export function wsQuery(workspaceId: string, extra?: Record<string, string>): stconst params = new URLSearchParams({ workspace_id: workspaceId, ...extra });return `?${params.toString()}`;}++export async function readApiResponse<T>(response: Response, format: "json" | "text", options?: ApiRequestOptions): Promise<T> {+ return readObservedResponse(response, () => format === "text" ? response.text() as Promise<T> : response.json() as Promise<T>, () => {+ options?.assertActive?.();+ if (options?.signal?.aborted) throw new DOMException("Cancelled request", "AbortError");+ });+}diff --git a/src/web/src/lib/api/conversations.ts b/src/web/src/lib/api/conversations.tsindex 0cdd23555..8229e5c58 100644--- a/src/web/src/lib/api/conversations.ts+++ b/src/web/src/lib/api/conversations.ts@@ -1,3 +1,4 @@+import { readApiResponse } from "./client";import type {Artifact,Conversation,@@ -157,8 +158,8 @@ export const sendMessage = async (if (blob) fd.append(`thumbnail:${i}`, blob, "thumbnail.jpg");}- const res = await apiFetchResponse(`/api/conversations/${conversationId}/messages${wsQuery(workspaceId)}`, { ...options, method: "POST", body: fd });- const data = await res.json() as { message: Message; task: TaskApi };+ const res = await apiFetchResponse(`/api/conversations/${conversationId}/messages${wsQuery(workspaceId)}`, { ...options, method: "POST", body: fd }, true);+ const data = await readApiResponse(res, "json", options) as { message: Message; task: TaskApi };options?.assertActive?.();if (options?.signal?.aborted) throw new DOMException("Cancelled chat upload", "AbortError");return data;diff --git a/src/web/src/lib/api/emails.ts b/src/web/src/lib/api/emails.tsindex d23b209d5..40c4fcccf 100644--- a/src/web/src/lib/api/emails.ts+++ b/src/web/src/lib/api/emails.ts@@ -1,3 +1,4 @@+import { readApiResponse } from "./client";import type { Email } from "@alook/shared";import { ApiError } from "@/lib/errors";import { apiFetch, apiFetchResponse, wsQuery, type ApiRequestOptions } from "./client";@@ -13,14 +14,14 @@ export const getEmailThread = (id: string, workspaceId: string, options?: ApiReqexport const getEmailBody = async (id: string, workspaceId: string, options?: ApiRequestOptions): Promise<{ content: string; isHtml: boolean }> => {let res: Response;- try { res = await apiFetchResponse(`/api/email/${id}/body${wsQuery(workspaceId)}`, options); }+ try { res = await apiFetchResponse(`/api/email/${id}/body${wsQuery(workspaceId)}`, options, true); }catch (error) {options?.assertActive?.();if (error instanceof ApiError && error.status !== 401) return { content: "(body not available)", isHtml: false };throw error;}const contentType = res.headers.get("Content-Type") ?? "";- const content = await res.text();+ const content = await readApiResponse<string>(res, "text", options);options?.assertActive?.();if (options?.signal?.aborted) throw new DOMException("Cancelled request", "AbortError");return { content, isHtml: contentType.includes("text/html") };@@ -54,7 +55,7 @@ export const uploadEmailAttachment = async (body: fd,});if (!res.ok) {- const msg = await res.text().catch(() => "Upload failed");+ const msg = await readApiResponse<string>(res, "text").catch(() => "Upload failed");throw new ApiError(msg, res.status);}return res.json();diff --git a/src/web/src/lib/api/issues.ts b/src/web/src/lib/api/issues.tsindex 25dc89c48..ee1b54b31 100644--- a/src/web/src/lib/api/issues.ts+++ b/src/web/src/lib/api/issues.ts@@ -1,3 +1,4 @@+import { readApiResponse } from "./client";import type {Artifact,Issue,@@ -55,8 +56,8 @@ export const createIssue = async (fd.append("file", file);}- const res = await apiFetchResponse(`/api/issues${wsQuery(workspaceId)}`, { ...options, method: "POST", body: fd });- const data = await res.json() as { issue: Issue; message?: Message; task?: TaskApi };+ const res = await apiFetchResponse(`/api/issues${wsQuery(workspaceId)}`, { ...options, method: "POST", body: fd }, true);+ const data = await readApiResponse(res, "json", options) as { issue: Issue; message?: Message; task?: TaskApi };options?.assertActive?.();if (options?.signal?.aborted) throw new DOMException("Cancelled issue upload", "AbortError");return data;diff --git a/src/web/src/lib/api/observability-consumers.test.ts b/src/web/src/lib/api/observability-consumers.test.tsnew file mode 100644index 000000000..93a6ddbef--- /dev/null+++ b/src/web/src/lib/api/observability-consumers.test.ts@@ -0,0 +1,34 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest"+import { getArtifactContent } from "./artifacts"+import { createIssue } from "./issues"+import { sendMessage } from "./conversations"+import { uploadEmailAttachment } from "./emails"+import { configureTelemetry, installTelemetrySink, retireTelemetry } from "../observability/telemetry"++const fetch = vi.fn(), events: Array<{ name: string; attributes: Record<string, string> }> = []+beforeEach(() => { fetch.mockReset(); events.length = 0; vi.stubGlobal("fetch", fetch); configureTelemetry({ session_id: "consumer-session" }, true); installTelemetrySink(event => events.push(event)) })+afterEach(() => { retireTelemetry(); vi.unstubAllGlobals() })+it("returns artifact text after observed parsing and preserves active owner checks", async () => {+ fetch.mockResolvedValue(new Response("private-artifact-body"))+ const assertActive = vi.fn()+ expect(await getArtifactContent("artifact-a", "workspace-a", { assertActive })).toBe("private-artifact-body")+ expect(fetch).toHaveBeenCalledWith("/api/artifacts/artifact-a/content?workspace_id=workspace-a", expect.any(Object))+ expect(assertActive).toHaveBeenCalled()+ expect(events.some(event => event.name === "request.body_parsed" && event.attributes.route_template === "/api/artifacts/[id]/content")).toBe(true)+ expect(JSON.stringify(events)).not.toContain("private-artifact-body")+})+it("preserves multipart issue and conversation responses through observed JSON parsing", async () => {+ const issue = { issue: { id: "issue-a" } }, message = { message: { id: "message-a" }, task: { id: "task-a" } }+ fetch.mockResolvedValueOnce(Response.json(issue)).mockResolvedValueOnce(Response.json(message))+ const file = new File(["private-file-body"], "private.txt", { type: "text/plain" })+ expect(await createIssue("workspace-a", { title: "private-title", agent_id: "agent-a", files: [file] })).toEqual(issue)+ expect(await sendMessage("conversation-a", "private-message", "workspace-a", [{ file, thumbnailUrl: null, thumbnailBlob: null }])).toEqual(message)+ expect(fetch.mock.calls.every(([, options]) => options.method === "POST" && options.body instanceof FormData)).toBe(true)+ expect(events.filter(event => event.name === "request.body_parsed")).toHaveLength(2)+ expect(JSON.stringify(events)).not.toMatch(/private-(?:file|message|title)/)+})+it("retains email upload status and text failure without leaking its body", async () => {+ fetch.mockResolvedValue(new Response("private-upload-error", { status: 413 }))+ await expect(uploadEmailAttachment(new File(["private"], "private.txt"), "workspace-a")).rejects.toMatchObject({ status: 413, message: "private-upload-error" })+ expect(JSON.stringify(events)).not.toContain("private-upload-error")+})diff --git a/src/web/src/lib/application-owner.tsx b/src/web/src/lib/application-owner.tsxindex 1f1a9f45e..dd85f8d4e 100644--- a/src/web/src/lib/application-owner.tsx+++ b/src/web/src/lib/application-owner.tsx@@ -14,6 +14,9 @@ import { DEFAULT_INBOX_TYPES, readStoredInboxFilterTypes } from "@/lib/inbox-filimport { createQueryClient } from "@/lib/query-client"import { getNotificationEnabled, getNotificationEvents, NOTIFICATION_EVENTS, type NotificationEvent } from "@/lib/browser-notification"import type { ApiRequestOptions } from "@/lib/api/client"+import { observeHydration, discardHydration } from "@/lib/observability/restore"+import { disposeQueryDiagnostics } from "@/lib/observability/query-observer"+import { captureTelemetryIdentityRetirement, setTelemetryUser } from "@/lib/observability/client"export function createApplicationOwner(userId: string, queryClient = createQueryClient()) {const bindings = createStore({ retireDisk: () => clearPersistedCache(userId), sessionViewer: () => userId as string | null | undefined })@@ -82,6 +85,8 @@ function ScopedApplicationQueryProvider({ userId, children, session, sessionViewconst [owner] = useState(() => createApplicationOwner(userId))const [handles] = useState(() => ({ owner }))const [persister] = useState(() => createIdbPersister(userId, "application"))+ const retireTelemetryIdentity = useRef<() => void>(() => undefined)+ useLayoutEffect(() => { setTelemetryUser(userId); retireTelemetryIdentity.current = captureTelemetryIdentityRetirement() }, [userId])const disposeTimer = useRef<ReturnType<typeof setTimeout> | null>(null)useEffect(() => {const hydrate = () => {@@ -115,22 +120,25 @@ function ScopedApplicationQueryProvider({ userId, children, session, sessionView}}, [owner])useLayoutEffect(() => {- if (!identityChanged || !owner.lifecycle.get().active) return+ if (!identityChanged) return+ if (!session.data?.user.id && sessionViewer?.() === null) retireTelemetryIdentity.current()+ if (!owner.lifecycle.get().active) returnretireApplicationOwner(owner)void owner.queryClient.cancelQueries()owner.queryClient.clear()void owner.retireDisk().catch(() => undefined)if (!session.data?.user.id) router.replace("/sign-in")else router.refresh()- }, [identityChanged, owner, router, session.data?.user.id])+ }, [identityChanged, owner, router, session.data?.user.id, sessionViewer])return <StoreProvider value={handles}>- <PersistQueryClientProvider client={owner.queryClient} onSuccess={() => { if (!owner.lifecycle.get().active) owner.queryClient.clear() }} persistOptions={{ persister, buster: `${PERSIST_BUSTER}-application`, maxAge: PERSIST_MAX_AGE_MS, dehydrateOptions: { shouldDehydrateQuery: (query) => query.state.status === "success" && shouldPersistApplicationQuery(query.queryKey), shouldDehydrateMutation: () => false } }}>+ <PersistQueryClientProvider client={owner.queryClient} onSuccess={() => { if (!owner.lifecycle.get().active) { discardHydration(persister); owner.queryClient.clear(); return } observeHydration(persister, owner.queryClient) }} persistOptions={{ persister, buster: `${PERSIST_BUSTER}-application`, maxAge: PERSIST_MAX_AGE_MS, dehydrateOptions: { shouldDehydrateQuery: (query) => query.state.status === "success" && shouldPersistApplicationQuery(query.queryKey), shouldDehydrateMutation: () => false } }}>{active && !identityChanged ? children : null}</PersistQueryClientProvider></StoreProvider>}export function retireApplicationOwner(owner: ApplicationOwner) {+ disposeQueryDiagnostics(owner.queryClient)owner.preferences.setState((state) => ({ ...state, localValues: new Map() }))owner.lifecycle.setState((state) => state.active ? { active: false, generation: state.generation + 1 } : state)void owner.queryClient.cancelQueries()diff --git a/src/web/src/lib/auth-client.ts b/src/web/src/lib/auth-client.tsindex a92a8a65f..cb2cf344b 100644--- a/src/web/src/lib/auth-client.ts+++ b/src/web/src/lib/auth-client.ts@@ -1,6 +1,7 @@"use client"import { createAuthClient } from "better-auth/react"import { emailOTPClient, deviceAuthorizationClient } from "better-auth/client/plugins"+import { captureTelemetryIdentityRetirement } from "@/lib/observability/client"import {resumeMobileSystemNotificationRegistration,suspendMobileSystemNotificationRegistration,@@ -22,12 +23,14 @@ async function signOutOriginal(assertOriginal: () => void, args: Parameters<typeconst options = args[0]?.fetchOptions ?? args[1]const assertActive = () => { if (options?.signal?.aborted) throw new DOMException("Retired sign-out", "AbortError"); assertOriginal() }assertActive()+ const finishTelemetrySignOut = captureTelemetryIdentityRetirement()suspendMobileSystemNotificationRegistration()try {await unregisterCurrentMobileSystemNotification(fetch, { signal: options?.signal ?? undefined, assertActive }).catch(() => { assertActive() })assertActive()const result = await authClient.signOut(...args)if ("error" in result && result.error) { assertActive(); resumeMobileSystemNotificationRegistration() }+ else { assertActive(); finishTelemetrySignOut() }return result} catch (error) {try { assertActive(); resumeMobileSystemNotificationRegistration() } catch {}diff --git a/src/web/src/lib/community-db/collections.ts b/src/web/src/lib/community-db/collections.tsindex 9912f4077..d421e2308 100644--- a/src/web/src/lib/community-db/collections.ts+++ b/src/web/src/lib/community-db/collections.ts@@ -1,4 +1,5 @@import { clearPersistedCache } from "@/lib/query-persister"+import { disposeQueryDiagnostics } from "@/lib/observability/query-observer"import {DbClient,BasicIndex,@@ -311,7 +312,7 @@ function buildCommunityDbRegistry(type CollectionName = keyof typeof collectionsconst restoration = createStore({ captured: false, names: new Set<string>(), hasData: false })const runtime = {- ui: createCommunityStore(), ws: createCommunityWsStore(accountId), messageStream: createMessageStreamStore(() => new Map(Array.from(messages.values()).flatMap((message) => typeof message.seq === "number" ? [[message.id, message as CanonicalMessage] as const] : []))),+ ui: createCommunityStore(), ws: createCommunityWsStore(accountId), messageStream: createMessageStreamStore(() => new Map(Array.from(messages.values()).flatMap((message) => typeof message.seq === "number" ? [[message.id, message as CanonicalMessage] as const] : [])), queryClient),serverEject: createOwnerServerDeleteStore(),lifecycle: createStore({ active: true, generation: 0 }), transport: { send: null as ((message: object) => void) | null },}@@ -352,6 +353,7 @@ function buildCommunityDbRegistry(hasRestoredData: () => restoration.get().hasData,preload: () => Promise.all(Object.values(collections).map((collection) => collection.preload())),cleanup: () => {+ disposeQueryDiagnostics(queryClient)cancelActiveConversationNavigationProof(queryClient)if (registryByQueryClient.get(queryClient) === registry) registryByQueryClient.delete(queryClient)runtime.lifecycle.setState((state) => ({ active: false, generation: state.generation + 1 }))diff --git a/src/web/src/lib/community-db/projections-unowned.dom.test.ts b/src/web/src/lib/community-db/projections-unowned.dom.test.tsnew file mode 100644index 000000000..2a827a7ca--- /dev/null+++ b/src/web/src/lib/community-db/projections-unowned.dom.test.ts@@ -0,0 +1,19 @@+import { expect, it, vi } from "vitest"+import { renderHook } from "@/test/react-dom-harness"+import { configureTelemetry, retireTelemetry } from "@/lib/observability/telemetry"+import { viewEvidence } from "@/lib/observability/data-source"++vi.mock("@tanstack/react-db", async importOriginal => {+ const real = await importOriginal<typeof import("@tanstack/react-db")>()+ return { ...real, useLiveQuery: () => ({ data: [{ id: "server-a", name: "Unowned snapshot", detailComplete: true, ownerId: "viewer" }] }) }+})+it("does not attribute an upstream cached tree snapshot to an absent community owner", async () => {+ const { useServerTreeProjection } = await import("./projections")+ configureTelemetry({ session_id: "snapshot-session" }, true)+ try {+ const rendered = renderHook(() => useServerTreeProjection("server-a"))+ expect(rendered.result.current).toMatchObject({ id: "server-a", name: "Unowned snapshot", categories: [] })+ expect(viewEvidence(rendered.result.current).source).toBe("unknown")+ rendered.unmount()+ } finally { retireTelemetry() }+})diff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.tsindex 39a00f809..03edcfc26 100644--- a/src/web/src/lib/community-db/projections.ts+++ b/src/web/src/lib/community-db/projections.ts@@ -17,6 +17,7 @@ import type { ChannelRefDirectory } from "@/lib/community/channel-ref"import type { CommunityDbRegistry } from "./collections"import { useCommunityPreviewProfiles } from "@/stores/community/profile-preview"import { MAX_PERSISTED_MESSAGES_PER_SCOPE } from "@/lib/query-persister"+import { collectionEvidence, deriveView, sourceEvidence, tagView, viewEvidence } from "@/lib/observability/data-source"import type {AttentionItemRow,@@ -35,6 +36,30 @@ import type {ServerRow,} from "./schema"+function annotateRows<T extends object>(registry: CommunityDbRegistry | null, collection: string, rows: T[] | undefined): T[] | undefined {+ if (!registry || !rows) return rows+ const key = (row: T) => String((row as Record<string, unknown>).id ?? (row as Record<string, unknown>).userId ?? (row as Record<string, unknown>).scopeId)+ for (const row of rows) tagView(row, collectionEvidence(registry.queryClient, collection, [key(row)], [row]))+ return tagView(rows, collectionEvidence(registry.queryClient, collection, rows.map(key), rows))+}++const presenceVersions = new WeakMap<CommunityDbRegistry, Map<string, { value: string; token: object }>>()+function presenceVersion(registry: CommunityDbRegistry, userId: string, value: string) {+ let entries = presenceVersions.get(registry)+ if (!entries) { entries = new Map(); presenceVersions.set(registry, entries) }+ const old = entries.get(userId)+ const token = old?.value === value ? old.token : {}+ entries.set(userId, { value, token })+ if (entries.size > 2048) entries.delete(entries.keys().next().value!)+ return sourceEvidence(token, "ws")+}++function projectedMessage(registry: CommunityDbRegistry | null, message: MessageRow, child?: ChannelRow): Msg {+ const { channelId: _channelId, replyToId: _replyToId, ...model } = message+ const value = { ...model, ...(child ? { thread: { id: child.id, name: child.name, messageCount: child.messageCount ?? 0, lastReplyAt: child.lastMessageAt ?? undefined, tags: child.tags, preview: child.preview, participantCount: child.participantCount } } : {}) } as Msg+ return registry ? deriveView(value, [collectionEvidence(registry.queryClient, "messages", [message.id], [message]), ...(child ? [collectionEvidence(registry.queryClient, "channels", [child.id], [child])] : [])]) : value+}+let communityDbContext: Context<CommunityDbRegistry | null> | null = nullfunction getCommunityDbContext() {@@ -98,61 +123,67 @@ export function CommunityDbProvider({function useServerRows(serverId?: string) {const registry = useOptionalCommunityDbRegistry()- return useLiveQuery({+ const data = useLiveQuery({query: (q) => registry? q.from({ server: registry.collections.servers }).where(({ server }) => serverId === undefined ? eq(1, 1) : eq(server.id, serverId)): undefined,}).data as ServerRow[] | undefined+ return annotateRows(registry, "servers", data)}function useCategoryRows(serverId?: string) {const registry = useOptionalCommunityDbRegistry()- return useLiveQuery({+ const data = useLiveQuery({query: (q) => registry? q.from({ category: registry.collections.categories }).where(({ category }) => serverId === undefined ? eq(1, 1) : eq(category.serverId, serverId)): undefined,}).data as CategoryRow[] | undefined+ return annotateRows(registry, "categories", data)}function useServerMembershipRows() {const registry = useOptionalCommunityDbRegistry()- return useLiveQuery({+ const data = useLiveQuery({query: (q) => registry? q.from({ membership: registry.collections.serverMemberships }): undefined,}).data as ServerMembershipRow[] | undefined+ return annotateRows(registry, "serverMemberships", data)}function useFolderRows() {const registry = useOptionalCommunityDbRegistry()- return useLiveQuery({+ const data = useLiveQuery({query: (q) => registry? q.from({ folder: registry.collections.folders }): undefined,}).data as FolderRow[] | undefined+ return annotateRows(registry, "folders", data)}function useFolderItemRows() {const registry = useOptionalCommunityDbRegistry()- return useLiveQuery({+ const data = useLiveQuery({query: (q) => registry? q.from({ item: registry.collections.folderItems }): undefined,}).data as FolderItemRow[] | undefined+ return annotateRows(registry, "folderItems", data)}function useNotificationSettingRows() {const registry = useOptionalCommunityDbRegistry()- return useLiveQuery({+ const data = useLiveQuery({query: (q) => registry? q.from({ setting: registry.collections.notificationSettings }): undefined,}).data as NotificationSettingRow[] | undefined+ return annotateRows(registry, "notificationSettings", data)}function useChannelRows(serverId?: string, type?: ChannelRow["type"]) {const registry = useOptionalCommunityDbRegistry()- return useLiveQuery({+ const data = useLiveQuery({query: (q) => {if (!registry) return undefinedlet query = q.from({ channel: registry.collections.channels })@@ -161,25 +192,28 @@ function useChannelRows(serverId?: string, type?: ChannelRow["type"]) {return query},}).data as ChannelRow[] | undefined+ return annotateRows(registry, "channels", data)}function useChannelMembershipRows(channelIds?: string[]) {const registry = useOptionalCommunityDbRegistry()- return useLiveQuery({+ const data = useLiveQuery({query: (q) => registry? q.from({ membership: registry.collections.channelMemberships }).where(({ membership }) => channelIds === undefined ? eq(1, 1) : inArray(membership.channelId, channelIds)): undefined,}).data as ChannelMembershipRow[] | undefined+ return annotateRows(registry, "channelMemberships", data)}function useMessageRowsById(messageIds: string[]) {const registry = useOptionalCommunityDbRegistry()- return useLiveQuery({+ const data = useLiveQuery({query: (q) => registry? q.from({ message: registry.collections.messages }).where(({ message }) => inArray(message.id, messageIds)): undefined,}).data as MessageRow[] | undefined+ return annotateRows(registry, "messages", data)}export function useServerRailProjection() {@@ -246,11 +280,21 @@ export function useServerRailProjection() {}] : []}),}))- return { servers, folders }+ deriveView(servers, [+ collectionEvidence(rows.registry.queryClient, "servers", rows.servers.map(row => row.id), rows.servers),+ collectionEvidence(rows.registry.queryClient, "serverMemberships", rows.serverMemberships.map(row => row.id), rows.serverMemberships),+ ])+ deriveView(folders, [+ viewEvidence(servers),+ collectionEvidence(rows.registry.queryClient, "folders", (rows.folders ?? []).map(row => row.id), rows.folders ?? []),+ collectionEvidence(rows.registry.queryClient, "folderItems", (rows.folderItems ?? []).map(row => row.id), rows.folderItems ?? []),+ ])+ return deriveView({ servers, folders }, [viewEvidence(servers), viewEvidence(folders)], servers.length + folders.length)}, [rows.registry, rows.servers, rows.serverMemberships, rows.folders, rows.folderItems])}export function useServerTreeProjection(serverId: string | null) {+ const registry = useOptionalCommunityDbRegistry()const rows = {servers: useServerRows(serverId ?? ""),categories: useCategoryRows(serverId ?? ""),@@ -304,17 +348,18 @@ export function useServerTreeProjection(serverId: string | null) {if (uncategorized.length > 0) {categories.push({ id: "__uncategorized__", name: "", private: false, channels: uncategorized })}- return {- id: server.id,- name: server.name,- discriminator: server.discriminator,- description: server.description,- icon: server.icon,- official: server.official,- ownerId: server.ownerId,- categories,+ if (registry) deriveView(categories, [collectionEvidence(registry.queryClient, "categories", rows.categories.map(row => row.id), rows.categories), collectionEvidence(registry.queryClient, "channels", channels.map(row => row.id), channels)], channels.length)+ const view = {+ id: server.id, name: server.name, discriminator: server.discriminator,+ description: server.description, icon: server.icon, official: server.official,+ ownerId: server.ownerId, categories,}- }, [rows.servers, rows.categories, rows.channels, serverId])+ return registry ? deriveView(view, [+ collectionEvidence(registry.queryClient, "servers", [server.id], [server]),+ collectionEvidence(registry.queryClient, "categories", rows.categories.map(row => row.id), rows.categories),+ collectionEvidence(registry.queryClient, "channels", channels.map(row => row.id), channels),+ ], channels.length) : view+ }, [rows.servers, rows.categories, rows.channels, serverId, registry])}export function useDmProjection() {@@ -342,7 +387,7 @@ export function useDmProjection() {const channelMemberships = rows.channelMembershipsconst profileById = new Map(rows.profiles.map((profile) => [profile.userId, profile]))const readStateByChannel = new Map((rows.readStates ?? []).map((state) => [state.channelId, state]))- return sortDmsByActivity(rows.channels+ const result = sortDmsByActivity(rows.channels.filter((channel) => channel.type === "dm").flatMap((channel): DM[] => {const peerMembership = channelMemberships.find((membership) => (@@ -370,7 +415,8 @@ export function useDmProjection() {: { lastUnreadSeq: channel.lastUnreadSeq ?? readState?.lastReadSeq }),}]}))- }, [rows.registry?.accountId, rows.channels, rows.channelMemberships, rows.profiles, rows.readStates])+ return deriveView(result, [viewEvidence(rows.channels), viewEvidence(rows.channelMemberships), collectionEvidence(rows.registry!.queryClient, "profiles", rows.profiles.map(row => row.userId), rows.profiles), collectionEvidence(rows.registry!.queryClient, "readStates", (rows.readStates ?? []).map(row => row.channelId), rows.readStates)])+ }, [rows.registry, rows.channels, rows.channelMemberships, rows.profiles, rows.readStates])}export function useRouteChannelProjection(channelId: string | null) {@@ -418,13 +464,13 @@ export function useMessageProjection(channelId: string | null, ids?: readonly st})return useMemo(() => {if (!channelId || !result.data) return undefined- return (result.data as Array<{ message: MessageRow; child?: ChannelRow }>)+ const messages = (result.data as Array<{ message: MessageRow; child?: ChannelRow }>).sort((a, b) => (a.message.seq ?? 0) - (b.message.seq ?? 0)).map(({ message, child }) => {- const { channelId: _channelId, replyToId: _replyToId, ...model } = message- return { ...model, ...(child ? { thread: { id: child.id, name: child.name, messageCount: child.messageCount ?? 0, lastReplyAt: child.lastMessageAt ?? undefined, tags: child.tags, preview: child.preview, participantCount: child.participantCount } } : {}) } as Msg+ return projectedMessage(registry, message, child)})- }, [channelId, result.data])+ return deriveView(messages, messages.map(viewEvidence))+ }, [channelId, result.data, registry])}export function useCanonicalMessagesById(ids?: readonly string[]): ReadonlyMap<string, Msg> | undefined {@@ -439,8 +485,7 @@ export function useCanonicalMessagesById(ids?: readonly string[]): ReadonlyMap<s})return useMemo(() => !registry ? undefined : new Map(((result.data ?? []) as Array<{ message: MessageRow; child?: ChannelRow }>).map(({ message, child }) => {- const { channelId: _channelId, replyToId: _replyToId, ...model } = message- return [message.id, { ...model, ...(child ? { thread: { id: child.id, name: child.name, messageCount: child.messageCount ?? 0, lastReplyAt: child.lastMessageAt ?? undefined, tags: child.tags, preview: child.preview, participantCount: child.participantCount } } : {}) } as Msg]+ return [message.id, projectedMessage(registry, message, child)]}),), [registry, result.data])}@@ -464,8 +509,8 @@ export function useCanonicalChannelsById(): ReadonlyMap<string, ChannelRow> {: undefined,})return useMemo(() => new Map(- ((result.data ?? []) as ChannelRow[]).map((channel) => [channel.id, channel]),- ), [result.data])+ (annotateRows(registry, "channels", (result.data ?? []) as ChannelRow[])!).map((channel) => [channel.id, channel]),+ ), [result.data, registry])}export function useFriendshipRows(ids?: readonly string[]) {@@ -481,8 +526,8 @@ export function useCanonicalServersById(): ReadonlyMap<string, ServerRow> {: undefined,})return useMemo(() => new Map(- ((result.data ?? []) as ServerRow[]).map((server) => [server.id, server]),- ), [result.data])+ (annotateRows(registry, "servers", (result.data ?? []) as ServerRow[])!).map((server) => [server.id, server]),+ ), [result.data, registry])}export function useCanonicalCommunityServer(serverId: string | null | undefined) {@@ -552,24 +597,29 @@ export function useCanonicalProfilesByUserId(userIds?: readonly string[]): Readoif (previewProfiles) return previewProfilesconst merged = new Map<string, CommunityProfile>()for (const [userId, profile] of canonicalProfiles) {- merged.set(userId, { ...profile, id: userId })+ merged.set(userId, registry ? deriveView({ ...profile, id: userId }, [collectionEvidence(registry.queryClient, "profiles", [userId], [profile])]) : { ...profile, id: userId })}for (const [userId, presence] of livePresence ?? []) {if (presence === undefined) continue- merged.set(userId, { ...merged.get(userId), id: userId, presence })+ const prior = merged.get(userId)+ const value = { ...prior, id: userId, presence }+ const presenceEvidence = registry ? presenceVersion(registry, userId, presence) : viewEvidence(value)+ merged.set(userId, deriveView(value, [...(prior ? [viewEvidence(prior)] : []), presenceEvidence]))}return merged- }, [canonicalProfiles, livePresence, previewProfiles])+ }, [canonicalProfiles, livePresence, previewProfiles, registry])}export function useServerMemberRows(serverId: string | null, userIds: readonly string[]) {const registry = useOptionalCommunityDbRegistry()- return (useLiveQuery({ query: (q) => registry && serverId ? q.from({ membership: registry.collections.serverMemberships }).where(({ membership }) => eq(membership.serverId, serverId)).where(({ membership }) => inArray(membership.userId, [...userIds])) : undefined }).data ?? []) as ServerMembershipRow[]+ const data = (useLiveQuery({ query: (q) => registry && serverId ? q.from({ membership: registry.collections.serverMemberships }).where(({ membership }) => eq(membership.serverId, serverId)).where(({ membership }) => inArray(membership.userId, [...userIds])) : undefined }).data ?? []) as ServerMembershipRow[]+ return annotateRows(registry, "serverMemberships", data)!}export function useChannelRosterRows(channelId: string, relation: "access" | "notify") {const registry = useOptionalCommunityDbRegistry()- return (useLiveQuery({ query: (q) => registry && channelId ? q.from({ membership: registry.collections.channelMemberships }).where(({ membership }) => eq(membership.channelId, channelId)).where(({ membership }) => eq(membership.relation, relation)) : undefined }).data ?? []) as ChannelMembershipRow[]+ const data = (useLiveQuery({ query: (q) => registry && channelId ? q.from({ membership: registry.collections.channelMemberships }).where(({ membership }) => eq(membership.channelId, channelId)).where(({ membership }) => eq(membership.relation, relation)) : undefined }).data ?? []) as ChannelMembershipRow[]+ return annotateRows(registry, "channelMemberships", data)!}export function useCanonicalCommunityProfile(userId: string | null | undefined) {@@ -580,8 +630,12 @@ export function useCanonicalCommunityProfile(userId: string | null | undefined)return useMemo(() => {if (!userId) return undefinedif (preview) return preview.get(userId)- return profile || presence ? { ...profile, id: userId, ...(presence ? { presence } : {}) } : undefined- }, [userId, preview, profile, presence])+ if (!profile && !presence) return undefined+ return deriveView({ ...profile, id: userId, ...(presence ? { presence } : {}) }, [+ ...(profile && registry ? [collectionEvidence(registry.queryClient, "profiles", [profile.userId], [profile])] : []),+ ...(presence && registry ? [presenceVersion(registry, userId, presence)] : []),+ ])+ }, [userId, preview, profile, presence, registry])}export function useAttentionScopes(): readonly AttentionScopeRow[] {@@ -591,7 +645,7 @@ export function useAttentionScopes(): readonly AttentionScopeRow[] {? q.from({ scope: registry.collections.attentionScopes }): undefined,})- return (result.data ?? []) as AttentionScopeRow[]+ return annotateRows(registry, "attentionScopes", (result.data ?? []) as AttentionScopeRow[])!}export function useAttentionItems(): readonly AttentionItemRow[] {@@ -601,7 +655,7 @@ export function useAttentionItems(): readonly AttentionItemRow[] {? q.from({ item: registry.collections.attentionItems }): undefined,})- return (result.data ?? []) as AttentionItemRow[]+ return annotateRows(registry, "attentionItems", (result.data ?? []) as AttentionItemRow[])!}export function useChannelRefDirectoryProjection(): ChannelRefDirectory | undefined {@@ -744,6 +798,7 @@ export function useForumSidebarProjection(parentUnread[child.parentChannelId] = true}}- return { threads, parentUnread }+ deriveView(threads, [viewEvidence(rows.channels), viewEvidence(rows.channelMemberships), viewEvidence(rows.messages)])+ return deriveView({ threads, parentUnread }, [viewEvidence(threads)], threads.length)}, [serverNowMs, rows.registry, rows.channels, rows.channelMemberships, rows.messages, serverId, retainId])}diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.tsindex c73a414e4..fa61e9a8f 100644--- a/src/web/src/lib/community-db/sync.ts+++ b/src/web/src/lib/community-db/sync.ts@@ -1,4 +1,5 @@import type { Transaction } from "@tanstack/react-db"+import { currentSource, withSource } from "@/lib/observability/data-source"import { communityRequestOptions as qualifiedCommunityRequestOptions } from "@/lib/community/account-cache-lifecycle"import { isAbortError } from "@/lib/errors"import { isOwnerServerDeleteScopeEvictionBlocked } from "@/lib/community/eject-server"@@ -261,7 +262,7 @@ function withCanonicalWriteContext<T>(const previous = canonicalWriteContexts.get(queryClient)canonicalWriteContexts.set(queryClient, context)try {- return publish()+ return withSource(queryClient, currentSource(queryClient) === "ws" ? "ws" : context.kind === "query" ? "network" : "local_mutation", publish)} finally {if (previous) canonicalWriteContexts.set(queryClient, previous)else canonicalWriteContexts.delete(queryClient)diff --git a/src/web/src/lib/community-db/write.ts b/src/web/src/lib/community-db/write.tsindex 9d51f87a9..eebe76dc2 100644--- a/src/web/src/lib/community-db/write.ts+++ b/src/web/src/lib/community-db/write.ts@@ -2,6 +2,7 @@ import { replaceEqualDeep } from "@tanstack/react-query"import { hasVirtualProps } from "@tanstack/react-db"import { communityKeys } from "@/lib/query-keys"import type { CommunityDbRegistry } from "./collections"+import { recordRows } from "@/lib/observability/data-source"function businessRow<T extends object>(row: T): T {return hasVirtualProps(row)@@ -31,6 +32,7 @@ export function writeCommunityCollectionRows<T extends object>(communityKeys.communityDbCollection(registry.scopeId, name),rows,)+ recordRows(registry.queryClient, name, registry.queryClient.getQueryData<T[]>(communityKeys.communityDbCollection(registry.scopeId, name)) ?? rows, getKey)return}const committed = registry.queryClient.getQueryData<T[]>(communityKeys.communityDbCollection(registry.scopeId, name))@@ -43,9 +45,13 @@ export function writeCommunityCollectionRows<T extends object>(const previousData = businessRow(previous)return replaceEqualDeep(previousData, row) !== previousData})- if (removed.length === 0 && changed.length === 0) return+ if (removed.length === 0 && changed.length === 0) {+ recordRows(registry.queryClient, name, rows, getKey)+ return+ }collection.utils.writeBatch(() => {if (removed.length > 0) collection.utils.writeDelete(removed)if (changed.length > 0) collection.utils.writeUpsert(changed)})+ recordRows(registry.queryClient, name, rows, getKey)}diff --git a/src/web/src/lib/community/account-cache-lifecycle.ts b/src/web/src/lib/community/account-cache-lifecycle.tsindex aa086a0ac..1c5342caa 100644--- a/src/web/src/lib/community/account-cache-lifecycle.ts+++ b/src/web/src/lib/community/account-cache-lifecycle.ts@@ -1,3 +1,4 @@+import { commandObservation } from "@/lib/observability/context"import { clearComposerAttachmentSessionsForAccount } from "./composer-attachment-session"import type { ApiRequestOptions } from "@/lib/api/client"import { getCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"@@ -13,7 +14,7 @@ export function retireCommunityAccount(registry: CommunityDbRegistry) {}export function communityRequestOptions(queryClient: QueryClient, token: CommunityLiveSnapshotToken, signal?: AbortSignal, assertActive = () => assertCommunityLiveSnapshotTokenCurrent(queryClient, token, signal)): ApiRequestOptions & { assertActive: () => void } {const registry = getCommunityDbRegistry(queryClient)- return { authenticationAccount: registry?.accountId ?? undefined, signal, assertActive, onUnauthorized: async () => {+ return { observation: commandObservation(token), authenticationAccount: registry?.accountId ?? undefined, signal, assertActive, onUnauthorized: async () => {assertActive()if (!registry || getCommunityDbRegistry(queryClient) !== registry || !registry.authenticationView.get().active) return falseconst generation = registry.authenticationView.get().generationdiff --git a/src/web/src/lib/community/message-list-items.ts b/src/web/src/lib/community/message-list-items.tsindex 2c67a491f..0a345457e 100644--- a/src/web/src/lib/community/message-list-items.ts+++ b/src/web/src/lib/community/message-list-items.ts@@ -1,3 +1,4 @@+import { deriveView, viewEvidence } from "@/lib/observability/data-source"import { dateKey, formatDateLabel } from "./format-time"import type { Msg, RenderMsg } from "./models/message"@@ -35,7 +36,7 @@ export function flattenMessageItems(&& prev.createdAt && m.createdAt && (new Date(m.createdAt).getTime() - new Date(prev.createdAt).getTime()) < MESSAGE_GROUP_WINDOW_MS)items.push({kind: "message",- m: { ...m, grouped },+ m: deriveView({ ...m, grouped }, [viewEvidence(m)]),key: messageDisplayKey(m),...(showDateDivider ? { dateLabel: formatDateLabel(m.createdAt!) } : {}),...(isNewDivider ? { newDivider: true } : {}),diff --git a/src/web/src/lib/community/message-stream.ts b/src/web/src/lib/community/message-stream.tsindex e4412549c..754861da6 100644--- a/src/web/src/lib/community/message-stream.ts+++ b/src/web/src/lib/community/message-stream.ts@@ -1,3 +1,4 @@+import { deriveView, sourceEvidence, viewEvidence } from "@/lib/observability/data-source"import type { Msg } from "@/lib/community/models/message"import type { MentionType } from "@alook/shared"import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"@@ -144,7 +145,7 @@ function upsertLiveCanonical(if (id !== message.id && compoundIdentity(current) === identity) liveById.delete(id)}}- liveById.set(message.id, { ...message, failed: false })+ liveById.set(message.id, deriveView({ ...message, failed: false }, [viewEvidence(message)]))}function mergeCanonicalAttachments(@@ -154,17 +155,17 @@ function mergeCanonicalAttachments(if (canonical.attachments !== undefined || !current.attachments?.length) {return canonical}- return { ...canonical, attachments: current.attachments }+ return deriveView({ ...canonical, attachments: current.attachments }, [viewEvidence(canonical), viewEvidence(current)])}function materializeIntent(intent: OutboxIntent): Msg {- return {+ return deriveView({...intent.message,id: intent.serverMessageId ?? intent.tempId,...(intent.serverSeq !== undefined ? { seq: intent.serverSeq } : {}),clientNonce: intent.nonce,failed: intent.status === "failed" || intent.uploadStatus === "failed",- }+ }, [sourceEvidence(intent, "local_mutation"), ...(intent.status === "acked" ? [viewEvidence(intent.message)] : [])])}function localUploadAttachments(@@ -437,7 +438,8 @@ export function reduceMessageOverlay(const liveById = new Map(state.liveById)const live = liveById.get(event.messageId)if (live) {- liveById.set(event.messageId, { ...live, content: event.content })+ const edited = { ...live, content: event.content }+ liveById.set(event.messageId, deriveView(edited, [viewEvidence(live), sourceEvidence(edited, "local_mutation")]))changed = true}const outboxByNonce = new Map(state.outboxByNonce)diff --git a/src/web/src/lib/community/models/message.ts b/src/web/src/lib/community/models/message.tsindex e3b1b34aa..799717f91 100644--- a/src/web/src/lib/community/models/message.ts+++ b/src/web/src/lib/community/models/message.ts@@ -1,4 +1,5 @@import type { FriendApprovalPayload } from "@alook/shared"+import { deriveView, viewEvidence } from "@/lib/observability/data-source"// ── Messages ───────────────────────────────────────────────────────────────type AttachmentMetadata = {@@ -161,7 +162,7 @@ export type MessagesWindowPage = Omit<MessagesPage, "messages"> & { messages: Arexport function messageWindowPage(page: MessagesPage): MessagesWindowPage {const newest = [...page.messages].filter((message) => message.createdAt).sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "") || a.id.localeCompare(b.id)).at(-1)- return { ...page, messages: page.messages.map((message) => ({ id: message.id, ...(message.seq === undefined ? {} : { seq: message.seq }) })), ...(newest?.createdAt ? { newestCursor: `${newest.createdAt}|${newest.id}` } : {}) }+ return deriveView({ ...page, messages: page.messages.map((message) => ({ id: message.id, ...(message.seq === undefined ? {} : { seq: message.seq }) })), ...(newest?.createdAt ? { newestCursor: `${newest.createdAt}|${newest.id}` } : {}) }, [viewEvidence(page)])}// Discriminated pageParam. The queryFn dispatches on `mode` — the URL paramdiff --git a/src/web/src/lib/community/profile-read.ts b/src/web/src/lib/community/profile-read.tsindex 8a659ac51..08398e471 100644--- a/src/web/src/lib/community/profile-read.ts+++ b/src/web/src/lib/community/profile-read.ts@@ -1,3 +1,4 @@+import { deriveView, viewEvidence } from "@/lib/observability/data-source"import { avatarInitial } from "@/lib/community/avatar"import type { CommunityProfile } from "@/lib/community/models/people"@@ -6,7 +7,7 @@ export function readCommunityProfile(userId: string,) {const name = profile?.name ?? "Deleted user"- return {+ return deriveView({id: userId,name,discriminator: profile?.discriminator ?? "",@@ -16,5 +17,5 @@ export function readCommunityProfile(statusEmoji: profile?.statusEmoji,statusText: profile?.statusText,presence: profile?.presence ?? "offline" as const,- }+ }, [viewEvidence(profile)])}diff --git a/src/web/src/lib/community/profile-seed.ts b/src/web/src/lib/community/profile-seed.tsindex 36ad2d193..8dc4b7e56 100644--- a/src/web/src/lib/community/profile-seed.ts+++ b/src/web/src/lib/community/profile-seed.ts@@ -14,6 +14,7 @@ import {} from "@/lib/community-db/collections"import { profileSchema, type ProfileRow } from "@/lib/community-db/schema"import { writeCommunityCollectionRows } from "@/lib/community-db/write"+import { currentSource, withSource } from "@/lib/observability/data-source"import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"type ProfileFieldRevisions = {@@ -212,7 +213,7 @@ export function writeCommunityProfilePatches(if (advanced && writeRevision !== null) revisions.revision = writeRevisionif (advanced) revisionStore.setState(() => revisions)const rows = [...profiles.values()]- writeCommunityCollectionRows(registry, "profiles", rows, (row) => row.userId)+ withSource(registry.queryClient, currentSource(registry.queryClient) === "ws" ? "ws" : options?.snapshot ? "network" : options?.command ? "local_mutation" : "unknown", () => writeCommunityCollectionRows(registry, "profiles", rows, (row) => row.userId))}export async function loadAndSeedProfiles<T>(diff --git a/src/web/src/lib/file-download.ts b/src/web/src/lib/file-download.tsindex 0b4514c70..8fd73a97b 100644--- a/src/web/src/lib/file-download.ts+++ b/src/web/src/lib/file-download.ts@@ -1,5 +1,6 @@"use client"+import { startAction, finishAction } from "./observability/context"import { useCallback, useLayoutEffect, useMemo } from "react"import { createStore } from "@tanstack/react-store"import { QueryObserver, queryOptions, useQuery, isCancelledError, type QueryKey } from "@tanstack/react-query"@@ -47,6 +48,7 @@ export async function cancelFileDownload(owner: ApplicationOwner, key: QueryKey)export async function startFileDownload(owner: ApplicationOwner, target: FileDownloadTarget, signal?: AbortSignal): Promise<FileSaveResult> {const token = captureApplicationOwner(owner)assertApplicationOwner(token, signal)+ const observation = startAction("attachment.download", { capability: "limited" })const options = downloadOptions(owner, target)const observer = new QueryObserver(owner.queryClient, { ...options, enabled: false })const unsubscribe = observer.subscribe(() => undefined)@@ -57,8 +59,10 @@ export async function startFileDownload(owner: ApplicationOwner, target: FileDowassertApplicationOwner(token, signal)const receipt = await owner.queryClient.fetchQuery(options)assertApplicationOwner(token, signal)+ finishAction(observation, receipt.status === "saved" ? "success" : receipt.status === "cancelled" ? "cancelled" : receipt.status === "error" ? "error" : "observed", { capability: receipt.status === "saved" ? "available" : "limited" })return receipt} catch (error) {+ finishAction(observation, isCancelledError(error) || isAbortError(error) ? "cancelled" : "error")if (isCancelledError(error) || isAbortError(error) || signal?.aborted) return { status: "cancelled" }throw error} finally {diff --git a/src/web/src/lib/observability/actions.ts b/src/web/src/lib/observability/actions.tsnew file mode 100644index 000000000..8bb6186d2--- /dev/null+++ b/src/web/src/lib/observability/actions.ts@@ -0,0 +1,111 @@+export const actionVariants = {+ "friend.command": { "send": "friend.request.send", "accept": "friend.request.accept", "reject": "friend.request.reject", "remove": "friend.remove", "cancel": "friend.request.cancel", "owner-decision": "friend.owner_decision.command", "block": "user.block", "unblock": "user.unblock" },+ "friend.owner_decision.command": { "approve": "friend.request.approve", "deny": "friend.request.deny" },+ "member.management.command": { "kick": "server.member.kick", "leave": "channel.member.leave", "remove": "channel.member.remove" },+ "billing.redirect": {+ "checkout": "billing.checkout.start",+ "portal": "billing.portal.open"+ },+ "calendar.command": {+ "create": "calendar.event.create",+ "update": "calendar.event.update",+ "delete": "calendar.event.delete"+ },+ "machine.command": {+ "delete": "machine.delete",+ "update": "machine.update"+ },+ "workspace.settings.command": {+ "update": "workspace.settings.update",+ "delete": "workspace.delete"+ },+ "workspace.members.command": {+ "create-invite": "workspace.invite.create",+ "revoke-invite": "workspace.invite.revoke",+ "remove-member": "workspace.member.remove"+ },+ "device.authorization.command": {+ "approve": "device.authorization.approve",+ "deny": "device.authorization.deny"+ },+ "chat.control.command": {+ "thread": "chat.thread.create",+ "stop": "chat.task.stop"+ },+ "account.deletion.command": {+ "code": "account.deletion.code.request",+ "delete": "account.delete"+ },+ "email.account.command": {+ "create": "email.account.connect",+ "delete": "email.account.delete",+ "sync": "email.account.sync"+ },+ "agent.rail.command": {+ "pin": "agent.pin",+ "unpin": "agent.unpin",+ "reorder-pins": "agent.pins.reorder",+ "reorder-unpinned": "agent.list.reorder"+ },+ "workspace.channel.command": {+ "create": "workspace.channel.create",+ "rename": "workspace.channel.rename",+ "delete": "workspace.channel.delete",+ "reorder": "workspace.channel.reorder"+ },+ "server.member.command": {+ "role": "server.member.role.change",+ "kick": "server.member.kick"+ },+ "bot.command": {+ "create-command": "bot.create",+ "active-command": "bot.active.change",+ "update-command": "bot.update",+ "delete-command": "bot.delete",+ "reset-command": "bot.session.reset",+ "machine-reset-command": "machine.agents.reset",+ "avatar-command": "bot.avatar.upload"+ },+ "channel.member.command": {+ "add": "channel.member.add",+ "remove": "channel.member.remove"+ },+ "chat.session.command": {+ "nap": "chat.session.nap",+ "retry": "chat.task.retry"+ },+ "agent.permission.command": {+ "whitelist-add": "agent.whitelist.add",+ "whitelist-remove": "agent.whitelist.remove",+ "visibility": "agent.visibility.change",+ "grant": "agent.access.grant",+ "revoke": "agent.access.revoke"+ },+ "issue.command": {+ "comment": "issue.comment.create",+ "create": "issue.create",+ "update": "issue.update",+ "delete": "issue.delete"+ },+ "runtime.command": {+ "update": "runtime.update",+ "rescan": "runtime.rescan"+ },+ "agent.link.command": { "create": "agent.link.create", "update": "agent.link.update", "delete": "agent.link.delete" },+ "email.command": { "send": "email.send", "read": "email.read", "delete": "email.delete", "trust": "email.sender.trust" },+ "chat.command": { "persist": "chat.message.persist", "read": "chat.inbox.read" },+ "meeting.command": { "stop": "meeting.stop", "approve": "meeting.approve",+ "create": "meeting.create",+ "update": "meeting.update",+ "delete": "meeting.delete"+ }+} as const++export function resolveActionName(base: string, variables: unknown): string {+ const value = variables && typeof variables === "object" ? variables as Record<string, unknown> : {}+ const action = value.action && typeof value.action === "object" ? value.action as Record<string, unknown> : {}+ const input = value.input && typeof value.input === "object" ? value.input as Record<string, unknown> : {}+ const kind = value.kind ?? action.kind ?? input.kind ?? value.action ?? value.decision+ const variants: Record<string, Readonly<Record<string, string>>> = actionVariants+ return variants[base] ? typeof kind === "string" ? variants[base]?.[kind] ?? "command.unknown" : "command.unknown" : base+}diff --git a/src/web/src/lib/observability/auth-client-observability.dom.test.tsx b/src/web/src/lib/observability/auth-client-observability.dom.test.tsxnew file mode 100644index 000000000..d9bb5e177--- /dev/null+++ b/src/web/src/lib/observability/auth-client-observability.dom.test.tsx@@ -0,0 +1,103 @@+import "fake-indexeddb/auto"+import { useLayoutEffect } from "react"+import { afterEach, expect, it, vi } from "vitest"+import { act, render, waitFor } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"++const backend = vi.hoisted(() => { const fetch = vi.fn(); vi.stubGlobal("fetch", fetch); return fetch })+vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))+vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))+vi.mock("@/lib/perf/react-scan-install", () => ({ installReactScan: vi.fn(async () => {}) }))+let mounted: ReturnType<typeof render> | undefined+afterEach(async () => {+ await act(async () => { mounted?.unmount(); mounted = undefined; document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied"); await new Promise(resolve => setTimeout(resolve, 0)) })+ window.history.replaceState(null, "", "/")+ vi.unstubAllEnvs(); vi.unstubAllGlobals()+})+it("real auth and Application sign-out preserve failure/B ownership and clear only the current successful user's native metadata", async () => {+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ vi.stubEnv("NEXT_PUBLIC_FARO_ENVIRONMENT", "qa")+ vi.stubEnv("NEXT_PUBLIC_FARO_RELEASE", "a".repeat(40))+ Object.defineProperty(performance, "getEntriesByType", { configurable: true, value: () => [] })+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ window.history.replaceState(null, "", "/workspaces")+ let selected: string | null = "account-a"+ let mode: "fail" | "hold" | "success" = "fail"+ let release!: (response: Response) => void+ const now = new Date().toISOString()+ const user = (id: string) => ({ id, name: "Private", email: "[email protected]", emailVerified: true, createdAt: now, updatedAt: now, image: null })+ const session = () => selected ? { user: user(selected), session: { id: "auth-" + selected, token: "fixture", userId: selected, expiresAt: new Date(Date.now() + 3600000).toISOString(), createdAt: now, updatedAt: now } } : null+ const sent: Array<{ meta: { session: { id: string }; user?: { id: string } }; events?: Array<{ name: string }> }> = []+ backend.mockImplementation(async (input: string | URL | Request, init?: RequestInit) => {+ const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, window.location.origin)+ if (url.hostname === "collector.example") { sent.push(JSON.parse(String(init?.body))); return new Response(null, { status: 204 }) }+ if (url.pathname.endsWith("/get-session")) return Response.json(session())+ if (url.pathname.endsWith("/sign-in/email")) { selected = "account-b"; return Response.json({ redirect: false, user: user(selected), token: "fixture" }) }+ if (url.pathname.endsWith("/sign-out")) {+ if (mode === "fail") return Response.json({ message: "Auth failed" }, { status: 400 })+ if (mode === "hold") return new Promise<Response>(resolve => { release = resolve })+ selected = null; return Response.json({ success: true })+ }+ throw new Error("Unexpected auth fixture path " + url.pathname)+ })+ const auth = await import("../auth-client")+ const Application = await import("../application-owner")+ const { useApplicationSignOut } = await import("@/hooks/use-application-sign-out")+ const { VolatileSessionsManager } = await import("@grafana/faro-web-sdk")+ const { emitTelemetry, isTelemetryEligible } = await import("./telemetry")+ let logout!: () => Promise<boolean>+ let owner!: ReturnType<typeof Application.useApplicationOwner>+ function Probe() {+ const current = Application.useApplicationOwner(), command = useApplicationSignOut()+ useLayoutEffect(() => { owner = current; logout = () => command.mutateAsync() }, [current, command])+ return <p>Account content</p>+ }+ function Root({ id }: { id: string }) { return <Application.ApplicationQueryProvider userId={id}><Probe /></Application.ApplicationQueryProvider> }+ await act(async () => { await import("@/instrumentation-client"); mounted = render(<Root id="account-a" />) })+ await waitFor(() => expect(auth.currentSessionViewer()).toBe("account-a"))+ await waitFor(() => expect(isTelemetryEligible()).toBe(true))+ await waitFor(() => expect(sent.some(body => body.meta.user?.id === "account-a")).toBe(true), { timeout: 5000 })+ const aSession = VolatileSessionsManager.fetchUserSession()!.sessionId+ await act(async () => { await expect(logout()).rejects.toThrow("Auth failed") })+ expect(owner.lifecycle.get().active).toBe(true)+ expect(VolatileSessionsManager.fetchUserSession()!.sessionId).toBe(aSession)+ mode = "hold"+ let oldResult!: Promise<unknown>+ act(() => { oldResult = logout().catch(error => error) })+ await waitFor(() => expect(release).toBeTypeOf("function"))+ await act(async () => { const result = await auth.authClient.signIn.email({ email: "[email protected]", password: "fixture-password" }); expect(result.error).toBeNull() })+ await waitFor(() => expect(auth.currentSessionViewer()).toBe("account-b"))+ await act(async () => mounted!.rerender(<Root id="account-b" />))+ await waitFor(() => expect(owner.userId).toBe("account-b"))+ await waitFor(() => expect(isTelemetryEligible()).toBe(true))+ await waitFor(() => expect(VolatileSessionsManager.fetchUserSession()!.sessionId).not.toBe(aSession))+ const bSession = VolatileSessionsManager.fetchUserSession()!.sessionId+ await act(async () => { release(Response.json({ success: true })); expect(await oldResult).toMatchObject({ name: "AbortError" }) })+ expect(owner.lifecycle.get().active).toBe(true)+ expect(VolatileSessionsManager.fetchUserSession()!.sessionId).toBe(bSession)+ emitTelemetry("business.result", { outcome: "success" })+ await waitFor(() => expect(sent.some(body => body.meta.session.id === bSession && body.meta.user?.id === "account-b")).toBe(true), { timeout: 5000 })+ mode = "success"+ await act(async () => { await logout() })+ await waitFor(() => expect(auth.currentSessionViewer()).toBeNull())+ await waitFor(() => expect(VolatileSessionsManager.fetchUserSession()!.sessionId).not.toBe(bSession))+ const anonymous = VolatileSessionsManager.fetchUserSession()!.sessionId+ await act(async () => window.history.replaceState(null, "", "/sign-in"))+ emitTelemetry("business.result", { outcome: "success" })+ await waitFor(() => expect(sent.some(body => body.meta.session.id === anonymous)).toBe(true), { timeout: 5000 })+ for (const body of sent.filter(body => body.meta.session.id === anonymous)) expect(body.meta.user).toBeUndefined()+ await act(async () => { await auth.authClient.signIn.email({ email: "[email protected]", password: "fixture-password" }) })+ await waitFor(() => expect(auth.currentSessionViewer()).toBe("account-b"))+ await act(async () => mounted!.rerender(<Root key="reentry" id="account-b" />))+ await waitFor(() => expect(isTelemetryEligible()).toBe(true))+ await waitFor(() => expect(VolatileSessionsManager.fetchUserSession()!.sessionId).not.toBe(anonymous))+ const confirmedAccount = VolatileSessionsManager.fetchUserSession()!.sessionId+ await act(async () => { const result = await auth.authClient.signOut(); expect(result.error).toBeNull() })+ await waitFor(() => expect(auth.currentSessionViewer()).toBeNull())+ await waitFor(() => expect(VolatileSessionsManager.fetchUserSession()!.sessionId).not.toBe(confirmedAccount))+ const confirmedAnonymous = VolatileSessionsManager.fetchUserSession()!.sessionId+ emitTelemetry("business.result", { outcome: "success" })+ await waitFor(() => expect(sent.some(body => body.meta.session.id === confirmedAnonymous)).toBe(true), { timeout: 5000 })+ for (const body of sent.filter(body => body.meta.session.id === confirmedAnonymous)) expect(body.meta.user).toBeUndefined()+ expect(JSON.stringify(sent)).not.toContain("[email protected]")+})diff --git a/src/web/src/lib/observability/browser.dom.test.ts b/src/web/src/lib/observability/browser.dom.test.tsnew file mode 100644index 000000000..162bf4b44--- /dev/null+++ b/src/web/src/lib/observability/browser.dom.test.ts@@ -0,0 +1,71 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest"+import { act } from "@/test/react-dom-harness"+import type { Faro } from "@grafana/faro-web-sdk"+import { installBrowserObservers } from "./browser"+import { configureTelemetry, installTelemetrySink, retireTelemetry } from "./telemetry"++const events: Array<{ name: string; attributes: Record<string, string> }> = []+let dispose: (() => void) | undefined+beforeEach(() => {+ events.length = 0+ act(() => configureTelemetry({ session_id: "browser-session" }, true))+ installTelemetrySink(event => events.push(event))+ vi.spyOn(performance, "getEntriesByType").mockReturnValue([])+})+afterEach(() => { dispose?.(); dispose = undefined; retireTelemetry(); vi.unstubAllGlobals(); vi.restoreAllMocks() })+it("redacts browser errors and rejections, excludes private frames and stops retired listeners", () => {+ const pushError = vi.fn(), faro = { api: { pushError } } as unknown as Faro+ dispose = installBrowserObservers(faro, "https://collector.example/collect/public")+ const prevent = (event: Event) => event.preventDefault()+ window.addEventListener("error", prevent)+ try {+ window.dispatchEvent(new ErrorEvent("error", { error: new TypeError("private-body"), message: "private-body", filename: window.location.origin + "/_next/static/chunks/a.js?token=private", lineno: 4, colno: 8, cancelable: true }))+ window.dispatchEvent(new ErrorEvent("error", { filename: "http://[", cancelable: true }))+ const rejection = new Event("unhandledrejection")+ Object.defineProperty(rejection, "reason", { value: new RangeError("private-rejection") })+ window.dispatchEvent(rejection)+ expect(pushError).toHaveBeenCalledTimes(3)+ expect(pushError.mock.calls[0]![1]).toMatchObject({ type: "TypeError", stackFrames: [{ filename: window.location.origin + "/_next/static/chunks/a.js", function: "[redacted]", lineno: 4, colno: 8 }] })+ expect(pushError.mock.calls[1]![1]).toMatchObject({ type: "Error", stackFrames: [] })+ expect(pushError.mock.calls[2]![1]).toMatchObject({ type: "RangeError", stackFrames: [] })+ expect(pushError.mock.calls.every(([error]) => error.message === "[redacted]")).toBe(true)+ retireTelemetry(); configureTelemetry({ session_id: "new-session" }, true)+ window.dispatchEvent(rejection)+ window.dispatchEvent(new ErrorEvent("error", { cancelable: true }))+ expect(pushError).toHaveBeenCalledTimes(3)+ } finally { window.removeEventListener("error", prevent) }+})+it("reports eligible resources with explicit kinds while excluding collector, old entries and retired callbacks", () => {+ const callbacks = new Map<string, (list: PerformanceObserverEntryList) => void>(), disconnect = vi.fn()+ class Observer {+ static supportedEntryTypes = ["resource", "longtask"]+ constructor(private callback: (list: PerformanceObserverEntryList) => void) {}+ observe({ type }: { type: string }) { callbacks.set(type, this.callback) }+ disconnect = disconnect+ }+ vi.stubGlobal("PerformanceObserver", Observer)+ dispose = installBrowserObservers({ api: { pushError: vi.fn() } } as unknown as Faro, "https://collector.example/collect/public", 10)+ const resource = (name: string, startTime = 20) => ({ name, startTime, duration: 8, transferSize: 12, encodedBodySize: 10, decodedBodySize: 14 }) as PerformanceEntry+ const send = (type: string, entries: PerformanceEntry[]) => callbacks.get(type)!({ getEntries: () => entries } as PerformanceObserverEntryList)+ send("resource", [resource("https://collector.example/collect/public"), resource("/collect/private"), resource("/api/agents", 0), resource("http://["), resource("/api/agents?token=private"), resource("/c/me/machines?_rsc=private"), resource("/_next/static/chunks/a.js?token=private"), resource("https://private.example/private")])+ expect(events.filter(event => event.name === "resource.finish").map(event => event.attributes.request_kind)).toEqual(["api", "rsc", "resource", "external"])+ expect(JSON.stringify(events)).not.toContain("private")+ send("longtask", [resource("longtask", 0), resource("longtask", 20)])+ expect(events.filter(event => event.name === "main_thread.longtask")).toHaveLength(1)+ const count = events.length+ retireTelemetry(); configureTelemetry({ session_id: "new-session" }, true)+ send("resource", [resource("/api/agents")])+ expect(events).toHaveLength(count)+ dispose(); dispose = undefined+ expect(disconnect).toHaveBeenCalledTimes(2)+})+it("reports unsupported and throwing observer capabilities without breaking content", () => {+ class Observer {+ static supportedEntryTypes = ["resource", "longtask"]+ constructor() { throw new Error("unavailable") }+ }+ vi.stubGlobal("PerformanceObserver", Observer)+ dispose = installBrowserObservers({ api: { pushError: vi.fn() } } as unknown as Faro, "https://collector.example/collect/public")+ expect(events).toHaveLength(2)+ expect(events.every(event => event.name === "telemetry.coverage" && event.attributes.capability === "unavailable")).toBe(true)+})diff --git a/src/web/src/lib/observability/browser.ts b/src/web/src/lib/observability/browser.tsnew file mode 100644index 000000000..f8ce92aae--- /dev/null+++ b/src/web/src/lib/observability/browser.ts@@ -0,0 +1,50 @@+import type { Faro } from "@grafana/faro-web-sdk"+import { routeTemplate } from "./coverage"+import { emitTelemetry, isTelemetryEligible, telemetryGeneration } from "./telemetry"++export function installBrowserObservers(faro: Faro, collector: string, since = 0) {+ const generation = telemetryGeneration()+ const active = () => isTelemetryEligible() && generation === telemetryGeneration()+ const error = (event: ErrorEvent) => {+ if (!active()) return+ const frames = []+ try {+ const url = new URL(event.filename, window.location.origin)+ if (url.origin === window.location.origin && /^\/(?:blog-static\/)?_next\/static\/[a-zA-Z0-9_./-]+\.js$/.test(url.pathname)) frames.push({ filename: url.origin + url.pathname, function: "[redacted]", lineno: event.lineno, colno: event.colno })+ } catch {}+ faro.api.pushError(new Error("[redacted]"), { type: event.error instanceof Error ? event.error.name : "Error", stackFrames: frames, skipDedupe: true })+ }+ const rejection = (event: PromiseRejectionEvent) => {+ if (!active()) return+ faro.api.pushError(new Error("[redacted]"), { type: event.reason instanceof Error ? event.reason.name : "Error", stackFrames: [], skipDedupe: true })+ }+ window.addEventListener("error", error)+ window.addEventListener("unhandledrejection", rejection)+ const observers: PerformanceObserver[] = []+ const observe = (type: string, callback: (entry: PerformanceEntry) => void) => {+ if (typeof PerformanceObserver === "undefined" || !PerformanceObserver.supportedEntryTypes?.includes(type)) {+ emitTelemetry("telemetry.coverage", { capability: "unavailable", phase: "transport", request_kind: type === "resource" ? "resource" : "unknown" })+ return+ }+ try {+ const observer = new PerformanceObserver(list => { if (active()) for (const entry of list.getEntries()) callback(entry) })+ observer.observe({ type, buffered: true })+ observers.push(observer)+ } catch { emitTelemetry("telemetry.coverage", { capability: "unavailable", phase: "transport" }) }+ }+ observe("resource", entry => {+ try {+ const url = new URL(entry.name, window.location.origin)+ if (url.href === collector || url.pathname.startsWith("/collect/")) return+ const resource = entry as PerformanceResourceTiming+ if (resource.startTime < since) return+ const template = routeTemplate(url.href, window.location.origin)+ const kind = url.origin !== window.location.origin ? "external" : url.searchParams.has("_rsc") ? "rsc" : url.pathname.startsWith("/api/") ? "api" : "resource"+ emitTelemetry("resource.finish", { route_template: template, request_kind: kind, start_ms: resource.startTime, duration_ms: resource.duration, transfer_bytes: resource.transferSize, encoded_bytes: resource.encodedBodySize, decoded_bytes: resource.decodedBodySize, cache_stage: "http", source: "unknown", capability: "limited", phase: "background", outcome: "observed" })+ } catch {}+ })+ observe("longtask", entry => { if (entry.startTime >= since) emitTelemetry("main_thread.longtask", { start_ms: entry.startTime, duration_ms: entry.duration, phase: "background", capability: "limited" }) })+ const navigation = performance.getEntriesByType("navigation")[0] as PerformanceNavigationTiming | undefined+ if (navigation && navigation.startTime >= since) emitTelemetry("resource.finish", { route_template: routeTemplate(window.location.href, window.location.origin), request_kind: "document", start_ms: navigation.startTime, duration_ms: navigation.duration, phase: "background", capability: "limited", source: "unknown", outcome: "observed" })+ return () => { window.removeEventListener("error", error); window.removeEventListener("unhandledrejection", rejection); for (const observer of observers) observer.disconnect() }+}diff --git a/src/web/src/lib/observability/client-account-reload.dom.test.tsx b/src/web/src/lib/observability/client-account-reload.dom.test.tsxnew file mode 100644index 000000000..d6e87dffe--- /dev/null+++ b/src/web/src/lib/observability/client-account-reload.dom.test.tsx@@ -0,0 +1,64 @@+import "fake-indexeddb/auto"+import { afterEach, expect, it, vi } from "vitest"+import { initializeFaro, InternalLoggerLevel, SessionInstrumentation, VolatileSessionsManager } from "@grafana/faro-web-sdk"+import { act, render } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"++vi.mock("@/lib/auth-client", () => ({ useSession: () => ({ data: { user: { id: "account-a" } }, isPending: false, error: null }), currentSessionViewer: () => "account-a" }))+vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))+vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))+vi.mock("@/lib/perf/react-scan-install", () => ({ installReactScan: vi.fn(async () => {}) }))+const tracingImport = vi.hoisted(() => {+ let release!: () => void+ const ready = new Promise<void>(resolve => { release = resolve })+ return { ready, release }+})+vi.mock("@grafana/faro-web-tracing", async importOriginal => {+ await tracingImport.ready+ return importOriginal<typeof import("@grafana/faro-web-tracing")>()+})+let mounted: ReturnType<typeof render> | undefined+afterEach(async () => {+ await act(async () => { mounted?.unmount(); mounted = undefined; document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied"); await vi.advanceTimersByTimeAsync(0) })+ window.history.replaceState(null, "", "/")+ vi.useRealTimers(); vi.unstubAllEnvs(); vi.unstubAllGlobals()+})+it("the actual early instrumentation entry waits for the first actual account Provider and resumes that same owner", async () => {+ vi.useFakeTimers()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ vi.stubEnv("NEXT_PUBLIC_FARO_ENVIRONMENT", "qa")+ vi.stubEnv("NEXT_PUBLIC_FARO_RELEASE", "a".repeat(40))+ Object.defineProperty(performance, "getEntriesByType", { configurable: true, value: () => [] })+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ window.history.replaceState(null, "", "/c/me")+ VolatileSessionsManager.removeUserSession()+ const previousDocument = initializeFaro({+ isolate: true, preventGlobalExposure: true, internalLoggerLevel: InternalLoggerLevel.OFF,+ app: { name: "alook-web" }, transports: [], instrumentations: [new SessionInstrumentation()],+ sessionTracking: { enabled: true, persistent: false, samplingRate: 1, session: { attributes: { alook_account: "account-a" } } },+ })!+ const prior = VolatileSessionsManager.fetchUserSession()!+ previousDocument.instrumentations.remove(...previousDocument.instrumentations.instrumentations)+ const sent: Array<{ meta: { session: { id: string }; user?: { id: string } }; events?: Array<{ name: string }> }> = []+ const fetch = vi.fn(async (_url: unknown, options?: RequestInit) => { if (options?.body) sent.push(JSON.parse(String(options.body))); return new Response(null, { status: 204 }) })+ vi.stubGlobal("fetch", fetch)+ const { isTelemetryEligible } = await import("./telemetry")+ await act(async () => { await import("@/instrumentation-client") })+ await vi.advanceTimersByTimeAsync(0)+ expect(isTelemetryEligible()).toBe(false)+ expect(fetch).not.toHaveBeenCalled()+ expect(VolatileSessionsManager.fetchUserSession()!.sessionId).toBe(prior.sessionId)+ const { QueryProvider } = await import("@/app/c/QueryProvider")+ await act(async () => { mounted = render(<QueryProvider userId="account-a"><p>Account content</p></QueryProvider>) })+ await vi.waitFor(() => expect(isTelemetryEligible()).toBe(true), { timeout: 5000 })+ await act(async () => vi.advanceTimersByTimeAsync(1500))+ expect(sent).toHaveLength(0)+ tracingImport.release()+ await vi.waitFor(() => expect(sent.some(body => body.events?.some(event => event.name === "session_resume"))).toBe(true), { timeout: 5000 })+ expect(VolatileSessionsManager.fetchUserSession()!.sessionId).toBe(prior.sessionId)+ expect(VolatileSessionsManager.fetchUserSession()!.started).toBe(prior.started)+ expect(sent.some(body => body.events?.some(event => event.name === "session_resume"))).toBe(true)+ expect(sent.some(body => body.meta.user?.id === "account-a")).toBe(true)+ for (const body of sent) expect(body.meta.session.id).toBe(prior.sessionId)+ expect(JSON.stringify(sent)).not.toContain("alook_account")+})diff --git a/src/web/src/lib/observability/client-document-restore-import.dom.test.ts b/src/web/src/lib/observability/client-document-restore-import.dom.test.tsnew file mode 100644index 000000000..e9c6c24f8--- /dev/null+++ b/src/web/src/lib/observability/client-document-restore-import.dom.test.ts@@ -0,0 +1,57 @@+import { afterEach, expect, it, vi } from "vitest"+import { act } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"++const pending = vi.hoisted(() => {+ let release!: () => void+ const ready = new Promise<void>(resolve => { release = resolve })+ return { ready, release }+})+vi.mock("@grafana/faro-web-sdk", async importOriginal => {+ await pending.ready+ return importOriginal<typeof import("@grafana/faro-web-sdk")>()+})+afterEach(async () => {+ await act(async () => { document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied"); await vi.advanceTimersByTimeAsync(0) })+ window.history.replaceState(null, "", "/")+ vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.unstubAllGlobals()+})++it("does not install or backfill a document generation whose SDK import resolves after document retirement", async () => {+ vi.useFakeTimers(); sessionStorage.clear()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ vi.spyOn(performance, "getEntriesByType").mockReturnValue([])+ window.history.replaceState(null, "", "/")+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ const sent: Array<{ events?: Array<{ name: string; attributes: Record<string, string> }> }> = []+ vi.stubGlobal("fetch", vi.fn(async (url: unknown, options?: RequestInit) => {+ if (String(url) === "https://collector.example/collect/public" && options?.body) sent.push(JSON.parse(String(options.body)))+ return new Response(null, { status: 204 })+ }))+ const { bootstrapObservability } = await import("./client")+ const { emitTelemetry, isTelemetryEligible, telemetryGeneration } = await import("./telemetry")+ const { navigationForHref, startAction, finishAction } = await import("./context")+ await act(async () => { bootstrapObservability("web") })+ const initial = navigationForHref("/")!+ expect(initial).toBeDefined()+ const generation = telemetryGeneration()+ const retired = startAction("message.edit")!+ emitTelemetry("business.result", { action_id: retired.id, outcome: "success" })+ await act(async () => { window.dispatchEvent(new PageTransitionEvent("pagehide", { persisted: true })) })+ document.cookie = "alook_analytics_consent=v1.denied; path=/"+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ await act(async () => { window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true })); pending.release() })+ await vi.waitFor(() => expect(isTelemetryEligible()).toBe(true))+ await act(async () => { await vi.advanceTimersByTimeAsync(3000) })+ finishAction(retired, "success")+ expect(initial.done).toBe(true)+ expect(telemetryGeneration()).toBeGreaterThan(generation)+ expect(JSON.stringify(sent)).not.toContain(initial.id)+ expect(JSON.stringify(sent)).not.toContain(retired.id)+ expect(sent.flatMap(body => body.events ?? []).some(event => event.attributes.navigation_kind === "document")).toBe(false)+ const current = startAction("message.pin")!+ expect(current.span).toBeDefined()+ finishAction(current, "success")+ await act(async () => { await vi.advanceTimersByTimeAsync(3000) })+ expect(sent.flatMap(body => body.events ?? []).some(event => event.name === "action.finish" && event.attributes.action_id === current.id)).toBe(true)+})diff --git a/src/web/src/lib/observability/client-document-restore.dom.test.tsx b/src/web/src/lib/observability/client-document-restore.dom.test.tsxnew file mode 100644index 000000000..b25cd9e01--- /dev/null+++ b/src/web/src/lib/observability/client-document-restore.dom.test.tsx@@ -0,0 +1,151 @@+import { useLayoutEffect } from "react"+import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"+import type { Faro } from "@grafana/faro-web-sdk"+import { afterEach, expect, it, vi } from "vitest"+import { act, render } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"+import { useObservedQueryRegion } from "./query-regions"++const native = vi.hoisted(() => ({ faro: undefined as Faro | undefined }))+const router = vi.hoisted(() => ({ pathname: "/" }))+vi.mock("@grafana/faro-web-sdk", async importOriginal => {+ const real = await importOriginal<typeof import("@grafana/faro-web-sdk")>()+ return { ...real, initializeFaro: (...args: Parameters<typeof real.initializeFaro>) => { native.faro = real.initializeFaro(...args); return native.faro } }+})+vi.mock("next/navigation", () => ({ usePathname: () => router.pathname, useSearchParams: () => new URLSearchParams() }))+let view: ReturnType<typeof render> | undefined+let queryClient: QueryClient | undefined+afterEach(async () => {+ await act(async () => {+ view?.unmount(); queryClient?.clear()+ document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied")+ await vi.advanceTimersByTimeAsync(0)+ })+ window.history.replaceState(null, "", "/")+ vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.unstubAllGlobals()+})++it("retires the old document before native resume, then exports one original Back in a fresh consent session", async () => {+ vi.useFakeTimers(); sessionStorage.clear()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ let now = 200+ vi.spyOn(performance, "now").mockImplementation(() => now)+ vi.spyOn(performance, "getEntriesByType").mockReturnValue([])+ type Event = { name: string; attributes: Record<string, string> }+ type Body = { meta: { session: { id: string } }; events?: Event[] }+ const sent: Body[] = []+ let collectorStatus = 204+ vi.stubGlobal("fetch", vi.fn(async (url: unknown, options?: RequestInit) => {+ if (String(url) === "https://collector.example/collect/public" && options?.body) {+ sent.push(JSON.parse(String(options.body)))+ }+ return new Response(null, { status: collectorStatus })+ }))+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ const text = "/c/channels/server-a/text-a", forum = "/c/channels/server-a/forum-a"+ window.history.replaceState(null, "", text); window.history.pushState(null, "", forum)+ router.pathname = forum+ const { bootstrapObservability, setTelemetryUser, onObservedRouterTransition } = await import("./client")+ const { commitNavigation, navigationForHref, startAction, finishAction } = await import("./context")+ const { emitTelemetry, isTelemetryEligible, telemetryGeneration } = await import("./telemetry")+ const { VolatileSessionsManager } = await import("@grafana/faro-web-sdk")+ queryClient = new QueryClient()+ queryClient.setQueryData([forum], [{ id: "post-a" }]); queryClient.setQueryData([text], [])+ function Content() {+ const query = useQuery({ queryKey: [router.pathname], queryFn: async () => [], staleTime: Infinity })+ useObservedQueryRegion(router.pathname === forum ? "forum" : "messages", query, query.data?.length)+ return <p>{router.pathname === forum ? "forum" : "empty text"}</p>+ }+ function Root() {+ useLayoutEffect(() => setTelemetryUser("account-a"), [])+ useLayoutEffect(() => commitNavigation(router.pathname), [router.pathname])+ return <QueryClientProvider client={queryClient!}><Content /></QueryClientProvider>+ }+ await act(async () => { bootstrapObservability("web"); view = render(<Root />) })+ await vi.waitFor(() => expect(native.faro?.api.getSession()?.id).toBeTruthy())+ await act(async () => { await vi.advanceTimersByTimeAsync(3000) })+ const originalSession = native.faro!.api.getSession()!.id+ const initialReady = sent.flatMap(body => body.events ?? []).filter(event => event.name === "navigation.ready")+ expect(initialReady).toHaveLength(1)+ expect(initialReady[0]?.attributes.navigation_kind).toBe("document")+ await act(async () => { window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: false })); await vi.advanceTimersByTimeAsync(3000) })+ expect(native.faro!.api.getSession()!.id).toBe(originalSession)+ expect(sent.flatMap(body => body.events ?? []).filter(event => event.name === "navigation.ready")).toHaveLength(1)++ const generation = telemetryGeneration()+ const retired = startAction("message.edit")!+ collectorStatus = 429+ const beforeRetry = sent.length+ emitTelemetry("business.result", { action_id: retired.id, outcome: "success" })+ await act(async () => { await vi.advanceTimersByTimeAsync(1000) })+ expect(sent.length).toBeGreaterThan(beforeRetry)+ const beforeHide = sent.length+ await act(async () => { window.dispatchEvent(new PageTransitionEvent("pagehide", { persisted: true })) })+ const inactiveAfterHide = !isTelemetryEligible()+ collectorStatus = 204+ document.cookie = "alook_analytics_consent=v1.denied; path=/"+ VolatileSessionsManager.removeUserSession()+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ await act(async () => {+ window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true }))+ await vi.advanceTimersByTimeAsync(3000)+ })+ const restoredSession = native.faro!.api.getSession()!.id+ expect(restoredSession).not.toBe(originalSession)+ expect(inactiveAfterHide).toBe(true)+ expect(telemetryGeneration()).toBeGreaterThan(generation)+ expect(retired.done).toBe(true)+ expect(isTelemetryEligible()).toBe(true)+ finishAction(retired, "success")++ now = 1600+ await act(async () => { window.history.back(); await vi.advanceTimersByTimeAsync(5) })+ const original = navigationForHref(text)!+ expect(original).toBeDefined()+ expect(original.done).toBe(false)+ expect(view!.container.textContent).toBe("forum")+ const parent = original.span!.spanContext()+ now += 5+ await act(async () => { onObservedRouterTransition(text) })+ expect(navigationForHref(text)).toBe(original)+ now += 50+ await act(async () => { router.pathname = text; view!.rerender(<Root />) })+ await act(async () => { await vi.advanceTimersByTimeAsync(3000) })+ expect(view!.container.textContent).toBe("empty text")+ const restored = sent.slice(beforeHide)+ expect(restored.every(body => body.meta.session.id === restoredSession)).toBe(true)+ expect(JSON.stringify(restored)).not.toContain(retired.id)+ const events = restored.flatMap(body => body.events ?? [])+ expect(events.some(event => event.attributes.navigation_kind === "document")).toBe(false)+ const ready = events.filter(event => event.name === "navigation.ready")+ expect(ready).toHaveLength(1)+ expect(ready[0]?.attributes).toMatchObject({ action_id: original.id, navigation_id: original.navigationId, session_id: restoredSession, trace_id: parent.traceId, span_id: parent.spanId, start_ms: "1600", duration_ms: "55", region: "messages", phase: "primary" })+ const spans: Record<string, unknown>[] = []+ const visit = (value: unknown) => {+ if (!value || typeof value !== "object") return+ const record = value as Record<string, unknown>+ if (typeof record.spanId === "string") spans.push(record)+ for (const child of Object.values(record)) visit(child)+ }+ visit(restored)+ expect(spans.filter(span => span.spanId === parent.spanId)).toHaveLength(1)++ await act(async () => { window.dispatchEvent(new PageTransitionEvent("pagehide", { persisted: true })) })+ const suspendedCount = sent.length+ await act(async () => { announceAnalyticsConsent("granted"); await vi.advanceTimersByTimeAsync(3000) })+ expect(isTelemetryEligible()).toBe(false)+ expect(sent).toHaveLength(suspendedCount)+ document.cookie = "alook_analytics_consent=v1.denied; path=/"+ VolatileSessionsManager.removeUserSession()+ const deniedCount = sent.length+ await act(async () => {+ window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true }))+ onObservedRouterTransition(forum); view!.rerender(<Root />)+ await vi.advanceTimersByTimeAsync(3000)+ })+ expect(isTelemetryEligible()).toBe(false)+ expect(sent).toHaveLength(deniedCount)+ await act(async () => { document.cookie = "alook_analytics_consent=v1.granted; path=/"; announceAnalyticsConsent("granted"); await vi.advanceTimersByTimeAsync(3000) })+ expect(native.faro!.api.getSession()!.id).not.toBe(restoredSession)+ expect(sent.slice(deniedCount).flatMap(body => body.events ?? []).some(event => event.attributes.navigation_kind === "document")).toBe(false)+})diff --git a/src/web/src/lib/observability/client-invalid-build.dom.test.ts b/src/web/src/lib/observability/client-invalid-build.dom.test.tsnew file mode 100644index 000000000..0812aea03--- /dev/null+++ b/src/web/src/lib/observability/client-invalid-build.dom.test.ts@@ -0,0 +1,18 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest"+import { act } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"+beforeEach(() => { vi.resetModules() })+afterEach(() => { document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied"); vi.unstubAllEnvs(); vi.unstubAllGlobals() })+it.each([undefined, "http://["])("rejects absent or malformed Collector %s before SDK startup or outbound telemetry", async url => {+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", url)+ vi.stubEnv("NEXT_PUBLIC_FARO_ENVIRONMENT", "qa")+ vi.stubEnv("NEXT_PUBLIC_FARO_RELEASE", "a".repeat(40))+ const fetch = vi.fn(); vi.stubGlobal("fetch", fetch)+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ const { bootstrapObservability } = await import("./client")+ const { emitTelemetry, isTelemetryEligible } = await import("./telemetry")+ await act(async () => { bootstrapObservability("web"); await Promise.resolve() })+ emitTelemetry("business.result", { outcome: "success" })+ expect(isTelemetryEligible()).toBe(false)+ expect(fetch).not.toHaveBeenCalled()+})diff --git a/src/web/src/lib/observability/client-invalid-labels.dom.test.ts b/src/web/src/lib/observability/client-invalid-labels.dom.test.tsnew file mode 100644index 000000000..4969a8074--- /dev/null+++ b/src/web/src/lib/observability/client-invalid-labels.dom.test.ts@@ -0,0 +1,42 @@+import { afterEach, expect, it, vi } from "vitest"+import { act } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"++afterEach(async () => {+ document.cookie = "alook_analytics_consent=v1.denied; path=/"+ announceAnalyticsConsent("denied")+ await vi.advanceTimersByTimeAsync(0)+ vi.useRealTimers(); vi.unstubAllEnvs(); vi.unstubAllGlobals()+})++it("exports actual native Faro events while omitting invalid optional build labels", async () => {+ vi.useFakeTimers(); sessionStorage.clear()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ vi.stubEnv("NEXT_PUBLIC_FARO_ENVIRONMENT", "untrusted-label")+ vi.stubEnv("NEXT_PUBLIC_FARO_RELEASE", "untrusted-label")+ Object.defineProperty(performance, "getEntriesByType", { configurable: true, value: () => [] })+ const sent: Array<{ meta: { app: Record<string, unknown>; sdk: { name: string; version: string } }; events?: Array<{ name: string; attributes?: Record<string, string> }> }> = []+ vi.stubGlobal("fetch", vi.fn(async (_url: unknown, options?: RequestInit) => {+ if (options?.body) sent.push(JSON.parse(String(options.body)))+ return new Response(null, { status: 204 })+ }))+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ const { bootstrapObservability } = await import("./client")+ const { emitTelemetry, isTelemetryEligible } = await import("./telemetry")+ await act(async () => { bootstrapObservability("blog"); await Promise.resolve() })+ await vi.waitFor(() => expect(isTelemetryEligible()).toBe(true))+ emitTelemetry("business.result", { outcome: "success" })+ await vi.advanceTimersByTimeAsync(1500)+ await vi.waitFor(() => expect(sent.some(body => body.events?.some(event => event.name === "session_start"))).toBe(true), { timeout: 5000 })+ expect(sent.some(body => body.events?.some(event => event.name === "business.result"))).toBe(true)+ for (const body of sent) {+ expect(body.meta.sdk).toEqual({ name: "faro-web", version: "2.12.1" })+ expect(body.meta.app).not.toHaveProperty("environment")+ expect(body.meta.app).not.toHaveProperty("release")+ expect(body.meta.app).not.toHaveProperty("version")+ for (const event of body.events ?? []) {+ expect(event.attributes).not.toHaveProperty("environment")+ expect(event.attributes).not.toHaveProperty("release")+ }+ }+})diff --git a/src/web/src/lib/observability/client-optional-build.dom.test.ts b/src/web/src/lib/observability/client-optional-build.dom.test.tsnew file mode 100644index 000000000..94884d495--- /dev/null+++ b/src/web/src/lib/observability/client-optional-build.dom.test.ts@@ -0,0 +1,42 @@+import { afterEach, expect, it, vi } from "vitest"+import { act } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"++afterEach(async () => {+ document.cookie = "alook_analytics_consent=v1.denied; path=/"+ announceAnalyticsConsent("denied")+ await vi.advanceTimersByTimeAsync(0)+ vi.useRealTimers(); vi.unstubAllEnvs(); vi.unstubAllGlobals()+})++it("exports actual native Faro events with only the Collector configured", async () => {+ vi.useFakeTimers(); sessionStorage.clear()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ vi.stubEnv("NEXT_PUBLIC_FARO_ENVIRONMENT", undefined)+ vi.stubEnv("NEXT_PUBLIC_FARO_RELEASE", undefined)+ Object.defineProperty(performance, "getEntriesByType", { configurable: true, value: () => [] })+ const sent: Array<{ meta: { app: Record<string, unknown>; sdk: { name: string; version: string } }; events?: Array<{ name: string; attributes?: Record<string, string> }> }> = []+ vi.stubGlobal("fetch", vi.fn(async (_url: unknown, options?: RequestInit) => {+ if (options?.body) sent.push(JSON.parse(String(options.body)))+ return new Response(null, { status: 204 })+ }))+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ const { bootstrapObservability } = await import("./client")+ const { emitTelemetry, isTelemetryEligible } = await import("./telemetry")+ await act(async () => { bootstrapObservability("blog"); await Promise.resolve() })+ await vi.waitFor(() => expect(isTelemetryEligible()).toBe(true))+ emitTelemetry("business.result", { outcome: "success" })+ await vi.advanceTimersByTimeAsync(1500)+ await vi.waitFor(() => expect(sent.some(body => body.events?.some(event => event.name === "session_start"))).toBe(true), { timeout: 5000 })+ expect(sent.some(body => body.events?.some(event => event.name === "business.result"))).toBe(true)+ for (const body of sent) {+ expect(body.meta.sdk).toEqual({ name: "faro-web", version: "2.12.1" })+ expect(body.meta.app).not.toHaveProperty("environment")+ expect(body.meta.app).not.toHaveProperty("release")+ expect(body.meta.app).not.toHaveProperty("version")+ for (const event of body.events ?? []) {+ expect(event.attributes).not.toHaveProperty("environment")+ expect(event.attributes).not.toHaveProperty("release")+ }+ }+})diff --git a/src/web/src/lib/observability/client-reload.dom.test.ts b/src/web/src/lib/observability/client-reload.dom.test.tsnew file mode 100644index 000000000..517fa715b--- /dev/null+++ b/src/web/src/lib/observability/client-reload.dom.test.ts@@ -0,0 +1,62 @@+import { afterEach, expect, it, vi } from "vitest"+import { initializeFaro, InternalLoggerLevel, SessionInstrumentation, VolatileSessionsManager } from "@grafana/faro-web-sdk"+import { act } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"++afterEach(() => {+ document.cookie = "alook_analytics_consent=v1.denied; path=/"+ announceAnalyticsConsent("denied")+ vi.useRealTimers(); vi.unstubAllEnvs(); vi.unstubAllGlobals()+})+it("resumes the actual previous SDK document and preserves its initial session_resume through beforeSend", async () => {+ vi.useFakeTimers()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ vi.stubEnv("NEXT_PUBLIC_FARO_ENVIRONMENT", "qa")+ vi.stubEnv("NEXT_PUBLIC_FARO_RELEASE", "a".repeat(40))+ Object.defineProperty(performance, "getEntriesByType", { configurable: true, value: () => [] })+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ VolatileSessionsManager.removeUserSession()+ const priorDocument = initializeFaro({+ isolate: true, preventGlobalExposure: true, internalLoggerLevel: InternalLoggerLevel.OFF,+ app: { name: "alook-web" }, transports: [], instrumentations: [new SessionInstrumentation()],+ sessionTracking: { enabled: true, persistent: false, samplingRate: 1, session: { attributes: { alook_account: "anon" } } },+ })!+ const prior = VolatileSessionsManager.fetchUserSession()!+ expect(prior.sessionId).toBe(priorDocument.api.getSession()!.id)+ priorDocument.instrumentations.remove(...priorDocument.instrumentations.instrumentations)+ const sent: Array<{ meta: { sdk: { name: string; version: string }; session: { id: string } }; events?: Array<{ name: string; timestamp: string; attributes?: Record<string, string> }> }> = []+ vi.stubGlobal("fetch", vi.fn(async (_url: unknown, options?: RequestInit) => { if (options?.body) sent.push(JSON.parse(String(options.body))); return new Response(null, { status: 204 }) }))+ const { bootstrapObservability } = await import("./client")+ const { emitTelemetry, isTelemetryEligible, telemetryGeneration } = await import("./telemetry")+ const { startAction, finishAction, actionAttributes } = await import("./context")+ let early!: ReturnType<typeof startAction>+ let initialGeneration = -1+ const earlyTimestamp = Date.now()+ await act(async () => {+ bootstrapObservability("web")+ initialGeneration = telemetryGeneration()+ early = startAction("message.edit")+ emitTelemetry("business.result", { ...actionAttributes(early), outcome: "success" })+ vi.setSystemTime(earlyTimestamp + 400)+ })+ expect(early).toBeDefined()+ await vi.waitFor(() => expect(sent.some(body => body.events?.some(event => event.name === "session_resume"))).toBe(true), { timeout: 5000 })+ expect(isTelemetryEligible()).toBe(true)+ expect(telemetryGeneration()).toBe(initialGeneration)+ expect(early!.done).toBe(false)+ finishAction(early, "success")+ emitTelemetry("business.result", { outcome: "success" })+ await vi.advanceTimersByTimeAsync(1500)+ const resumed = VolatileSessionsManager.fetchUserSession()!+ expect(resumed.sessionId).toBe(prior.sessionId)+ expect(resumed.started).toBe(prior.started)+ expect(sent.some(body => body.events?.some(event => event.name === "session_resume"))).toBe(true)+ expect(sent.some(body => body.events?.some(event => event.name === "business.result"))).toBe(true)+ const earlyExport = sent.flatMap(body => (body.events ?? []).filter(event => event.attributes?.action_id === early!.id).map(event => ({ event, meta: body.meta })))+ expect(earlyExport.map(record => record.event.name)).toEqual(["action.start", "business.result", "action.finish"])+ for (const { event, meta } of earlyExport) expect(event.attributes).toMatchObject({ action_id: early!.id, action_name: "message.edit", session_id: meta.session.id, start_ms: String(early!.start) })+ expect(Date.parse(earlyExport[0]!.event.timestamp)).toBe(earlyTimestamp)+ expect(Date.parse(earlyExport[1]!.event.timestamp)).toBe(earlyTimestamp)+ for (const body of sent) expect(body).toMatchObject({ meta: { sdk: { name: "faro-web", version: "2.12.1" }, session: { id: prior.sessionId } } })+ expect(JSON.stringify(sent)).not.toContain("alook_account")+})diff --git a/src/web/src/lib/observability/client.dom.test.ts b/src/web/src/lib/observability/client.dom.test.tsnew file mode 100644index 000000000..633d41d0d--- /dev/null+++ b/src/web/src/lib/observability/client.dom.test.ts@@ -0,0 +1,163 @@+import { afterEach, expect, it, vi } from "vitest"+import { act } from "@/test/react-dom-harness"+import type { Faro } from "@grafana/faro-web-sdk"+import { announceAnalyticsConsent } from "../analytics-consent"++const native = vi.hoisted(() => ({ faro: undefined as Faro | undefined, release: undefined as (() => void) | undefined, vitals: undefined as unknown }))+vi.mock("@grafana/faro-web-sdk", async importOriginal => {+ const real = await importOriginal<typeof import("@grafana/faro-web-sdk")>()+ await new Promise<void>(resolve => { native.release = resolve })+ return { ...real, getWebInstrumentations: (...args: Parameters<typeof real.getWebInstrumentations>) => { const all = real.getWebInstrumentations(...args); native.vitals = all.find(item => item.name.endsWith("instrumentation-web-vitals")); return all }, initializeFaro: (...args: Parameters<typeof real.initializeFaro>) => { native.faro = real.initializeFaro(...args); return native.faro } }+})+afterEach(() => { document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied"); vi.useRealTimers(); vi.unstubAllEnvs(); vi.unstubAllGlobals() })+it("real Faro sessions align after interrupted import, regrant, account changes, expiry and reload metadata", async () => {+ vi.useFakeTimers()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ vi.stubEnv("NEXT_PUBLIC_FARO_ENVIRONMENT", "qa")+ vi.stubEnv("NEXT_PUBLIC_FARO_RELEASE", "a".repeat(40))+ Object.defineProperty(performance, "getEntriesByType", { configurable: true, value: () => [] })+ sessionStorage.setItem("com.grafana.faro.session", JSON.stringify({ sessionId: "previous-document", lastActivity: Date.now(), started: Date.now(), isSampled: true, sessionMeta: { id: "previous-document", attributes: { isSampled: "true" } } }))+ const sent: unknown[] = []+ let collectorStatus = 204+ vi.stubGlobal("fetch", vi.fn(async (_url: unknown, options?: RequestInit) => {+ const url = String(_url instanceof Request ? _url.url : _url)+ if (url === "https://collector.example/collect/public" && options?.body) sent.push(JSON.parse(String(options.body)))+ if (url === "https://collector.example/collect/public") return new Response(null, { status: collectorStatus })+ return url.endsWith("/api/community/channels/private/messages") ? new Response("{}", { status: 201 }) : new Response(null, { status: 204 })+ }))+ const { bootstrapObservability, setTelemetryUser } = await import("./client")+ const { emitTelemetry, telemetryGeneration, isTelemetryEligible } = await import("./telemetry")+ const { beginNavigation, navigationForHref, finishAction, startAction } = await import("./context")+ const consent = (value: "granted" | "denied") => { document.cookie = "alook_analytics_consent=v1." + value + "; path=/"; announceAnalyticsConsent(value) }+ await act(async () => { consent("granted"); bootstrapObservability("web") })+ await vi.waitFor(() => expect(native.release).toBeTypeOf("function"))+ expect(native.release).toBeTypeOf("function")+ consent("denied"); setTelemetryUser("account-b"); consent("granted")+ native.release?.()+ for (let i = 0; i < 10; i++) await vi.advanceTimersByTimeAsync(0)+ expect(isTelemetryEligible()).toBe(true)+ const session = native.faro!.api.getSession()!.id+ expect(session).not.toBe("previous-document")+ emitTelemetry("business.result", { outcome: "success" })+ await vi.advanceTimersByTimeAsync(1500)+ expect(JSON.stringify(sent)).toContain(session)+ expect(JSON.stringify(sent)).toContain("business.result")+ expect(sent.length).toBeGreaterThan(0)+ expect(sent.some(body => (body as { events?: Array<{ name: string }> }).events?.some(event => event.name === "session_start"))).toBe(true)+ for (const body of sent) expect(body).toMatchObject({ meta: { sdk: { name: "faro-web", version: "2.12.1" } } })+ const controls = document.createElement("div")+ controls.innerHTML = '<a href="/c/me/machines">Machines</a><button>Command</button>'+ document.body.append(controls)+ const firstLink = controls.querySelector("a")!, button = controls.querySelector("button")!+ firstLink.addEventListener("click", event => event.preventDefault())+ const beforeGesture = sent.length+ firstLink.click()+ const router = await import("@/instrumentation-client")+ router.onRouterTransitionStart("/c/me/machines")+ const gesture = navigationForHref("/c/me/machines")!+ finishAction(gesture, "success")+ button.click()+ await vi.advanceTimersByTimeAsync(1500)+ expect(JSON.stringify(sent.slice(beforeGesture))).toContain("ui_interaction")+ expect(JSON.stringify(sent.slice(beforeGesture))).toContain(gesture.id)+ document.dispatchEvent(new Event("visibilitychange"))+ const vitals = native.vitals as { api: { pushMeasurement: Faro["api"]["pushMeasurement"] } }+ const beforeVitals = sent.length+ vitals.api.pushMeasurement({ type: "web-vitals", values: { lcp: 12, cls: 0, private: 88, inp: Infinity } })+ await vi.advanceTimersByTimeAsync(1500)+ expect(JSON.stringify(sent.slice(beforeVitals))).toContain('"lcp":12')+ expect(JSON.stringify(sent.slice(beforeVitals))).not.toContain('"private":88')+ collectorStatus = 429+ emitTelemetry("business.result", { outcome: "error" })+ await vi.advanceTimersByTimeAsync(12000)+ collectorStatus = 204+ const beforeRecovery = sent.length+ emitTelemetry("business.result", { outcome: "success" })+ await vi.advanceTimersByTimeAsync(3000)+ expect(JSON.stringify(sent.slice(beforeRecovery))).toContain("delivery_failure_count")+ expect(JSON.stringify(sent.slice(beforeRecovery))).toContain("rate_limit")+ controls.remove()+ const generation = telemetryGeneration()+ emitTelemetry("business.result", { action_name: "message.edit", outcome: "success" })+ const beforeAccount = sent.length+ setTelemetryUser("account-c")+ for (let i = 0; i < 10; i++) await vi.advanceTimersByTimeAsync(0)+ expect(native.faro!.api.getSession()!.id).not.toBe(session)+ expect(telemetryGeneration()).toBeGreaterThan(generation)+ emitTelemetry("business.result", { action_name: "message.pin", outcome: "success" })+ await vi.advanceTimersByTimeAsync(1500)+ expect(JSON.stringify(sent.slice(beforeAccount))).not.toContain("message.edit")+ expect(JSON.stringify(sent.slice(beforeAccount))).toContain("message.pin")+ const accountSession = native.faro!.api.getSession()!.id+ vi.setSystemTime(Date.now() + 5 * 60 * 60 * 1000)+ const beforeExpiry = sent.length+ const first = beginNavigation("/c/me/bots")!+ expect(first.done).toBe(false)+ expect(first.span?.isRecording()).toBe(true)+ expect(first.generation).toBe(telemetryGeneration())+ expect(navigationForHref("/c/me/bots")).toBe(first)+ finishAction(first, "success")+ expect(first.span?.isRecording()).toBe(false)+ await vi.advanceTimersByTimeAsync(1500)+ const extended = native.faro!.api.getSession()!.id+ expect(extended).not.toBe(accountSession)+ const expiryPayload = JSON.stringify(sent.slice(beforeExpiry))+ expect(expiryPayload).toContain(first.id)+ expect(expiryPayload).toContain("action.start")+ expect(expiryPayload).toContain("action.finish")+ expect(expiryPayload).toContain(extended)+ emitTelemetry("business.result", { outcome: "success" })+ await vi.advanceTimersByTimeAsync(1500)+ expect(JSON.stringify(sent)).toContain(extended)+ const spans: Record<string, unknown>[] = []+ const visit = (value: unknown) => {+ if (!value || typeof value !== "object") return+ const record = value as Record<string, unknown>+ if (typeof record.spanId === "string") spans.push(record)+ for (const child of Object.values(record)) visit(child)+ }+ visit(sent.slice(beforeExpiry))+ expect(spans.some(span => span.name === "navigation" && JSON.stringify(span).includes(first.id) && JSON.stringify(span).includes(extended))).toBe(true)+ const { apiFetchResponse } = await import("@/lib/api/client")+ const beforeRequests = sent.length+ const one = startAction("message.edit")!, two = startAction("message.pin")!+ const firstContext = one.span!.spanContext(), secondContext = two.span!.spanContext()+ await Promise.all([+ apiFetchResponse("/api/agents", { observation: { action: one, reason: "command" } }),+ apiFetchResponse("/api/workspaces", { observation: { action: two, reason: "command" } }),+ ])+ finishAction(one, "success"); finishAction(two, "success")+ await vi.advanceTimersByTimeAsync(3000)+ spans.length = 0+ visit(sent.slice(beforeRequests))+ const children = (parent: typeof firstContext) => spans.filter(span => span.traceId === parent.traceId && span.parentSpanId === parent.spanId)+ expect(children(firstContext)).toHaveLength(1)+ expect(children(secondContext)).toHaveLength(1)+ expect(children(firstContext)[0]?.name).toBe("GET /api/agents")+ expect(children(secondContext)[0]?.name).toBe("GET /api/workspaces")+ const beforeDm = sent.length+ const dm = startAction("dm.message.send")!+ const dmContext = dm.span!.spanContext()+ await apiFetchResponse("/api/community/channels/private/messages", { method: "POST", body: JSON.stringify({ text: "fixture-private-body" }), observation: { action: dm, reason: "command" } })+ finishAction(dm, "success")+ await vi.advanceTimersByTimeAsync(3000)+ spans.length = 0+ visit(sent.slice(beforeDm))+ const parent = spans.find(span => span.spanId === dmContext.spanId)!+ const child = children(dmContext)[0]!+ const attributes = (span: Record<string, unknown>) => Object.fromEntries((span.attributes as Array<{ key: string; value: { stringValue: string } }>).map(attribute => [attribute.key, attribute.value.stringValue]))+ expect(parent).toMatchObject({ name: "dm.message.send", kind: 1, traceId: dmContext.traceId })+ expect(attributes(parent)).toMatchObject({ action_id: dm.id, session_id: extended, "session.id": extended })+ expect(attributes(parent)).not.toHaveProperty("navigation_id")+ expect(attributes(parent)).not.toHaveProperty("http.request.method")+ expect(Object.values(attributes(parent))).not.toContain("undefined")+ expect(child).toMatchObject({ name: "POST /api/community/channels/[id]/messages", kind: 3, traceId: dmContext.traceId, parentSpanId: dmContext.spanId })+ expect(attributes(child)).toMatchObject({ "http.request.method": "POST", "http.response.status_code": "201", session_id: extended })+ expect(JSON.stringify(sent.slice(beforeDm))).not.toContain("fixture-private-body")+ for (const body of sent) expect(body).toMatchObject({ meta: { sdk: { name: "faro-web", version: "2.12.1" } } })+ consent("denied")+ const size = sent.length+ emitTelemetry("business.result", { outcome: "success" })+ await vi.advanceTimersByTimeAsync(1500)+ expect(sent).toHaveLength(size)+})diff --git a/src/web/src/lib/observability/client.ts b/src/web/src/lib/observability/client.tsnew file mode 100644index 000000000..e0ed2e2f7--- /dev/null+++ b/src/web/src/lib/observability/client.ts@@ -0,0 +1,263 @@+import type { Faro, Instrumentation, FetchTransport } from "@grafana/faro-web-sdk"+import type { getDefaultOTELInstrumentations } from "@grafana/faro-web-tracing"+import { ANALYTICS_CONSENT_CHANGE_EVENT, hasAnalyticsConsent } from "../analytics-consent"+import { capabilityLimits, routeTemplate } from "./coverage"+import { actionSequence, beginNavigation, clearActions, finishAction, installActionSpans, startAction, telemetryId } from "./context"+import { alignInitialTelemetrySession, configureTelemetry, emitTelemetry, installTelemetrySink, isTelemetryEligible, telemetryGeneration, reportTelemetryDrops, retireTelemetry } from "./telemetry"+import { sanitizeItem } from "./sanitize"+import { installBrowserObservers } from "./browser"+import { resolveCommunityModulePlan } from "../community/community-route"+import { cleanAttributes } from "./schema"++type BuildProfile = { url?: string; environment?: string; release?: string }+function validBuildProfile(profile: BuildProfile) {+ try {+ const url = new URL(profile.url ?? "")+ return url.protocol === "https:" && !url.username && !url.password && !url.search && !url.hash+ } catch { return false }+}+const build: BuildProfile = {+ url: process.env.NEXT_PUBLIC_FARO_COLLECTOR_URL,+ ...cleanAttributes({ environment: process.env.NEXT_PUBLIC_FARO_ENVIRONMENT, release: process.env.NEXT_PUBLIC_FARO_RELEASE }),+}+let started = false+let documentSuspended = false+let faro: Faro | undefined+let transport: FetchTransport | undefined+let controller: AbortController | undefined+let sessionId = ""+let load: Promise<void> | undefined+let pendingReconcile = false+let pendingInitialNavigation = false+let deliveryFailures = 0+let deliveryFailureReason = "unknown"+let makeTransport: (() => FetchTransport) | undefined+let stopBrowser: (() => void) | undefined+let eligibleSince = 0+let vitalsInitialized = false+let surface: "web" | "blog" = "web"+let userKey: string | undefined+let identityEstablished = false+let identityRevision = 0+let mayResumeNativeSession = hasAnalyticsConsent()+let clearNativeSession: (() => void) | undefined+let httpInstrumentations: ReturnType<typeof getDefaultOTELInstrumentations> = []+let webInstrumentations: Instrumentation[] = []+const pageId = telemetryId()++function deactivate() {+ retireTelemetry()+ clearActions()+ installActionSpans(undefined)+ stopBrowser?.()+ stopBrowser = undefined+ faro?.pause()+ if (transport) faro?.transports.remove(transport)+ controller?.abort()+ transport = undefined+ controller = undefined+ deliveryFailures = 0+ deliveryFailureReason = "unknown"+ for (const instrumentation of httpInstrumentations.flat()) instrumentation.disable()+}+function configure() {+ configureTelemetry({ release: build.release, environment: build.environment, frontend_surface: surface, page_instance_id: pageId, session_id: sessionId, user_key: userKey }, true)+}+async function activate() {+ if (documentSuspended || !hasAnalyticsConsent() || !validBuildProfile(build)) return+ const route = routeTemplate(window.location.href, window.location.origin)+ const communityOwner = (route === "/c" || route.startsWith("/c/")) && resolveCommunityModulePlan(window.location.pathname).route !== "public-invite"+ const applicationOwner = route.startsWith("/w/") || ["/workspaces", "/studio/new", "/invite/[token]"].includes(route)+ if (!identityEstablished && (communityOwner || applicationOwner)) return+ const mayResume = mayResumeNativeSession+ sessionId = telemetryId()+ configure()+ if (pendingInitialNavigation) { pendingInitialNavigation = false; beginNavigation(window.location.href, "document") }+ const capturedSession = sessionId+ const [{ initializeFaro, FetchTransport: NativeFetchTransport, getWebInstrumentations, InternalLoggerLevel, VolatileSessionsManager }, { TracingInstrumentation, getDefaultOTELInstrumentations: createHttp }] = await Promise.all([+ import("@grafana/faro-web-sdk"), import("@grafana/faro-web-tracing"),+ ])+ clearNativeSession = () => VolatileSessionsManager.removeUserSession()+ if (documentSuspended || !hasAnalyticsConsent() || capturedSession !== sessionId || !isTelemetryEligible()) return+ mayResumeNativeSession = false+ makeTransport = () => {+ controller = new AbortController()+ const ownerSession = sessionId+ class ObservedFetchTransport extends NativeFetchTransport {+ override logError(...args: Parameters<FetchTransport["logError"]>) {+ if (ownerSession !== sessionId || !isTelemetryEligible()) return+ deliveryFailures = Math.min(deliveryFailures + 1, 1_000_000)+ const detail = args.find(value => value && typeof value === "object") as Record<string, unknown> | undefined+ deliveryFailureReason = detail?.status === 429 ? "rate_limit" : detail?.kind === "http" || typeof detail?.status === "number" ? "http_error" : detail?.kind === "timeout" ? "timeout" : detail?.kind === "aborted" ? "abort" : String(args[0]).includes("retries exhausted") ? "retries_exhausted" : "unknown"+ }+ }+ return new ObservedFetchTransport({ url: build.url!, bufferSize: 16, concurrency: 2, retry: { maxAttempts: 2, initialBackoffMs: 1000, maxBackoffMs: 5000 }, requestTimeoutMs: 5000, requestOptions: { signal: controller.signal, credentials: "omit" } })+ }+ transport = makeTransport()+ if (!faro) {+ const accountScope = userKey ?? "anon"+ let storedScope: string | undefined+ try { storedScope = VolatileSessionsManager.fetchUserSession()?.sessionMeta?.attributes?.alook_account } catch { clearNativeSession() }+ if (!mayResume || storedScope !== accountScope) clearNativeSession()+ httpInstrumentations = createHttp({ ignoreUrls: [build.url!], propagateTraceHeaderCorsUrls: [new RegExp("^" + window.location.origin.replace(/[.*+?^$(){}|[\]\\]/g, "\\$&") + "/")] })+ const defaults = getWebInstrumentations({ captureConsole: false, enableContentSecurityPolicyInstrumentation: false, enablePerformanceInstrumentation: false })+ const vitals = defaults.find(instrumentation => instrumentation.name.endsWith("instrumentation-web-vitals"))+ if (vitals) {+ const initialize = vitals.initialize+ vitals.initialize = function () {+ if (vitalsInitialized) return+ vitalsInitialized = true+ const original = this.api.pushMeasurement+ this.api = { ...this.api, pushMeasurement: (measurement, options) => {+ if (!hasAnalyticsConsent() || !isTelemetryEligible()) return+ const values = Object.fromEntries(Object.entries(measurement.values).filter(([key,value]) => /^(lcp|cls|inp|fcp|ttfb)$/.test(key) && typeof value === "number" && Number.isFinite(value)))+ if (Object.keys(values).length) original({ type: "web-vitals", values }, { skipDedupe: options?.skipDedupe })+ } }+ initialize.call(this)+ }+ }+ webInstrumentations = defaults.filter(instrumentation => !instrumentation.name.endsWith("instrumentation-errors") && !instrumentation.name.endsWith("instrumentation-navigation"))+ const initialTransport = transport+ faro = initializeFaro({+ app: { name: "alook-web", version: build.release, release: build.release, environment: build.environment },+ preventGlobalExposure: true,+ dedupe: false,+ internalLoggerLevel: InternalLoggerLevel.OFF,+ transports: [transport],+ instrumentations: [...webInstrumentations, new TracingInstrumentation({ instrumentations: httpInstrumentations })],+ sessionTracking: { enabled: true, persistent: false, samplingRate: 1, generateSessionId: telemetryId, session: { attributes: { alook_account: accountScope } }, onSessionChange: (_previous, next) => { if (next.id) adoptNativeSession(next.id) } },+ pageTracking: { generatePageId: () => pageId },+ trackGeolocation: false,+ webVitalsInstrumentation: { trackAttributionSources: false },+ batching: { enabled: true, itemLimit: 40, sendTimeout: 1000 },+ beforeSend: item => hasAnalyticsConsent() && isTelemetryEligible() ? sanitizeItem(item, sessionId, window.location.origin) : null,+ })+ const initialized = faro?.api.getSession()+ if (!faro || !initialized?.id || !/^[a-zA-Z0-9_-]{1,80}$/.test(initialized.id) || initialized.attributes?.alook_account !== accountScope) { deactivate(); return }+ if (initialized.id !== capturedSession) {+ if (!alignInitialTelemetrySession(capturedSession, initialized.id)) { deactivate(); return }+ sessionId = initialized.id+ configure()+ faro.transports.remove(initialTransport)+ controller?.abort()+ transport = makeTransport()+ faro.transports.add(transport)+ }+ faro.api.setUser(userKey ? { id: userKey } : undefined)+ } else {+ faro.transports.add(transport)+ for (const instrumentation of httpInstrumentations.flat()) instrumentation.enable()+ faro.api.setUser(userKey ? { id: userKey } : undefined)+ faro.unpause()+ faro.api.setSession({ id: capturedSession, attributes: { isSampled: "true", alook_account: userKey ?? "anon" } })+ }+ if (!faro) { deactivate(); return }+ installActionSpans((name, attributes, startTime) => {+ if (!isTelemetryEligible()) return+ return faro?.api.getOTEL()?.trace.getTracer("alook.frontend").startSpan(name, { attributes, startTime })+ })+ connectSink()+ stopBrowser = installBrowserObservers(faro, build.url!, eligibleSince)+ emitTelemetry("telemetry.coverage", { collection_rate: 1, eligibility: "eligible", capability: "available", count: Object.keys(capabilityLimits).length })+}+function connectSink() {+ installTelemetrySink(event => {+ if (!hasAnalyticsConsent() || !isTelemetryEligible()) return+ if (deliveryFailures) {+ const count = deliveryFailures+ deliveryFailures = 0+ faro?.api.pushEvent("telemetry.coverage", { delivery_failure_count: String(count), delivery_failure_reason: deliveryFailureReason, outcome: "error", capability: "limited", session_id: sessionId, frontend_surface: surface }, "alook.frontend", { skipDedupe: true })+ }+ faro?.api.pushEvent(event.name, event.attributes, "alook.frontend", { skipDedupe: true, timestampOverwriteMs: event.timestamp })+ })+}+function adoptNativeSession(next: string) {+ if (next === sessionId || !/^[a-zA-Z0-9_-]{1,80}$/.test(next) || !hasAnalyticsConsent() || !isTelemetryEligible()) return+ retireTelemetry("native_session")+ clearActions()+ stopBrowser?.()+ if (transport) faro?.transports.remove(transport)+ controller?.abort()+ sessionId = next+ deliveryFailures = 0+ deliveryFailureReason = "unknown"+ eligibleSince = performance.now()+ configure()+ transport = makeTransport?.()+ if (transport) faro?.transports.add(transport)+ connectSink()+ if (faro) stopBrowser = installBrowserObservers(faro, build.url!, eligibleSince)+ emitTelemetry("telemetry.coverage", { eligibility: "eligible", capability: "available", phase: "auth" })+}+function reconcile() {+ if (documentSuspended) return+ if (!hasAnalyticsConsent()) { mayResumeNativeSession = false; clearNativeSession?.(); deactivate(); return }+ if (load) { pendingReconcile = true; return }+ if (isTelemetryEligible()) return+ load = activate().catch(() => { deactivate() }).finally(() => {+ load = undefined+ if (pendingReconcile) { pendingReconcile = false; reconcile() }+ })+}+export function setTelemetryUser(key: string | null) {+ const next = key && /^[a-zA-Z0-9_-]{8,64}$/.test(key) ? key : undefined+ const firstIdentity = !identityEstablished+ identityEstablished = true+ if (userKey === next) { if (firstIdentity && started) reconcile(); return }+ identityRevision+++ if (!firstIdentity || faro) { mayResumeNativeSession = false; clearNativeSession?.() }+ const wasEligible = isTelemetryEligible()+ deactivate()+ userKey = next+ sessionId = telemetryId()+ if (wasEligible || hasAnalyticsConsent()) reconcile()+}+export function captureTelemetryIdentityRetirement() {+ const original = userKey, revision = identityRevision+ return () => { if (original && original === userKey && revision === identityRevision) setTelemetryUser(null) }+}+export function bootstrapObservability(nextSurface: "web" | "blog") {+ if (started || typeof window === "undefined") return+ started = true+ surface = nextSurface+ pendingInitialNavigation = hasAnalyticsConsent() && validBuildProfile(build)+ window.addEventListener(ANALYTICS_CONSENT_CHANGE_EVENT, () => { eligibleSince = performance.now(); if (!hasAnalyticsConsent()) pendingInitialNavigation = false; reconcile() })+ window.addEventListener("popstate", () => { if (isTelemetryEligible()) beginNavigation(window.location.href) })+ document.addEventListener("visibilitychange", () => {+ if (isTelemetryEligible()) { reportTelemetryDrops("transport_failure"); emitTelemetry("telemetry.coverage", { visibility: document.visibilityState, capability: "limited" }) }+ })+ window.addEventListener("pagehide", () => {+ documentSuspended = true+ pendingInitialNavigation = false+ deactivate()+ }, { capture: true })+ window.addEventListener("pageshow", event => {+ if (!event.persisted) return+ documentSuspended = false+ pendingInitialNavigation = false+ mayResumeNativeSession = false+ clearNativeSession?.()+ eligibleSince = performance.now()+ deactivate()+ reconcile()+ }, { capture: true })+ document.addEventListener("click", event => {+ if (!isTelemetryEligible() || !(event.target instanceof Element)) return+ const control = event.target.closest("a,button,[role=button],input[type=checkbox],select")+ if (!control) return+ if (control instanceof HTMLAnchorElement && control.href && control.origin === window.location.origin && !control.download && control.target !== "_blank" && !(event instanceof MouseEvent && (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey)) && routeTemplate(control.href, window.location.origin) !== "/unmapped") beginNavigation(control.href, "gesture")+ else {+ const before = actionSequence(), generation = telemetryGeneration()+ queueMicrotask(() => {+ if (!isTelemetryEligible() || generation !== telemetryGeneration() || actionSequence() !== before) return+ const action = startAction("ui_interaction", { phase: "interaction" })+ if (!faro?.api.getActiveUserAction()) faro?.api.startUserAction("ui_interaction", { session_id: sessionId })+ finishAction(action, "observed", { phase: "interaction" })+ })+ }+ }, { capture: true, passive: true })+ reconcile()+}+export function onObservedRouterTransition(url: string) {+ if (isTelemetryEligible()) beginNavigation(url, "transport")+}diff --git a/src/web/src/lib/observability/context.test.ts b/src/web/src/lib/observability/context.test.tsnew file mode 100644index 000000000..bbad962de--- /dev/null+++ b/src/web/src/lib/observability/context.test.ts@@ -0,0 +1,254 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { bindCommandAction, beginNavigation, clearActions, commandObservation, finishAction, startAction, installActionSpans, navigationForHref, commitNavigation, committedNavigationPathname } from "./context"+import { alignInitialTelemetrySession, configureTelemetry, emitTelemetry, installTelemetrySink, retireTelemetry, telemetryGeneration } from "./telemetry"+import type { Span } from "@opentelemetry/api"+import { startRequest, requestHeaders, readObservedResponse } from "./requests"+import { resolveActionName } from "./actions"++describe("original observation ownership", () => {+ const events: Array<{ name: string; attributes: Record<string, string> }> = []+ beforeEach(() => { vi.useFakeTimers(); events.length = 0; configureTelemetry({ session_id: "session-a" }, true); installTelemetrySink(event => events.push(event)) })+ afterEach(() => { retireTelemetry(); clearActions(); installActionSpans(undefined); vi.useRealTimers() })+ it("keeps an intent through synchronous native session extension and ends the returned span", () => {+ const end = vi.fn()+ installActionSpans(() => {+ retireTelemetry("native_session"); clearActions()+ configureTelemetry({ session_id: "session-b" }, true); installTelemetrySink(event => events.push(event))+ return { end, setAttribute: vi.fn() } as unknown as Span+ })+ const action = beginNavigation("/c/me/bots")!+ expect(action.done).toBe(false)+ expect(action.generation).toBe(telemetryGeneration())+ expect(navigationForHref("/c/me/bots")).toBe(action)+ finishAction(action, "success")+ expect(end).toHaveBeenCalledTimes(1)+ expect(events.filter(event => ["action.start", "action.finish"].includes(event.name)).map(event => event.attributes.session_id)).toEqual(["session-b", "session-b"])+ })+ it("ends and discards a span when its factory crosses a revoke or account boundary", () => {+ const end = vi.fn()+ installActionSpans(() => {+ retireTelemetry(); clearActions(); configureTelemetry({ session_id: "account-b" }, true); installTelemetrySink(event => events.push(event))+ return { end } as unknown as Span+ })+ expect(startAction("message.edit")).toBeUndefined()+ expect(end).toHaveBeenCalledTimes(1)+ expect(events.filter(event => event.name.startsWith("action."))).toEqual([])+ })+ it("passes only present whitelisted attributes to native action spans", () => {+ const factory = vi.fn((_name: string, _fields: Record<string, string>) => ({ end: vi.fn(), setAttribute: vi.fn() } as unknown as Span))+ installActionSpans(factory)+ const dm = startAction("dm.message.send")!+ const navigation = beginNavigation("/c/me/bots")!+ const dmFields = factory.mock.calls[0]![1] as Record<string, string>+ const navigationFields = factory.mock.calls[1]![1] as Record<string, string>+ expect(dmFields).toMatchObject({ action_id: dm.id, action_name: "dm.message.send", start_ms: String(dm.start) })+ expect(dmFields).not.toHaveProperty("navigation_id")+ expect(dmFields).not.toHaveProperty("trace_id")+ expect(dmFields).not.toHaveProperty("span_id")+ expect(Object.values(dmFields)).not.toContain("undefined")+ expect(navigationFields.navigation_id).toBe(navigation.navigationId)+ finishAction(dm, undefined)+ expect(dm.span!.setAttribute).not.toHaveBeenCalled()+ finishAction(navigation, "success")+ expect(navigation.span!.setAttribute).toHaveBeenCalledWith("outcome", "success")+ })+ it("keeps concurrent commands and their requests on their original tokens", async () => {+ const one = { original: {} }, two = { original: {} }+ const a = startAction("message.edit")!, b = startAction("message.pin")!+ bindCommandAction(one, a); bindCommandAction(two, b)+ const request = startRequest("/api/community/messages/private", { method: "PATCH", observation: commandObservation(one.original) })+ const response = new Response("{}", { headers: { "cf-ray": "a".repeat(16) + "-SJC" } })+ requestHeaders(request, response)+ await readObservedResponse(response, () => response.json())+ finishAction(b, "success"); finishAction(a, "success")+ expect(events.filter(event => event.name.startsWith("request.")).every(event => event.attributes.action_id === a.id)).toBe(true)+ expect(commandObservation(two.original)?.action?.id).toBe(b.id)+ expect(events.filter(event => event.name === "action.finish").map(event => event.attributes.action_id)).toEqual([b.id, a.id])+ expect(JSON.stringify(events)).not.toContain("private")+ })+ it("rejects old parsed responses, actions and command contexts after retirement", async () => {+ const intent = { original: {} }, action = startAction("message.edit")!+ bindCommandAction(intent, action)+ const request = startRequest("/api/community/messages/private", { observation: commandObservation(intent.original) })+ const response = new Response("{}")+ requestHeaders(request, response)+ retireTelemetry(); configureTelemetry({ session_id: "session-b" }, true); installTelemetrySink(event => events.push(event)); events.length = 0+ await readObservedResponse(response, () => response.json())+ finishAction(action, "success")+ expect(events).toEqual([])+ expect(commandObservation(intent.original)).toBeUndefined()+ })+ it("closes superseded navigation once and records the winner independently", () => {+ const a = beginNavigation("/c/me/bots")!, b = beginNavigation("/c/me/friends")!, c = beginNavigation("/c/me/machines")!+ finishAction(c, "success"); finishAction(a, "success"); finishAction(b, "success")+ expect(events.filter(event => event.name === "action.finish").map(event => event.attributes.outcome)).toEqual(["superseded", "superseded", "success"])+ })+ it("bounds pre-SDK events and separates event drops from delivery failures", () => {+ retireTelemetry(); configureTelemetry({ session_id: "session-c" }, true); events.length = 0+ for (let i = 0; i < 300; i++) emitTelemetry("telemetry.coverage", { count: i })+ installTelemetrySink(event => events.push(event))+ expect(events).toHaveLength(257)+ expect(events.at(-1)?.attributes).toMatchObject({ drop_count: "44", drop_reason: "early_queue_full" })+ })+ it("preserves an accepted unsent intent, request ownership and timestamp across initial native identity alignment", async () => {+ retireTelemetry(); clearActions(); configureTelemetry({ session_id: "provisional" }, true)+ const generation = telemetryGeneration(), timestamp = Date.now()+ const action = startAction("message.edit")!+ const request = startRequest("/api/community/messages/private", { observation: { action, reason: "command" } })+ const response = new Response("{}")+ vi.setSystemTime(timestamp + 500)+ expect(alignInitialTelemetrySession("provisional", "native-session")).toBe(true)+ expect(telemetryGeneration()).toBe(generation)+ expect(action.done).toBe(false)+ requestHeaders(request, response)+ await readObservedResponse(response, () => response.json())+ finishAction(action, "success")+ const pending: Array<{ name: string; timestamp: number; attributes: Record<string, string> }> = []+ installTelemetrySink(event => pending.push(event))+ expect(pending[0]).toMatchObject({ name: "action.start", timestamp, attributes: { session_id: "native-session", action_id: action.id } })+ expect(pending.every(event => event.attributes.session_id === "native-session" && event.attributes.action_id === action.id)).toBe(true)+ expect(pending.some(event => event.name === "request.body_parsed")).toBe(true)+ expect(pending.at(-1)?.name).toBe("action.finish")+ })+ it("does not align a live sink, a different pending identity, or retired work", () => {+ expect(alignInitialTelemetrySession("session-a", "native-session")).toBe(false)+ retireTelemetry(); configureTelemetry({ session_id: "provisional" }, true)+ emitTelemetry("business.result", { session_id: "different" })+ expect(alignInitialTelemetrySession("provisional", "native-session")).toBe(false)+ retireTelemetry(); configureTelemetry({ session_id: "account-b" }, true)+ expect(alignInitialTelemetrySession("provisional", "native-session")).toBe(false)+ emitTelemetry("business.result", { action_name: "message.pin" })+ expect(alignInitialTelemetrySession("account-b", "native-session")).toBe(true)+ installTelemetrySink(event => events.push(event))+ expect(events).toHaveLength(1)+ expect(events[0]?.attributes).toMatchObject({ action_name: "message.pin", session_id: "native-session" })+ retireTelemetry()+ expect(alignInitialTelemetrySession("native-session", "another-session")).toBe(false)+ })+ it("uses business enums and labels unsupported command kinds as a gap", () => {+ expect(resolveActionName("billing.redirect", { action: { kind: "checkout", priceId: "PRIVATE" } })).toBe("billing.checkout.start")+ expect(resolveActionName("bot.command", { input: { kind: "delete-command" } })).toBe("bot.delete")+ expect(resolveActionName("issue.command", { action: { kind: "comment" } })).toBe("issue.comment.create")+ expect(resolveActionName("billing.redirect", { action: { kind: "PRIVATE" } })).toBe("command.unknown")+ })+ it("adopts a gesture into router transport on the same action without a duplicate start", () => {+ const action = beginNavigation("/c/me/machines", "gesture")!+ expect(beginNavigation("/c/me/machines", "transport")).toBe(action)+ expect(events.filter(event => event.name === "action.start")).toHaveLength(1)+ expect(events.filter(event => event.name === "navigation.intent").map(event => event.attributes.phase)).toEqual(["intent", "transport"])+ finishAction(action, "success")+ expect(events.filter(event => event.name === "action.finish")).toHaveLength(1)+ })+ it("keeps structural renderer ownership across retirement without emitting denied commits", () => {+ commitNavigation("/c/channels/server-a/forum-a?tag=hello%20there")+ const action = beginNavigation("/c/channels/server-a/text-a?q=hello+there")!+ expect(committedNavigationPathname()).toBe("/c/channels/server-a/forum-a")+ expect(beginNavigation("/c/channels/server-a/text-a?q=hello+there", "transport")).toBe(action)+ commitNavigation("/c/channels/server-a/text-a")+ expect(committedNavigationPathname()).toBe("/c/channels/server-a/text-a")+ retireTelemetry(); clearActions()+ expect(committedNavigationPathname()).toBe("/c/channels/server-a/text-a")+ const count = events.length+ commitNavigation("/c/me")+ expect(committedNavigationPathname()).toBe("/c/me")+ expect(events).toHaveLength(count)+ })++ it("measures document visits from the document clock and later visits from their own intent", () => {+ vi.advanceTimersByTime(400)+ const document = beginNavigation("/c/me/bots", "document")!+ vi.advanceTimersByTime(60)+ finishAction(document, "success", { region: "bots", phase: "primary" })+ finishAction(document, "success", { region: "bots", phase: "primary" })+ vi.advanceTimersByTime(1000)+ const route = beginNavigation("/c/me/friends", "gesture")!+ vi.advanceTimersByTime(20)+ expect(beginNavigation("/c/me/friends", "transport")).toBe(route)+ vi.advanceTimersByTime(30)+ finishAction(route, "success", { region: "friends", phase: "primary" })+ const ready = events.filter(event => event.name === "navigation.ready")+ expect(ready).toHaveLength(2)+ expect(ready[0]?.attributes).toMatchObject({ navigation_kind: "document", start_ms: "0", duration_ms: "460", action_id: document.id, region: "bots" })+ expect(ready[1]?.attributes).toMatchObject({ navigation_kind: "route", duration_ms: "50", action_id: route.id, region: "friends" })+ })++ it("does not turn unfinished or retired visits and non-content completion into ready metrics", () => {+ beginNavigation("/c/me/bots")+ const cancelled = beginNavigation("/c/me/friends")!+ finishAction(cancelled, "cancelled", { region: "friends", phase: "primary" })+ beginNavigation("/c/me/machines")+ vi.advanceTimersByTime(30_000)+ const shell = beginNavigation("/c/me/bots")!+ finishAction(shell, "success", { region: "shell", phase: "commit" })+ const old = beginNavigation("/c/me/friends")!+ retireTelemetry(); clearActions(); configureTelemetry({ session_id: "session-b" }, true); installTelemetrySink(event => events.push(event))+ finishAction(old, "success", { region: "friends", phase: "primary" })+ expect(events.filter(event => event.name === "navigation.ready")).toEqual([])+ })++ it("binds completed and live deferred navigations with their original clocks and request trace fields", () => {+ retireTelemetry(); clearActions(); configureTelemetry({ session_id: "pending" }, true); events.length = 0+ const first = beginNavigation("/c/me/bots", "document")!+ vi.advanceTimersByTime(240)+ finishAction(first, "success", { phase: "primary", region: "bots" })+ const second = beginNavigation("/c/me/friends")!+ const request = startRequest("/api/agents", { observation: { action: second, reason: "router" } })+ vi.advanceTimersByTime(660)+ const spans = [first, second].map((_action, index) => ({ spanContext: () => ({ traceId: String(index + 1).repeat(32), spanId: String(index + 1).repeat(16) }), setAttribute: vi.fn(), end: vi.fn() }))+ const factory = vi.fn((_name: string, _fields: Record<string, string>, _start: number) => spans[factory.mock.calls.length - 1] as unknown as Span)+ installActionSpans(factory)+ expect(factory.mock.calls.map(call => call[2])).toEqual([performance.timeOrigin, performance.timeOrigin + second.start])+ expect(spans[0]!.end).toHaveBeenCalledWith(performance.timeOrigin + 240)+ expect(spans[0]!.setAttribute).toHaveBeenCalledWith("outcome", "success")+ expect(spans[1]!.end).not.toHaveBeenCalled()+ requestHeaders(request, new Response(null, { status: 204 }))+ finishAction(second, "success", { phase: "primary", region: "friends" })+ installTelemetrySink(event => events.push(event))+ for (const [index, action] of [first, second].entries()) {+ const owned = events.filter(event => event.attributes.action_id === action.id)+ expect(owned.length).toBeGreaterThan(0)+ expect(owned.every(event => event.attributes.trace_id === String(index + 1).repeat(32) && event.attributes.span_id === String(index + 1).repeat(16))).toBe(true)+ }+ expect(spans[1]!.end).toHaveBeenCalledWith(performance.timeOrigin + 900)+ installActionSpans(factory)+ expect(factory).toHaveBeenCalledTimes(2)+ })+ it("bounds deferred navigations and discards completed and live references on retirement", () => {+ retireTelemetry(); clearActions(); configureTelemetry({ session_id: "pending" }, true)+ for (let i = 0; i < 80; i++) finishAction(beginNavigation("/c/me/bots"), "success", { phase: "primary", region: "bots" })+ const factory = vi.fn(() => ({ end: vi.fn(), setAttribute: vi.fn() } as unknown as Span))+ installActionSpans(factory)+ expect(factory).toHaveBeenCalledTimes(64)+ installActionSpans(undefined)+ finishAction(beginNavigation("/c/me/bots"), "success", { phase: "primary", region: "bots" })+ beginNavigation("/c/me/friends")+ retireTelemetry(); clearActions(); configureTelemetry({ session_id: "account-b" }, true)+ factory.mockClear(); installActionSpans(factory)+ expect(factory).not.toHaveBeenCalled()+ installTelemetrySink(event => events.push(event))+ expect(events).toEqual([])+ })+ it("ends a completed deferred span even if setting its outcome fails", () => {+ retireTelemetry(); clearActions(); configureTelemetry({ session_id: "pending" }, true)+ const action = beginNavigation("/c/me/bots", "document")!+ vi.advanceTimersByTime(50)+ finishAction(action, "success", { phase: "primary", region: "bots" })+ const end = vi.fn()+ installActionSpans(() => ({ end, setAttribute: () => { throw new Error("unavailable") } } as unknown as Span))+ expect(end).toHaveBeenCalledWith(performance.timeOrigin + 50)+ })+ it("discards deferred binding when the factory retires its original account", () => {+ retireTelemetry(); clearActions(); configureTelemetry({ session_id: "pending" }, true)+ const action = beginNavigation("/c/me/bots", "document")!+ finishAction(action, "success", { phase: "primary", region: "bots" })+ const end = vi.fn()+ installActionSpans(() => {+ retireTelemetry(); clearActions(); configureTelemetry({ session_id: "account-b" }, true)+ return { end } as unknown as Span+ })+ expect(action.span).toBeUndefined()+ expect(end).toHaveBeenCalledTimes(1)+ installTelemetrySink(event => events.push(event))+ expect(events).toEqual([])+ })+})diff --git a/src/web/src/lib/observability/context.ts b/src/web/src/lib/observability/context.tsnew file mode 100644index 000000000..7e2259be4--- /dev/null+++ b/src/web/src/lib/observability/context.ts@@ -0,0 +1,136 @@+import type { Span } from "@opentelemetry/api"+import { routeTemplate, actionNames } from "./coverage"+import { emitTelemetry, isTelemetryEligible, isNativeSessionContinuation, telemetryGeneration, notifyObservation, linkQueuedActionTrace } from "./telemetry"+import { cleanAttributes, type Attributes } from "./schema"++export type Action = { id: string; navigationId?: string; navigationKind?: "document" | "route"; name: string; route: string; start: number; generation: number; done: boolean; end?: number; outcome?: Attributes["outcome"]; span?: Span; timer?: ReturnType<typeof setTimeout> }+let makeSpan: ((name: string, attributes: Record<string, string>, startTime: number) => Span | undefined) | undefined+const live = new Set<Action>()+const deferred = new Set<Action>()+let navigation: Action | undefined+let navigationHref: string | undefined+let committedHref: string | undefined+let gesturePending = false+let sequence = 0+export function actionSequence() { return sequence }+const names = new Set<string>(actionNames)+export const telemetryId = () => typeof crypto !== "undefined" ? crypto.randomUUID() : String(Date.now())+export const currentRoute = () => typeof window === "undefined" ? "/unmapped" : routeTemplate(window.location.href, window.location.origin)+export function installActionSpans(factory: typeof makeSpan) {+ makeSpan = factory+ if (!factory) return+ for (const action of deferred) {+ deferred.delete(action)+ if (!isTelemetryEligible() || action.generation !== telemetryGeneration()) continue+ let span: Span | undefined+ try { span = factory(action.name, cleanAttributes(actionAttributes(action)), performance.timeOrigin + action.start) } catch {}+ if (!isTelemetryEligible() || action.generation !== telemetryGeneration()) { try { span?.end() } catch {}; continue }+ action.span = span+ const attributes = actionAttributes(action)+ linkQueuedActionTrace(action.id, action.generation, attributes.trace_id, attributes.span_id)+ if (action.done && action.end !== undefined) {+ const outcome = cleanAttributes({ outcome: action.outcome }).outcome+ if (outcome !== undefined) { try { span?.setAttribute("outcome", outcome) } catch {} }+ try { span?.end(performance.timeOrigin + action.end) } catch {}+ }+ }+}++export function startAction(name: string, attributes: Attributes = {}, start = performance.now()): Action | undefined {+ if (!isTelemetryEligible() || !names.has(name)) return+ if (live.size >= 64) finishAction(live.values().next().value, "cancelled")+ const action: Action = { id: telemetryId(), name, route: String(attributes.route_template ?? currentRoute()), start, generation: telemetryGeneration(), done: false }+ if (name === "navigation") { action.navigationId = telemetryId(); action.navigationKind = attributes.navigation_kind === "document" ? "document" : "route" }+ const fields = actionAttributes(action)+ try { action.span = makeSpan?.(name, cleanAttributes(fields), performance.timeOrigin + action.start) } catch {}+ if (!isTelemetryEligible() || (action.generation !== telemetryGeneration() && !isNativeSessionContinuation(action.generation))) {+ try { action.span?.end() } catch {}+ return+ }+ action.generation = telemetryGeneration()+ sequence+++ live.add(action)+ if (action.navigationId && !action.span) {+ if (deferred.size >= 64) deferred.delete(deferred.values().next().value!)+ deferred.add(action)+ }+ emitTelemetry("action.start", { ...actionAttributes(action), ...attributes, phase: "intent" })+ action.timer = setTimeout(() => finishAction(action, "timeout"), 30_000)+ return action+}+export function actionAttributes(action?: Action): Attributes {+ let span+ try { span = action?.span?.spanContext() } catch {}+ return action ? { trace_id: span?.traceId, span_id: span?.spanId, action_id: action.id, navigation_id: action.navigationId, navigation_kind: action.navigationKind, action_name: action.name, route_template: action.route, start_ms: action.start } : {}+}+export function finishAction(action: Action | undefined, outcome: Attributes["outcome"], fields: Attributes = {}) {+ if (!action || action.done) return+ action.done = true+ action.end = performance.now()+ action.outcome = outcome+ clearTimeout(action.timer)+ live.delete(action)+ if (action.generation === telemetryGeneration()) {+ const attributes = { ...actionAttributes(action), ...fields, outcome, duration_ms: action.end - action.start }+ emitTelemetry("action.finish", attributes)+ if (action.navigationId && outcome === "success" && fields.phase === "primary") emitTelemetry("navigation.ready", attributes)+ const safeOutcome = cleanAttributes({ outcome }).outcome+ if (safeOutcome !== undefined) {+ try { action.span?.setAttribute("outcome", safeOutcome) } catch {}+ }+ }+ try { action.span?.end(performance.timeOrigin + action.end) } catch {}+ if (action === navigation) notifyObservation()+}+export function clearActions() {+ for (const action of live) finishAction(action, "cancelled")+ deferred.clear()+ navigation = undefined+ navigationHref = undefined+ gesturePending = false+}+function normalizedHref(href: string) {+ const origin = typeof window === "undefined" ? "https://alook.ai" : window.location.origin+ try { const url = new URL(href, origin); return url.origin === origin ? url.pathname + url.search : undefined } catch { return undefined }+}+export function beginNavigation(href: string, phase: "intent" | "transport" | "gesture" | "document" = "intent") {+ if (!isTelemetryEligible()) return+ const target = normalizedHref(href)+ if (!target) return+ if (navigation && navigationHref === target && !navigation.done && (phase === "transport" || (phase === "intent" && gesturePending))) {+ gesturePending = false+ if (phase === "transport") emitTelemetry("navigation.intent", { ...actionAttributes(navigation), phase, request_reason: "router" })+ return navigation+ }+ finishAction(navigation, "superseded")+ navigation = startAction("navigation", { route_template: routeTemplate(href, typeof window === "undefined" ? "https://alook.ai" : window.location.origin), navigation_kind: phase === "document" ? "document" : "route" }, phase === "document" ? 0 : performance.now())+ if (!navigation) return+ navigationHref = target+ gesturePending = phase === "gesture"+ emitTelemetry("navigation.intent", { ...actionAttributes(navigation), phase: phase === "document" ? "hydrate" : phase === "gesture" ? "intent" : phase, request_reason: "router" })+ notifyObservation()+ return navigation+}+export function navigationNoop(href: string) { const action = beginNavigation(href); finishAction(action, "noop") }+export function commitNavigation(href: string, region: "shell" | "page" = "shell") {+ committedHref = normalizedHref(href)+ if (!isTelemetryEligible()) return+ const matched = navigationHref === committedHref && navigation && !navigation.done ? navigation : undefined+ emitTelemetry("navigation.commit", { ...actionAttributes(matched), route_template: routeTemplate(href, typeof window === "undefined" ? "https://alook.ai" : window.location.origin), region, phase: "commit" })+ notifyObservation()+}+export function committedNavigationPathname() { return committedHref?.split("?")[0] }+export function navigationForHref(href: string) {+ return navigation && !navigation.done && navigationHref === normalizedHref(href) ? navigation : undefined+}+const commandActions = new WeakMap<object, Action>()+export function bindCommandAction(value: unknown, action: Action, depth = 0) {+ if (!value || typeof value !== "object" || depth > 3) return+ commandActions.set(value, action)+ const object = value as Record<string, unknown>+ for (const key of ["original", "token", "intent"]) bindCommandAction(object[key], action, depth + 1)+}+export function commandObservation(value: unknown): { action?: Action; reason: "command" } | undefined {+ const action = value && typeof value === "object" ? commandActions.get(value) : undefined+ return action && action.generation === telemetryGeneration() ? { action, reason: "command" } : undefined+}diff --git a/src/web/src/lib/observability/coverage.test.ts b/src/web/src/lib/observability/coverage.test.tsnew file mode 100644index 000000000..d6af4e7d3--- /dev/null+++ b/src/web/src/lib/observability/coverage.test.ts@@ -0,0 +1,29 @@+import { readFileSync, readdirSync } from "node:fs"+import { resolve, relative } from "node:path"+import ts from "typescript"+import { expect, it } from "vitest"+import { actionNames, pageRoutes, mutationCoverage, facadeCoverage } from "./coverage"+import { actionVariants } from "./actions"++const web = resolve(import.meta.dirname, "../../..")+const files = (root: string) => readdirSync(root, { recursive: true }).filter((file): file is string => typeof file === "string" && /\.tsx?$/.test(file)).map(file => resolve(root, file))+it("keeps the route whitelist aligned with both builds and parallel route slots", () => {+ const routes = new Set(["src/app", "blog/src/app"].flatMap(root => files(resolve(web, root)).filter(file => file.endsWith("/page.tsx")).map(file => "/" + relative(resolve(web, root), file).split("/").slice(0, -1).filter(segment => !segment.startsWith("(") && !segment.startsWith("@")).join("/"))))+ expect([...routes].sort()).toEqual([...pageRoutes].sort())+})+it("requires every native mutation owner in the inventory and every semantic variant on the whitelist", () => {+ const inventory = new Set<string>([...mutationCoverage, ...facadeCoverage].map(entry => entry.file))+ for (const file of files(resolve(web, "src"))) {+ if (/\.test\./.test(file) || file.includes("/test/")) continue+ const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true, file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS)+ const visit = (node: ts.Node) => {+ if (ts.isCallExpression(node) && ["useMutation", "useCommunityCommandMutation"].includes(node.expression.getText(source))) {+ expect(inventory.has("src/web/" + relative(web, file)), file).toBe(true)+ expect(node.arguments.map(argument => argument.getText(source)).join(" "), file).toContain("observabilityAction")+ }+ ts.forEachChild(node, visit)+ }+ visit(source)+ }+ for (const variants of Object.values(actionVariants)) for (const name of Object.values(variants)) expect(actionNames as readonly string[]).toContain(name)+})diff --git a/src/web/src/lib/observability/coverage.ts b/src/web/src/lib/observability/coverage.tsnew file mode 100644index 000000000..d7b2d5da2--- /dev/null+++ b/src/web/src/lib/observability/coverage.ts@@ -0,0 +1,957 @@+export const pageRoutes = [+ "/",+ "/blog",+ "/blog/[slug]",+ "/c",+ "/c/channels/[serverId]",+ "/c/channels/[serverId]/[channelId]",+ "/c/channels/[serverId]/settings",+ "/c/invite/[token]",+ "/c/me",+ "/c/me/[dmId]",+ "/c/me/bots",+ "/c/me/friends",+ "/c/me/machines",+ "/c/onboarding-preview",+ "/device",+ "/invite/[token]",+ "/landing-legacy",+ "/onboarding-preview",+ "/pricing",+ "/pricing-concept",+ "/privacy",+ "/sign-in",+ "/studio/new",+ "/templates",+ "/templates/[id]",+ "/w/[slug]",+ "/w/[slug]/agents",+ "/w/[slug]/agents/[id]",+ "/w/[slug]/agents/[id]/activity",+ "/w/[slug]/agents/[id]/chat",+ "/w/[slug]/agents/[id]/chat/[convId]",+ "/w/[slug]/agents/[id]/email",+ "/w/[slug]/agents/[id]/files",+ "/w/[slug]/agents/[id]/meetings",+ "/w/[slug]/agents/new",+ "/w/[slug]/calendar",+ "/w/[slug]/flags",+ "/w/[slug]/help/email-setup",+ "/w/[slug]/home",+ "/w/[slug]/issues",+ "/w/[slug]/runtimes",+ "/w/[slug]/settings",+ "/w/[slug]/traces",+ "/w/[slug]/traces/[traceId]",+ "/w/[slug]/unread",+ "/workspaces"+] as const++export const apiRoutes = [+ "/api/agent-links",+ "/api/agent-links/[id]",+ "/api/agents",+ "/api/agents/[id]",+ "/api/agents/[id]/access",+ "/api/agents/[id]/access/[userId]",+ "/api/agents/[id]/active-tasks",+ "/api/agents/[id]/activity",+ "/api/agents/[id]/chat-init",+ "/api/agents/[id]/conversation",+ "/api/agents/[id]/conversations",+ "/api/agents/[id]/email-accounts",+ "/api/agents/[id]/email-accounts/[accountId]",+ "/api/agents/[id]/email-accounts/[accountId]/sync",+ "/api/agents/[id]/email-accounts/[accountId]/test",+ "/api/agents/[id]/meetings",+ "/api/agents/[id]/meetings/[meetingId]",+ "/api/agents/[id]/meetings/[meetingId]/approve",+ "/api/agents/[id]/meetings/[meetingId]/stop",+ "/api/agents/[id]/pin",+ "/api/agents/[id]/skills",+ "/api/agents/[id]/threads",+ "/api/agents/[id]/whitelist",+ "/api/agents/[id]/whitelist/[whitelistId]",+ "/api/agents/[id]/workspace/browse",+ "/api/agents/active-task-counts",+ "/api/agents/active-tasks",+ "/api/agents/pins",+ "/api/agents/pins/reorder",+ "/api/agents/recruit",+ "/api/agents/sidebar/reorder",+ "/api/artifacts",+ "/api/artifacts/[id]",+ "/api/artifacts/[id]/content",+ "/api/artifacts/[id]/thumbnail",+ "/api/artifacts/upload",+ "/api/auth/[...all]",+ "/api/auth/native/attempt",+ "/api/auth/native/cancel",+ "/api/auth/native/exchange",+ "/api/auth/native/status",+ "/api/calendar",+ "/api/calendar/[id]",+ "/api/channels",+ "/api/channels/[id]",+ "/api/channels/reorder",+ "/api/cli/latest-version",+ "/api/community/analytics/funnel-events",+ "/api/community/billing",+ "/api/community/billing/cancel-change",+ "/api/community/billing/checkout",+ "/api/community/billing/portal",+ "/api/community/bots",+ "/api/community/bots/[id]",+ "/api/community/bots/[id]/active",+ "/api/community/bots/[id]/approval-requests/[requestId]/approve",+ "/api/community/bots/[id]/approval-requests/[requestId]/deny",+ "/api/community/bots/[id]/audit-log",+ "/api/community/bots/[id]/avatar",+ "/api/community/bots/[id]/diagnostics",+ "/api/community/bots/[id]/marks",+ "/api/community/bots/[id]/notifications/channel/[scopeId]",+ "/api/community/bots/[id]/notifications/server/[scopeId]",+ "/api/community/bots/[id]/reset-session",+ "/api/community/bots/me/nap",+ "/api/community/channels",+ "/api/community/channels/[id]",+ "/api/community/channels/[id]/attachments",+ "/api/community/channels/[id]/attachments/[attachmentId]",+ "/api/community/channels/[id]/attachments/[attachmentId]/thumbnail",+ "/api/community/channels/[id]/members",+ "/api/community/channels/[id]/members/[userId]",+ "/api/community/channels/[id]/messages",+ "/api/community/channels/[id]/messages/seq/[seq]",+ "/api/community/channels/[id]/messages/tags",+ "/api/community/channels/[id]/participants",+ "/api/community/channels/[id]/participants/[userId]",+ "/api/community/channels/[id]/pins",+ "/api/community/channels/[id]/pins/[messageId]",+ "/api/community/channels/[id]/read",+ "/api/community/channels/[id]/read-state",+ "/api/community/channels/[id]/threads",+ "/api/community/channels/[id]/upload",+ "/api/community/channels/participants/batch",+ "/api/community/daemon/activate",+ "/api/community/daemon/bots",+ "/api/community/daemon/diagnostics/[reportId]",+ "/api/community/daemon/diagnostics/[reportId]/bundle",+ "/api/community/daemon/enroll-agent",+ "/api/community/daemon/identity",+ "/api/community/daemon/resync-diagnostics",+ "/api/community/daemon/resync-wakes",+ "/api/community/diagnostics/[reportId]",+ "/api/community/friends/[id]",+ "/api/community/friends/[id]/accept",+ "/api/community/friends/[id]/owner-decision",+ "/api/community/friends/[id]/reject",+ "/api/community/friends/accepted",+ "/api/community/friends/blocked",+ "/api/community/friends/pending",+ "/api/community/friends/presence",+ "/api/community/friends/request",+ "/api/community/invites/[token]",+ "/api/community/invites/[token]/info",+ "/api/community/invites/[token]/join",+ "/api/community/machines",+ "/api/community/machines/[id]",+ "/api/community/machines/[id]/reconnect",+ "/api/community/machines/[id]/reset-agents",+ "/api/community/machines/[id]/update",+ "/api/community/machines/pair",+ "/api/community/messages/[id]",+ "/api/community/messages/[id]/marks",+ "/api/community/messages/[id]/properties",+ "/api/community/messages/[id]/reactions",+ "/api/community/messages/[id]/reactions/[emoji]",+ "/api/community/messages/[id]/tags",+ "/api/community/messages/batch",+ "/api/community/messages/search",+ "/api/community/messages/tags/batch",+ "/api/community/notifications/devices",+ "/api/community/notifications/devices/[installationId]",+ "/api/community/servers",+ "/api/community/servers/[id]",+ "/api/community/servers/[id]/bots",+ "/api/community/servers/[id]/categories",+ "/api/community/servers/[id]/categories/[catId]",+ "/api/community/servers/[id]/categories/reorder",+ "/api/community/servers/[id]/channels",+ "/api/community/servers/[id]/channels/admin",+ "/api/community/servers/[id]/channels/reorder",+ "/api/community/servers/[id]/icon",+ "/api/community/servers/[id]/invites",+ "/api/community/servers/[id]/leave",+ "/api/community/servers/[id]/members",+ "/api/community/servers/[id]/members/[memberId]",+ "/api/community/servers/[id]/members/search",+ "/api/community/servers/[id]/onboard",+ "/api/community/servers/[id]/presence",+ "/api/community/servers/[id]/unreads",+ "/api/community/servers/channels",+ "/api/community/share-image/avatar/[userId]",+ "/api/community/users/[userId]/avatar",+ "/api/community/users/[userId]/block",+ "/api/community/users/[userId]/profile",+ "/api/community/users/[userId]/unblock",+ "/api/community/users/me/account-deletion",+ "/api/community/users/me/account-deletion/code",+ "/api/community/users/me/attention",+ "/api/community/users/me/avatar",+ "/api/community/users/me/channel-directory",+ "/api/community/users/me/dms",+ "/api/community/users/me/inbox/ack",+ "/api/community/users/me/inbox/dms/read-all",+ "/api/community/users/me/inbox/mentions/[id]",+ "/api/community/users/me/inbox/mentions/read-all",+ "/api/community/users/me/inbox/pull",+ "/api/community/users/me/inbox/snapshot",+ "/api/community/users/me/inbox/unreads/read-all",+ "/api/community/users/me/marks",+ "/api/community/users/me/notifications",+ "/api/community/users/me/notifications/channel/[id]",+ "/api/community/users/me/notifications/server/[id]",+ "/api/community/users/me/profile",+ "/api/community/users/me/read-state",+ "/api/community/users/me/server-folders",+ "/api/community/users/me/server-folders/[id]",+ "/api/community/users/me/server-folders/reorder",+ "/api/community/users/me/server-rail",+ "/api/community/users/search",+ "/api/config/min-version",+ "/api/config/model-options",+ "/api/conversations",+ "/api/conversations/[id]",+ "/api/conversations/[id]/active-task",+ "/api/conversations/[id]/init",+ "/api/conversations/[id]/messages",+ "/api/conversations/[id]/threads",+ "/api/conversations/check-fresh",+ "/api/daemon/conversations/[id]/messages",+ "/api/daemon/deregister",+ "/api/daemon/heartbeat",+ "/api/daemon/latest-version",+ "/api/daemon/register",+ "/api/daemon/skills/sync",+ "/api/daemon/sweep",+ "/api/daemon/tasks/[taskId]/complete",+ "/api/daemon/tasks/[taskId]/fail",+ "/api/daemon/tasks/[taskId]/messages",+ "/api/daemon/tasks/[taskId]/progress",+ "/api/daemon/tasks/[taskId]/start",+ "/api/daemon/tasks/[taskId]/status",+ "/api/daemon/tasks/[taskId]/supersede",+ "/api/daemon/tasks/poll",+ "/api/daemon/workspace/report",+ "/api/daily-quote",+ "/api/desktop/update/[target]/[arch]/[current_version]",+ "/api/email",+ "/api/email/[id]",+ "/api/email/[id]/attachment/[index]",+ "/api/email/[id]/body",+ "/api/email/[id]/raw",+ "/api/email/[id]/thread",+ "/api/email/[id]/trust",+ "/api/email/notify",+ "/api/email/send",+ "/api/email/upload",+ "/api/flags",+ "/api/flags/[messageId]",+ "/api/flags/count",+ "/api/health",+ "/api/inbox",+ "/api/inbox/count",+ "/api/inbox/read",+ "/api/inbox/read-all",+ "/api/invite/[token]",+ "/api/issues",+ "/api/issues/[id]",+ "/api/issues/[id]/comments",+ "/api/machine-tokens",+ "/api/machine-tokens/[id]",+ "/api/machine-tokens/activate",+ "/api/machine-tokens/status",+ "/api/me",+ "/api/meeting/callback",+ "/api/members/me",+ "/api/pricing",+ "/api/privacy/analytics-consent",+ "/api/runtimes",+ "/api/runtimes/[runtimeId]/rescan",+ "/api/runtimes/[runtimeId]/update",+ "/api/runtimes/machine",+ "/api/stripe/webhook",+ "/api/studios",+ "/api/studios/check-handles",+ "/api/studios/check-name",+ "/api/tasks/[id]",+ "/api/tasks/[id]/messages",+ "/api/tasks/[id]/retry",+ "/api/traces",+ "/api/traces/[traceId]",+ "/api/workspaces",+ "/api/workspaces/[id]",+ "/api/workspaces/[id]/invites",+ "/api/workspaces/[id]/invites/[inviteId]",+ "/api/workspaces/[id]/members",+ "/api/workspaces/[id]/members/[memberId]",+ "/api/workspaces/[id]/onboarded",+ "/api/workspaces/[id]/overview",+ "/api/ws/token"+] as const++export const actionNames = [+ "account.delete",+ "account.deletion.code.request",+ "account.deletion.command",+ "account.sign_out",+ "agent.access.grant",+ "agent.access.revoke",+ "agent.create",+ "agent.instruction.save",+ "agent.link.command",+ "agent.list.reorder",+ "agent.permission.command",+ "agent.pin",+ "agent.pins.reorder",+ "agent.rail.command",+ "agent.task.retry",+ "agent.unpin",+ "agent.update",+ "agent.visibility.change",+ "agent.whitelist.add",+ "agent.whitelist.remove",+ "attachment.download",+ "attachment.prepare",+ "attachment.upload",+ "attachment_preview",+ "auth_dev_sign_in",+ "auth_send_code",+ "auth_social",+ "auth_verify_code",+ "billing.change.cancel",+ "billing.checkout.start",+ "billing.portal.open",+ "billing.redirect",+ "billing_return",+ "bot.active.change",+ "bot.avatar.upload",+ "bot.bug_report.submit",+ "bot.command",+ "bot.create",+ "bot.delete",+ "bot.notification.update",+ "bot.session.reset",+ "bot.update",+ "cache.clear",+ "calendar.command",+ "calendar.event.create",+ "calendar.event.delete",+ "calendar.event.update",+ "category.create",+ "category.delete",+ "category.reorder",+ "category.update",+ "channel.create",+ "channel.delete",+ "channel.member.add",+ "channel.member.leave",+ "member.management.command",+ "channel.member.command",+ "channel.member.remove",+ "channel.members.add",+ "channel.members.remove",+ "channel.message.send",+ "channel.move",+ "channel.rename",+ "channel.reorder",+ "chat.command",+ "chat.control.command",+ "chat.message.send",+ "chat.session.command",+ "chat.session.nap",+ "chat.task.retry",+ "chat.task.stop",+ "chat.thread.create",+ "command.unknown",+ "community.command",+ "community.onboarding.initialize",+ "device.authorization.approve",+ "device.authorization.command",+ "device.authorization.deny",+ "dm.message.send",+ "dm.open",+ "email.account.command",+ "email.account.connect",+ "email.account.delete",+ "email.account.sync",+ "email.send",+ "forum.tags.update",+ "forum.thread.create",+ "forum.thread.delete",+ "inbox.read_all",+ "invitation.copy",+ "invitation.send",+ "issue.command",+ "issue.comment.create",+ "issue.create",+ "issue.delete",+ "issue.update",+ "machine.agents.reset",+ "machine.command",+ "machine.delete",+ "machine.pair.generate",+ "machine.pair.launch",+ "machine.update",+ "meeting.command",+ "meeting.create",+ "meeting.delete",+ "meeting.update",+ "mention.dismiss",+ "message.compose.send",+ "message.edit",+ "message.export",+ "message.flag.remove",+ "message.flag.toggle",+ "message.mark",+ "message.mark.command",+ "message.pin",+ "message.pin.command",+ "message.reaction.add",+ "message.reaction.command",+ "message.reaction.toggle",+ "message.thread.create",+ "message.unmark",+ "message.unpin",+ "message_send",+ "navigation",+ "notification.channel.update",+ "notification.permission.request",+ "notification.server.update",+ "notification.settings.command",+ "profile.avatar.upload",+ "profile.update",+ "router_transition",+ "runtime.command",+ "runtime.rescan",+ "runtime.update",+ "server.create",+ "server.delete",+ "server.icon.upload",+ "server.invite.accept",+ "server.invite.resolve",+ "server.invite.revoke",+ "server.join",+ "server.leave",+ "server.member.command",+ "server.member.kick",+ "server.member.role.change",+ "server.rail.reorder",+ "server.update",+ "studio.agent.create",+ "studio.onboarding.finish",+ "ui_interaction",+ "workspace.channel.command",+ "workspace.channel.create",+ "workspace.channel.delete",+ "workspace.channel.rename",+ "workspace.channel.reorder",+ "workspace.create",+ "workspace.delete",+ "workspace.instruction.save",+ "workspace.invite.accept",+ "workspace.invite.create",+ "workspace.invite.revoke",+ "workspace.member.remove",+ "workspace.members.command",+ "workspace.settings.command",+ "workspace.settings.update"+, "agent.link.create", "agent.link.update", "agent.link.delete", "email.command", "email.read", "email.delete", "email.sender.trust", "chat.message.persist", "chat.inbox.read", "meeting.stop", "meeting.approve"+, "friend.command", "friend.owner_decision.command", "friend.request.send", "friend.request.accept", "friend.request.reject", "friend.remove", "friend.request.cancel", "friend.request.approve", "friend.request.deny", "user.block", "user.unblock"+] as const++export const mutationCoverage = [+ {+ "file": "src/web/src/app/(app)/invite/[token]/page.tsx",+ "owner": "InvitePage",+ "action": "workspace.invite.accept"+ },+ {+ "file": "src/web/src/app/(app)/studio/new/client.tsx",+ "owner": "StudioOnboardingInner",+ "action": "studio.agent.create"+ },+ {+ "file": "src/web/src/app/(app)/studio/new/client.tsx",+ "owner": "StudioOnboardingInner",+ "action": "studio.onboarding.finish"+ },+ {+ "file": "src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx",+ "owner": "ActivityRow",+ "action": "agent.task.retry"+ },+ {+ "file": "src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx",+ "owner": "AgentEmailSurface",+ "action": "email.send"+ },+ {+ "file": "src/web/src/app/(app)/w/[slug]/agents/new/page.tsx",+ "owner": "CreateAgentPage",+ "action": "agent.create"+ },+ {+ "file": "src/web/src/app/(app)/w/[slug]/calendar/page.tsx",+ "owner": "CalendarPage",+ "action": "calendar.command"+ },+ {+ "file": "src/web/src/app/(app)/w/[slug]/home/page.tsx",+ "owner": "AgentCanvas",+ "action": "agent.link.command"+ },+ {+ "file": "src/web/src/app/(app)/w/[slug]/settings/general-tab.tsx",+ "owner": "GeneralTab",+ "action": "workspace.settings.command"+ },+ {+ "file": "src/web/src/app/(app)/w/[slug]/settings/instruction-tab.tsx",+ "owner": "InstructionTab",+ "action": "workspace.instruction.save"+ },+ {+ "file": "src/web/src/app/(app)/w/[slug]/settings/members-tab.tsx",+ "owner": "MembersTab",+ "action": "workspace.members.command"+ },+ {+ "file": "src/web/src/app/(app)/w/[slug]/settings/notification-tab.tsx",+ "owner": "NotificationTab",+ "action": "notification.permission.request"+ },+ {+ "file": "src/web/src/app/(app)/workspaces/client.tsx",+ "owner": "WorkspaceListClient",+ "action": "workspace.create"+ },+ {+ "file": "src/web/src/app/c/invite/[token]/invite-accept-client.tsx",+ "owner": "InviteAcceptInner",+ "action": "server.invite.accept"+ },+ {+ "file": "src/web/src/app/device/page.tsx",+ "owner": "DeviceAuthPageInner",+ "action": "device.authorization.command"+ },+ {+ "file": "src/web/src/components/agent-chat/agent-chat-view.tsx",+ "owner": "AgentChatView",+ "action": "chat.control.command"+ },+ {+ "file": "src/web/src/components/agent-edit-form.tsx",+ "owner": "AgentEditForm",+ "action": "agent.instruction.save"+ },+ {+ "file": "src/web/src/components/community/machines/machine-list.tsx",+ "owner": "MachineList",+ "action": "machine.command"+ },+ {+ "file": "src/web/src/components/community/machines/pair-machine-sheet.tsx",+ "owner": "PairMachineSheet",+ "action": "machine.pair.generate"+ },+ {+ "file": "src/web/src/components/community/machines/pair-machine-sheet.tsx",+ "owner": "PairMachineSheet",+ "action": "machine.pair.launch"+ },+ {+ "file": "src/web/src/components/community/members/add-members-dialog.tsx",+ "owner": "AddMembersDialog",+ "action": "channel.members.add"+ },+ {+ "file": "src/web/src/components/community/members/member-list.tsx",+ "owner": "MemberList",+ "action": "member.management.command"+ },+ {+ "file": "src/web/src/components/community/messages/create-forum-thread.tsx",+ "owner": "CreateForumThread",+ "action": "forum.thread.create"+ },+ {+ "file": "src/web/src/components/community/messages/message-share-dialog.tsx",+ "owner": "MessageShareDialog",+ "action": "message.export"+ },+ {+ "file": "src/web/src/components/community/messages/use-composer-controller.ts",+ "owner": "useComposerController",+ "action": "message.compose.send"+ },+ {+ "file": "src/web/src/components/community/onboarding/community-onboarding-form.tsx",+ "owner": "CommunityOnboardingForm",+ "action": "community.onboarding.initialize"+ },+ {+ "file": "src/web/src/components/community/onboarding/onboarding-machine-dialog.tsx",+ "owner": "OnboardingMachineDialog",+ "action": "machine.pair.generate"+ },+ {+ "file": "src/web/src/components/community/settings/account-deletion-flow.tsx",+ "owner": "AccountDeletionFlow",+ "action": "account.deletion.command"+ },+ {+ "file": "src/web/src/components/community/settings/user-settings.tsx",+ "owner": "AdvancedSettings",+ "action": "cache.clear"+ },+ {+ "file": "src/web/src/components/community/social/invite-dialog.tsx",+ "owner": "InviteDialog",+ "action": "invitation.send"+ },+ {+ "file": "src/web/src/components/community/social/invite-dialog.tsx",+ "owner": "InviteDialog",+ "action": "invitation.copy"+ },+ {+ "file": "src/web/src/components/custom-email-form.tsx",+ "owner": "CustomEmailForm",+ "action": "email.account.command"+ },+ {+ "file": "src/web/src/contexts/agent-context.tsx",+ "owner": "useAgentContext",+ "action": "agent.update"+ },+ {+ "file": "src/web/src/contexts/agent-context.tsx",+ "owner": "useAgentContext",+ "action": "agent.rail.command"+ },+ {+ "file": "src/web/src/contexts/channel-context.tsx",+ "owner": "useChannel",+ "action": "workspace.channel.command"+ },+ {+ "file": "src/web/src/hooks/community/mutations/dm.ts",+ "owner": "useCreateOrGetDm",+ "action": "dm.open"+ },+ {+ "file": "src/web/src/hooks/community/mutations/forum.ts",+ "owner": "useCreateForumThread",+ "action": "forum.thread.create"+ },+ {+ "file": "src/web/src/hooks/community/mutations/forum.ts",+ "owner": "useUpdatePostTags",+ "action": "forum.tags.update"+ },+ {+ "file": "src/web/src/hooks/community/mutations/forum.ts",+ "owner": "useDeleteForumThread",+ "action": "forum.thread.delete"+ },+ {+ "file": "src/web/src/hooks/community/mutations/invites.ts",+ "owner": "useResolveOrCreateInvite",+ "action": "server.invite.resolve"+ },+ {+ "file": "src/web/src/hooks/community/mutations/invites.ts",+ "owner": "useRevokeInvite",+ "action": "server.invite.revoke"+ },+ {+ "file": "src/web/src/hooks/community/mutations/members.ts",+ "owner": "useMemberCommand",+ "action": "server.member.command"+ },+ {+ "file": "src/web/src/hooks/community/mutations/message-memberships.ts",+ "owner": "usePinCommand",+ "action": "message.pin.command"+ },+ {+ "file": "src/web/src/hooks/community/mutations/message-memberships.ts",+ "owner": "useMarkCommand",+ "action": "message.mark.command"+ },+ {+ "file": "src/web/src/hooks/community/mutations/message-reactions.ts",+ "owner": "useReactionIntent",+ "action": "message.reaction.command"+ },+ {+ "file": "src/web/src/hooks/community/mutations/messages.ts",+ "owner": "useEditMessage",+ "action": "message.edit"+ },+ {+ "file": "src/web/src/hooks/community/mutations/messages.ts",+ "owner": "useSendMessage",+ "action": "channel.message.send"+ },+ {+ "file": "src/web/src/hooks/community/mutations/messages.ts",+ "owner": "useSendDmMessage",+ "action": "dm.message.send"+ },+ {+ "file": "src/web/src/hooks/community/mutations/messages.ts",+ "owner": "useCreateThread",+ "action": "message.thread.create"+ },+ {+ "file": "src/web/src/hooks/community/mutations/messages.ts",+ "owner": "useMarkAllInboxRead",+ "action": "inbox.read_all"+ },+ {+ "file": "src/web/src/hooks/community/mutations/messages.ts",+ "owner": "useDeleteMention",+ "action": "mention.dismiss"+ },+ {+ "file": "src/web/src/hooks/community/mutations/notifications.ts",+ "owner": "useNotificationCommand",+ "action": "notification.settings.command"+ },+ {+ "file": "src/web/src/hooks/community/mutations/profile.ts",+ "owner": "useUpdateProfile",+ "action": "profile.update"+ },+ {+ "file": "src/web/src/hooks/community/mutations/profile.ts",+ "owner": "useUploadUserAvatar",+ "action": "profile.avatar.upload"+ },+ {+ "file": "src/web/src/hooks/community/mutations/uploads.ts",+ "owner": "useUploadFile",+ "action": "attachment.upload"+ },+ {+ "file": "src/web/src/hooks/community/use-account-sign-out.ts",+ "owner": "useAccountSignOut",+ "action": "account.sign_out"+ },+ {+ "file": "src/web/src/hooks/community/use-billing.ts",+ "owner": "useBilling",+ "action": "billing.redirect"+ },+ {+ "file": "src/web/src/hooks/community/use-billing.ts",+ "owner": "useBilling",+ "action": "billing.change.cancel"+ },+ {+ "file": "src/web/src/hooks/community/use-bot-bug-report.ts",+ "owner": "useBotBugReport",+ "action": "bot.bug_report.submit"+ },+ {+ "file": "src/web/src/hooks/community/use-bots.ts",+ "owner": "useBotCommand",+ "action": "bot.command"+ },+ {+ "file": "src/web/src/hooks/community/use-channel-members.ts",+ "owner": "useChannelMemberCommand",+ "action": "channel.member.command"+ },+ {+ "file": "src/web/src/hooks/community/use-community-command-mutation.ts",+ "owner": "useCommunityCommandMutation",+ "action": "community.command"+ },+ {+ "file": "src/web/src/hooks/community/use-notification-settings.ts",+ "owner": "useSetBotNotificationSetting",+ "action": "bot.notification.update"+ },+ {+ "file": "src/web/src/hooks/use-agent-chat.ts",+ "owner": "useAgentChat",+ "action": "chat.command"+ },+ {+ "file": "src/web/src/hooks/use-agent-chat.ts",+ "owner": "useAgentChat",+ "action": "chat.message.send"+ },+ {+ "file": "src/web/src/hooks/use-agent-chat.ts",+ "owner": "useAgentChat",+ "action": "chat.session.command"+ },+ {+ "file": "src/web/src/hooks/use-application-sign-out.ts",+ "owner": "useApplicationSignOut",+ "action": "account.sign_out"+ },+ {+ "file": "src/web/src/hooks/use-file-attachments.ts",+ "owner": "useFileAttachments",+ "action": "attachment.prepare"+ },+ {+ "file": "src/web/src/hooks/use-message-flags.ts",+ "owner": "useMessageFlags",+ "action": "message.flag.toggle"+ },+ {+ "file": "src/web/src/hooks/workspace/use-agent-permission-command.ts",+ "owner": "useAgentPermissionCommand",+ "action": "agent.permission.command"+ },+ {+ "file": "src/web/src/hooks/workspace/use-inbox.ts",+ "owner": "useMarkAllInboxRead",+ "action": "inbox.read_all"+ },+ {+ "file": "src/web/src/hooks/workspace/use-inbox.ts",+ "owner": "useUnflagWorkspaceMessage",+ "action": "message.flag.remove"+ },+ {+ "file": "src/web/src/hooks/workspace/use-issue-command.ts",+ "owner": "useIssueCommand",+ "action": "issue.command"+ },+ {+ "file": "src/web/src/hooks/workspace/use-runtime-command.ts",+ "owner": "useRuntimeCommand",+ "action": "runtime.command"+ },+ {+ "file": "src/web/src/hooks/workspace/use-workspace-meetings.ts",+ "owner": "useWorkspaceMeetings",+ "action": "meeting.command"+ }+] as const++export const facadeCoverage = [+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useCreateChannel",+ "action": "channel.create"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useRenameChannel",+ "action": "channel.rename"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useMoveChannel",+ "action": "channel.move"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useDeleteChannel",+ "action": "channel.delete"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useCreateCategory",+ "action": "category.create"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useUpdateCategory",+ "action": "category.update"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useDeleteCategory",+ "action": "category.delete"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useReorderCategories",+ "action": "category.reorder"+ },+ {+ "file": "src/web/src/hooks/community/mutations/channels.ts",+ "owner": "useReorderChannels",+ "action": "channel.reorder"+ },+ {+ "file": "src/web/src/hooks/community/mutations/friends.ts",+ "owner": "useFriendCommand",+ "action": "friend.command"+ },+ {+ "file": "src/web/src/hooks/community/mutations/server-rail.ts",+ "owner": "useServerRailCommit",+ "action": "server.rail.reorder"+ },+ {+ "file": "src/web/src/hooks/community/mutations/servers.ts",+ "owner": "useCreateServer",+ "action": "server.create"+ },+ {+ "file": "src/web/src/hooks/community/mutations/servers.ts",+ "owner": "useJoinServer",+ "action": "server.join"+ },+ {+ "file": "src/web/src/hooks/community/mutations/servers.ts",+ "owner": "useLeaveServer",+ "action": "server.leave"+ },+ {+ "file": "src/web/src/hooks/community/mutations/servers.ts",+ "owner": "useDeleteServer",+ "action": "server.delete"+ },+ {+ "file": "src/web/src/hooks/community/mutations/servers.ts",+ "owner": "useUpdateServer",+ "action": "server.update"+ },+ {+ "file": "src/web/src/hooks/community/mutations/servers.ts",+ "owner": "useUploadServerIcon",+ "action": "server.icon.upload"+ }+] as const++export const capabilityLimits = {+ auth_worker: "separate status HTML has no consent-aware client bundle",+ external_oauth: "in-app handoff and return only",+ stripe: "in-app handoff and qualified billing return only",+ native_os: "platform timing and lifecycle require independent verification",+ rsc_cache: "public router intent; cache hit unknown without public evidence",+ backend_trace: "cf-ray correlation; same-trace backend unverified",+ ssr_source: "server-rendered source unknown unless an explicit owner supplies evidence",+} as const++const routeMatchers = [...pageRoutes, ...apiRoutes].sort((a,b) => b.split("/").length-a.split("/").length || b.split("/").filter(part => !part.startsWith("[")).length-a.split("/").filter(part => !part.startsWith("[")).length || a.localeCompare(b)).map(template => ({template, pattern:new RegExp("^" + template.split("/").map(part => part.startsWith("[...") ? ".+" : part.startsWith("[") ? "[^/]+" : part.replace(/[.*+?^$(){}|\\]/g, "\\$&")).join("/") + "/?$")}))+export function routeTemplate(input: string, origin = "https://alook.ai"): string {+ try {+ const url = new URL(input, origin)+ if (url.origin !== new URL(origin).origin) return "/external"+ if (url.pathname.startsWith("/_next/")) return "/_next/resource"+ return routeMatchers.find(({pattern}) => pattern.test(url.pathname))?.template ?? "/unmapped"+ } catch { return "/unmapped" }+}diff --git a/src/web/src/lib/observability/data-source.test.ts b/src/web/src/lib/observability/data-source.test.tsnew file mode 100644index 000000000..b1adf3948--- /dev/null+++ b/src/web/src/lib/observability/data-source.test.ts@@ -0,0 +1,72 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest"+import { QueryClient } from "@tanstack/react-query"+import { collectionEvidence, recordRows, disposeSources, tagView, viewEvidence, mergeEvidence, observedValueSource, withSource, sourceEvidence } from "./data-source"+import { configureTelemetry, retireTelemetry } from "./telemetry"++describe("actual row and window provenance", () => {+ let client: QueryClient+ beforeEach(() => { client = new QueryClient(); configureTelemetry({}, true) })+ afterEach(() => { retireTelemetry(); disposeSources(client); client.clear() })+ it("preserves unchanged IDB versions through validation, replaces changed fields conservatively", () => {+ const cached = [{ id: "one", content: "private", reaction: 0 }, { id: "two", content: "private", reaction: 0 }]+ recordRows(client, "messages", cached, row => row.id, "restored_idb")+ const initial = collectionEvidence(client, "messages", ["one"])+ expect(initial.source).toBe("restored_idb")+ recordRows(client, "messages", cached.map(row => ({ ...row })), row => row.id, "network")+ const validated = collectionEvidence(client, "messages", ["one"])+ expect(validated.version).toBe(initial.version)+ expect(validated.source).toBe("restored_idb")+ expect(validated.freshness).toBe("validated")+ recordRows(client, "messages", [{ ...cached[0]!, reaction: 1 }, cached[1]!], row => row.id, "ws")+ expect(collectionEvidence(client, "messages", ["one"]).source).toBe("mixed")+ expect(collectionEvidence(client, "messages", ["two"]).source).toBe("restored_idb")+ expect(collectionEvidence(client, "messages", ["one"]).version).not.toBe(initial.version)+ })+ it("marks an untracked optimistic row unknown, never reuses IDB labels on it", () => {+ const row = { id: "one", content: "original" }+ recordRows(client, "messages", [row], item => item.id, "restored_idb")+ expect(collectionEvidence(client, "messages", ["one"], [{ ...row, content: "edited" }]).source).toBe("unknown")+ })+ it("gives local preference snapshots stable versions while retaining unknown provenance", () => {+ const one = {}, two = {}+ const first = sourceEvidence(one, "unknown")+ expect(first.version).not.toBe("unknown")+ expect(sourceEvidence(one, "unknown")).toEqual(first)+ expect(sourceEvidence(two, "unknown")).toMatchObject({ source: "unknown" })+ expect(sourceEvidence(two, "unknown").version).not.toBe(first.version)+ })+ it("binds snapshots to rendered values; later writes cannot mutate an old snapshot", () => {+ recordRows(client, "messages", [{ id: "one", content: "old" }], item => item.id, "restored_idb")+ const view = tagView({}, collectionEvidence(client, "messages", ["one"]))+ recordRows(client, "messages", [{ id: "one", content: "new" }], item => item.id, "network")+ expect(viewEvidence(view).source).toBe("restored_idb")+ expect(viewEvidence(view).version).not.toBe(collectionEvidence(client, "messages", ["one"]).version)+ })+ it("carries the original WS apply receipt into the actual rendered row and expires it on retirement", () => {+ const row = { id: "one", content: "changed" }+ withSource(client, "ws", () => recordRows(client, "messages", [row], item => item.id), { id: "event-a", start: 10 })+ const rendered = tagView({}, collectionEvidence(client, "messages", ["one"], [row]))+ expect(viewEvidence(rendered)).toMatchObject({ wsEventId: "event-a", wsStart: 10, source: "ws" })+ retireTelemetry(); configureTelemetry({}, true)+ expect(viewEvidence(rendered).wsEventId).toBeUndefined()+ })+ it("handles authoritative empty, deletion, owner retirement and mixed joins", () => {+ recordRows(client, "messages", [], (row: {id:string}) => row.id, "network")+ expect(collectionEvidence(client, "messages", []).source).toBe("network")+ recordRows(client, "profiles", [{ id: "one" }], row => row.id, "restored_idb")+ const joined = mergeEvidence([collectionEvidence(client,"profiles",["one"]), collectionEvidence(client,"messages",[])])+ expect(joined.source).toBe("mixed")+ recordRows(client, "profiles", [], (row: {id:string})=>row.id,"ws")+ expect(collectionEvidence(client,"profiles",["one"]).source).toBe("unknown")+ disposeSources(client)+ expect(collectionEvidence(client,"profiles",[]).source).toBe("unknown")+ })+ it("classifies a composed response by its actual child view evidence", () => {+ const cached = tagView([], sourceEvidence({}, "restored_idb"))+ const live = tagView({}, sourceEvidence({}, "network"))+ expect(observedValueSource({ cached })).toBe("restored_idb")+ expect(observedValueSource({ cached, live })).toBe("mixed")+ expect(observedValueSource({ cached, untracked: {} })).toBe("mixed")+ })++})diff --git a/src/web/src/lib/observability/data-source.ts b/src/web/src/lib/observability/data-source.tsnew file mode 100644index 000000000..febfa731b--- /dev/null+++ b/src/web/src/lib/observability/data-source.ts@@ -0,0 +1,143 @@+import { replaceEqualDeep, type QueryClient } from "@tanstack/react-query"+import { emitTelemetry, isTelemetryEligible, telemetryGeneration } from "./telemetry"+import type { Source } from "./schema"++export type Evidence = { source: Source; version: string; freshness: "restored" | "validated" | "changed" | "unknown"; count: number; wsEventId?: string; wsStart?: number }+type RowEvidence = Evidence & { value: object; fields: Map<string, Source> }+type Diagnostics = { generation: number; revision: number; collections: Map<string, Map<string, RowEvidence>>; empty: Map<string, Evidence>; scope?: Source; origin?: { id: string; start: number }; values: WeakMap<object, Evidence> }+const owners = new WeakMap<QueryClient, Diagnostics>()+const views = new WeakMap<object, { generation: number; evidence: Evidence }>()+let viewRevision = 0+const unknown = (count = 0): Evidence => ({ source: "unknown", version: "unknown", freshness: "unknown", count })+function owner(client: QueryClient) {+ let state = owners.get(client)+ if (!state || state.generation !== telemetryGeneration()) {+ state = { generation: telemetryGeneration(), revision: 0, collections: new Map(), empty: new Map(), values: new WeakMap() }+ owners.set(client, state)+ }+ return state+}+function plain(row: object): Record<string, unknown> { return Object.fromEntries(Object.entries(row).filter(([key]) => !key.startsWith("$"))) }+export function mergeEvidence(evidence: readonly Evidence[]): Evidence {+ if (!evidence.length) return unknown()+ const sources = new Set(evidence.map(item => item.source))+ const ws = evidence.filter(item => item.wsStart !== undefined).sort((a,b) => b.wsStart! - a.wsStart!)[0]+ return {+ ...(ws ? { wsEventId: ws.wsEventId, wsStart: ws.wsStart } : {}),+ source: sources.size === 1 ? evidence[0]!.source : "mixed",+ version: evidenceVersion(evidence),+ freshness: evidence.some(item => item.freshness === "unknown") ? "unknown" : evidence.every(item => item.freshness === "restored") ? "restored" : evidence.every(item => item.freshness === "validated") ? "validated" : "changed",+ count: evidence.reduce((sum,item) => sum + item.count, 0),+ }+}+function evidenceVersion(evidence: readonly Evidence[]) {+ let hash = 2166136261+ for (const item of evidence) for (const character of item.version + ":" + item.source + ":" + item.count + ";") hash = Math.imul(hash ^ character.charCodeAt(0), 16777619) >>> 0+ return String(evidence.length) + "_" + String(hash)+}+export function withSource<T>(client: QueryClient, source: Source, effect: () => T, origin?: { id: string; start: number }): T {+ if (!isTelemetryEligible()) return effect()+ const state = owner(client), previous = state.scope, previousOrigin = state.origin+ state.scope = source+ state.origin = origin ?? (source === previous ? previousOrigin : undefined)+ try { return effect() } finally { state.scope = previous; state.origin = previousOrigin }+}+export function currentSource(client: QueryClient): Source { return owners.get(client)?.scope ?? "unknown" }+export function recordRows<T extends object>(client: QueryClient, collection: string, rows: readonly T[], getKey: (row: T) => string, source = currentSource(client)) {+ if (!isTelemetryEligible()) return+ const state = owner(client)+ const previous = state.collections.get(collection) ?? new Map<string, RowEvidence>()+ const next = new Map<string, RowEvidence>()+ let changed = 0+ for (const row of rows) {+ const key = getKey(row), old = previous.get(key)+ const value = plain(row)+ if (old && !(source === "restored_idb" && old.source === "unknown")) {+ const prior = plain(old.value)+ if (replaceEqualDeep(prior, value) === prior) {+ const evidence = { ...old, value: row, freshness: source === "network" ? "validated" as const : old.freshness }+ next.set(key, evidence)+ state.values.set(row, evidence)+ continue+ }+ }+ const fields = new Map<string, Source>()+ const prior = old ? plain(old.value) : {}+ for (const field of Object.keys(value)) fields.set(field, old && replaceEqualDeep(prior[field], value[field]) === prior[field] ? old.fields.get(field) ?? "unknown" : source)+ const sources = new Set(fields.values())+ const ws = source === "ws" && state.origin ? { wsEventId: state.origin.id, wsStart: state.origin.start } : sources.has("ws") && old?.wsEventId ? { wsEventId: old.wsEventId, wsStart: old.wsStart } : {}+ const evidence: RowEvidence = { ...ws, value: row, fields, source: sources.size === 1 ? [...sources][0]! : "mixed", version: String(++state.revision), freshness: source === "restored_idb" ? "restored" : "changed", count: 1 }+ next.set(key, evidence)+ state.values.set(row, evidence)+ changed+++ }+ const removed = [...previous.keys()].filter(key => !next.has(key)).length+ state.collections.set(collection, next)+ const oldEmpty = state.empty.get(collection)+ const emptyChanged = !rows.length && (!oldEmpty || oldEmpty.source !== source || previous.size > 0)+ if (emptyChanged) state.empty.set(collection, { ...(source === "ws" && state.origin ? { wsEventId: state.origin.id, wsStart: state.origin.start } : {}), source, version: String(++state.revision), freshness: source === "restored_idb" ? "restored" : "changed", count: 0 })+ else if (rows.length) state.empty.delete(collection)+ if (changed || removed || emptyChanged) emitTelemetry("data.publish", { ws_event_id: state.origin?.id, source, data_version: String(state.revision), changed_count: changed, removed_count: removed, row_count: rows.length, eligibility: "eligible", freshness: source === "restored_idb" ? "restored" : "changed" })+}+export function collectionEvidence(client: QueryClient, collection: string, keys: readonly string[], actual?: readonly object[]): Evidence {+ if (!isTelemetryEligible()) return unknown()+ const state = owner(client), map = state.collections.get(collection)+ if (!keys.length) return state.empty.get(collection) ?? unknown()+ const evidence = keys.map((key,index) => {+ const item = map?.get(key)+ if (!item) return unknown(1)+ if (actual?.[index]) {+ const prior = plain(item.value)+ if (replaceEqualDeep(prior, plain(actual[index]!)) !== prior) return unknown(1)+ }+ return item+ })+ return mergeEvidence(evidence)+}+export function tagValue(client: QueryClient, value: unknown, source: Source, previous?: unknown) {+ if (!isTelemetryEligible() || !value || typeof value !== "object") return+ const state = owner(client), existing = state.values.get(value)+ if (existing && !(source === "restored_idb" && existing.source === "unknown")) { if (source === "network") state.values.set(value, { ...existing, freshness: "validated" }); return }+ const prior = previous && typeof previous === "object" ? state.values.get(previous) : undefined+ state.values.set(value, { ...(source === "ws" && state.origin ? { wsEventId: state.origin.id, wsStart: state.origin.start } : {}), source: prior && prior.source !== source ? "mixed" : source, version: String(++state.revision), freshness: source === "restored_idb" ? "restored" : "changed", count: Array.isArray(value) ? value.length : 1 })+}+export function valueEvidence(client: QueryClient, value: unknown): Evidence { return value && typeof value === "object" ? owner(client).values.get(value) ?? viewEvidence(value) : unknown() }+export function tagView<T extends object>(value: T, evidence: Evidence): T { if (isTelemetryEligible()) views.set(value, { generation: telemetryGeneration(), evidence }); return value }+export function viewEvidence(value: unknown): Evidence {+ if (!value || typeof value !== "object") return unknown()+ const entry = views.get(value)+ return isTelemetryEligible() && entry?.generation === telemetryGeneration() ? entry.evidence : unknown(Array.isArray(value) ? value.length : 1)+}+export function sourceEvidence(value: object, source: Source): Evidence {+ const current = viewEvidence(value)+ if (current.source === source && current.version !== "unknown") return current+ const evidence: Evidence = { source, version: "v_" + String(++viewRevision), freshness: source === "restored_idb" ? "restored" : "changed", count: Array.isArray(value) ? value.length : 1 }+ tagView(value, evidence)+ return evidence+}+export function deriveView<T extends object>(value: T, inputs: readonly Evidence[], count = Array.isArray(value) ? value.length : 1): T {+ return tagView(value, { ...mergeEvidence(inputs), count })+}+export function forgetCollection(client: QueryClient, collection: string) { const state = owners.get(client); state?.collections.delete(collection); state?.empty.delete(collection) }+export function disposeSources(client: QueryClient) { owners.delete(client) }++export function tagNetworkResponse(value: unknown) {+ if (!isTelemetryEligible()) return+ const seen = new WeakSet<object>()+ let budget = 4096+ const visit = (input: unknown, depth: number) => {+ if (!input || typeof input !== "object" || seen.has(input) || depth > 8 || budget-- < 1) return+ seen.add(input)+ sourceEvidence(input, "network")+ for (const child of Object.values(input)) visit(child, depth + 1)+ }+ visit(value, 0)+}+export function observedValueSource(value: unknown): Source {+ const direct = viewEvidence(value)+ if (direct.source !== "unknown") return direct.source+ if (!value || typeof value !== "object") return "unknown"+ const children = Object.values(value).slice(0, 256).filter(child => child && typeof child === "object")+ if (!children.length) return "unknown"+ return mergeEvidence(children.map(viewEvidence)).source+}diff --git a/src/web/src/lib/observability/messages.ts b/src/web/src/lib/observability/messages.tsnew file mode 100644index 000000000..b875e92ba--- /dev/null+++ b/src/web/src/lib/observability/messages.ts@@ -0,0 +1,32 @@+import { actionAttributes, finishAction, startAction, type Action } from "./context"+import { emitTelemetry, telemetryGeneration } from "./telemetry"+import type { Attributes } from "./schema"++const owners = new WeakMap<object, Map<string, Action>>()+export function beginMessageObservation(owner: object | undefined, nonce: string, kind: "channel" | "dm") {+ if (!owner) return+ let entries = owners.get(owner)+ if (!entries) { entries = new Map(); owners.set(owner, entries) }+ const previous = entries.get(nonce)+ if (previous && !previous.done && previous.generation === telemetryGeneration()) return previous+ const action = startAction(kind === "dm" ? "dm.message.send" : "channel.message.send")+ if (action) {+ entries.set(nonce, action)+ if (entries.size > 256) entries.delete(entries.keys().next().value!)+ }+ return action+}+export function messageObservation(owner: object | undefined, nonce: unknown): Action | undefined {+ const action = owner && typeof nonce === "string" ? owners.get(owner)?.get(nonce) : undefined+ return action?.generation === telemetryGeneration() ? action : undefined+}+export function messageMilestone(owner: object | undefined, nonce: string, phase: Attributes["phase"], outcome: Attributes["outcome"], terminal = false) {+ const action = messageObservation(owner, nonce)+ if (!action) return+ emitTelemetry("message.milestone", { ...actionAttributes(action), phase, outcome, duration_ms: performance.now() - action.start, source: phase === "optimistic" ? "local_mutation" : "unknown" })+ if (terminal) finishAction(action, outcome, { phase })+}+export function disposeMessageObservations(owner: object) {+ for (const action of owners.get(owner)?.values() ?? []) finishAction(action, "cancelled")+ owners.delete(owner)+}diff --git a/src/web/src/lib/observability/navigation-history-consent.dom.test.tsx b/src/web/src/lib/observability/navigation-history-consent.dom.test.tsxnew file mode 100644index 000000000..2b803c519--- /dev/null+++ b/src/web/src/lib/observability/navigation-history-consent.dom.test.tsx@@ -0,0 +1,119 @@+import { useLayoutEffect } from "react"+import { usePathname } from "next/navigation"+import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"+import { afterEach, expect, it, vi } from "vitest"+import { act, render } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"+import { useObservedQueryRegion } from "./query-regions"+import type { Action } from "./context"++const router = vi.hoisted(() => ({ pathname: "/" }))+const native = vi.hoisted(() => ({ release: undefined as (() => void) | undefined }))+vi.mock("@grafana/faro-web-sdk", async importOriginal => {+ const real = await importOriginal<typeof import("@grafana/faro-web-sdk")>()+ await new Promise<void>(resolve => { native.release = resolve })+ return real+})+vi.mock("next/navigation", () => ({ usePathname: () => router.pathname, useSearchParams: () => new URLSearchParams() }))+let view: ReturnType<typeof render> | undefined+let client: QueryClient | undefined+afterEach(async () => {+ await act(async () => { view?.unmount(); document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied"); client?.clear(); await vi.advanceTimersByTimeAsync(0) })+ window.history.replaceState(null, "", "/")+ vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.unstubAllGlobals()+})++it("retains real renderer ownership through late grant and revoke/regrant without collecting denied work", async () => {+ vi.useFakeTimers(); sessionStorage.clear()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ let now = 240+ vi.spyOn(performance, "now").mockImplementation(() => now)+ vi.spyOn(performance, "getEntriesByType").mockReturnValue([])+ const sent: unknown[] = []+ vi.stubGlobal("fetch", vi.fn(async (url: unknown, options?: RequestInit) => {+ if (String(url) === "https://collector.example/collect/public" && options?.body) sent.push(JSON.parse(String(options.body)))+ return new Response(null, { status: 204 })+ }))+ document.cookie = "alook_analytics_consent=v1.denied; path=/"+ const text = "/c/channels/server-a/text-a", forum = "/c/channels/server-a/forum-a"+ window.history.replaceState(null, "", text)+ window.history.pushState(null, "", forum)+ router.pathname = forum+ const { bootstrapObservability, setTelemetryUser, onObservedRouterTransition } = await import("./client")+ const { commitNavigation, navigationForHref } = await import("./context")+ client = new QueryClient()+ client.setQueryData([forum], [{ id: "post-a" }]); client.setQueryData([text], [])+ function Content() {+ const pathname = usePathname()+ const query = useQuery({ queryKey: [pathname], queryFn: async () => [], staleTime: Infinity })+ useObservedQueryRegion(pathname === forum ? "forum" : "messages", query, query.data?.length)+ return <p>{pathname === forum ? "forum" : "empty text"}</p>+ }+ function Root() {+ const pathname = usePathname()+ useLayoutEffect(() => setTelemetryUser("account-a"), [])+ useLayoutEffect(() => commitNavigation(pathname), [pathname])+ return <QueryClientProvider client={client!}><Content /></QueryClientProvider>+ }+ await act(async () => { bootstrapObservability("web"); view = render(<Root />); await vi.advanceTimersByTimeAsync(3000) })+ expect(sent).toEqual([])+ const originals: Action[] = [], prematurelyDone: boolean[] = []+ for (const [index, grant] of ["late", "regrant"].entries()) {+ if (grant === "regrant") {+ let forward: Action | undefined+ await act(async () => {+ window.history.pushState(null, "", forum); onObservedRouterTransition(forum)+ forward = navigationForHref(forum)+ router.pathname = forum; view!.rerender(<Root />); await vi.advanceTimersByTimeAsync(0)+ })+ expect(forward!.done).toBe(true)+ await act(async () => { await vi.advanceTimersByTimeAsync(3000) })+ await act(async () => {+ document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied"); await vi.advanceTimersByTimeAsync(3000)+ })+ const deniedCount = sent.length+ await act(async () => { view!.rerender(<Root />); await vi.advanceTimersByTimeAsync(3000) })+ expect(sent).toHaveLength(deniedCount)+ }+ const beforeGrantCount = sent.length+ await act(async () => { document.cookie = "alook_analytics_consent=v1.granted; path=/"; announceAnalyticsConsent("granted") })+ await vi.waitFor(() => expect(native.release).toBeTypeOf("function"))+ await act(async () => { native.release?.(); await vi.advanceTimersByTimeAsync(3000) })+ await vi.waitFor(() => expect(sent.length).toBeGreaterThan(beforeGrantCount))+ let original: Action | undefined+ window.addEventListener("popstate", () => { original = navigationForHref(window.location.href) }, { once: true })+ now = 1500 + index * 1000+ await act(async () => { window.history.back(); await vi.advanceTimersByTimeAsync(5) })+ expect(window.location.pathname).toBe(text)+ expect(view!.container.textContent).toBe("forum")+ expect(original).toBeDefined()+ originals.push(original!); prematurelyDone.push(original!.done)+ now += 7+ await act(async () => { onObservedRouterTransition(text) })+ now += 53+ await act(async () => { router.pathname = text; view!.rerender(<Root />); await vi.advanceTimersByTimeAsync(3000) })+ expect(view!.container.textContent).toBe("empty text")+ expect(original!.outcome).toBe("success")+ }+ expect(prematurelyDone).toEqual([false, false])+ await act(async () => { await vi.advanceTimersByTimeAsync(3000) })+ const spans: Record<string, unknown>[] = []+ const events: Array<{ name: string; attributes: Record<string, string> }> = []+ const visit = (value: unknown) => {+ if (!value || typeof value !== "object") return+ const record = value as Record<string, unknown>+ if (typeof record.spanId === "string") spans.push(record)+ if (Array.isArray(record.events)) events.push(...record.events as typeof events)+ for (const child of Object.values(record)) visit(child)+ }+ visit(sent)+ expect(events.filter(event => event.name === "navigation.ready")).toHaveLength(3)+ expect(events.some(event => event.attributes.navigation_kind === "document")).toBe(false)+ for (const original of originals) {+ const parent = original.span!.spanContext()+ const ready = events.filter(event => event.name === "navigation.ready" && event.attributes.action_id === original.id)+ expect(ready).toHaveLength(1)+ expect(ready[0]?.attributes).toMatchObject({ region: "messages", duration_ms: "60", trace_id: parent.traceId, span_id: parent.spanId })+ expect(spans.filter(span => span.spanId === parent.spanId)).toHaveLength(1)+ }+})diff --git a/src/web/src/lib/observability/navigation-history.dom.test.tsx b/src/web/src/lib/observability/navigation-history.dom.test.tsxnew file mode 100644index 000000000..dc9c04f00--- /dev/null+++ b/src/web/src/lib/observability/navigation-history.dom.test.tsx@@ -0,0 +1,100 @@+import { useLayoutEffect } from "react"+import { usePathname } from "next/navigation"+import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"+import { afterEach, expect, it, vi } from "vitest"+import { act, render } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"+import { useObservedQueryRegion } from "./query-regions"+import type { Action } from "./context"++const router = vi.hoisted(() => ({ pathname: "/" }))+const native = vi.hoisted(() => ({ release: undefined as (() => void) | undefined }))+vi.mock("@grafana/faro-web-sdk", async importOriginal => {+ const real = await importOriginal<typeof import("@grafana/faro-web-sdk")>()+ await new Promise<void>(resolve => { native.release = resolve })+ return real+})+vi.mock("next/navigation", () => ({ usePathname: () => router.pathname, useSearchParams: () => new URLSearchParams() }))+let view: ReturnType<typeof render> | undefined+let client: QueryClient | undefined+afterEach(async () => {+ await act(async () => { view?.unmount(); document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied"); client?.clear(); await vi.advanceTimersByTimeAsync(0) })+ window.history.replaceState(null, "", "/")+ vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.unstubAllGlobals()+})++it("keeps one original Back span until the text frame commits, ignoring the outgoing ready forum", async () => {+ vi.useFakeTimers(); sessionStorage.clear()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ let now = 240+ vi.spyOn(performance, "now").mockImplementation(() => now)+ vi.spyOn(performance, "getEntriesByType").mockReturnValue([])+ const sent: unknown[] = []+ vi.stubGlobal("fetch", vi.fn(async (url: unknown, options?: RequestInit) => {+ if (String(url) === "https://collector.example/collect/public" && options?.body) sent.push(JSON.parse(String(options.body)))+ return new Response(null, { status: 204 })+ }))+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ const text = "/c/channels/server-a/text-a", forum = "/c/channels/server-a/forum-a"+ const textHref = text + "?q=hello%20there"+ window.history.replaceState(null, "", textHref)+ window.history.pushState(null, "", forum)+ router.pathname = forum+ const { bootstrapObservability, setTelemetryUser, onObservedRouterTransition } = await import("./client")+ const { commitNavigation, navigationForHref } = await import("./context")+ client = new QueryClient()+ client.setQueryData([forum], [{ id: "post-a" }]); client.setQueryData([text], [])+ function Content() {+ const pathname = usePathname()+ const query = useQuery({ queryKey: [pathname], queryFn: async () => [], staleTime: Infinity })+ useObservedQueryRegion(pathname === forum ? "forum" : "messages", query, query.data?.length)+ return <p>{pathname === forum ? "forum" : "empty text"}</p>+ }+ function Root() {+ const pathname = usePathname()+ useLayoutEffect(() => setTelemetryUser("account-a"), [])+ useLayoutEffect(() => commitNavigation(pathname), [pathname])+ return <QueryClientProvider client={client!}><Content /></QueryClientProvider>+ }+ await act(async () => { bootstrapObservability("web"); view = render(<Root />) })+ await vi.waitFor(() => expect(native.release).toBeTypeOf("function"))+ await act(async () => { native.release?.(); await vi.advanceTimersByTimeAsync(3000) })+ let original: Action | undefined+ window.addEventListener("popstate", () => { original = navigationForHref(window.location.href) }, { once: true })+ now = 1500+ await act(async () => { window.history.back(); await vi.advanceTimersByTimeAsync(5) })+ expect(window.location.pathname).toBe(text)+ expect(view!.container.textContent).toBe("forum")+ expect(original).toBeDefined()+ expect(original!.done).toBe(false)+ const parent = original!.span!.spanContext()+ now = 1507+ await act(async () => { onObservedRouterTransition(textHref) })+ expect(navigationForHref(textHref)).toBe(original)+ now = 1560+ await act(async () => { router.pathname = text; view!.rerender(<Root />); await vi.advanceTimersByTimeAsync(0) })+ expect(view!.container.textContent).toBe("empty text")+ expect(original!.done).toBe(true)+ await act(async () => { view!.rerender(<Root />); await vi.advanceTimersByTimeAsync(3000) })+ const spans: Record<string, unknown>[] = []+ const events: Array<{ name: string; attributes: Record<string, string> }> = []+ const visit = (value: unknown) => {+ if (!value || typeof value !== "object") return+ const record = value as Record<string, unknown>+ if (typeof record.spanId === "string") spans.push(record)+ if (Array.isArray(record.events)) events.push(...record.events as typeof events)+ for (const child of Object.values(record)) visit(child)+ }+ visit(sent)+ const starts = events.filter(event => event.name === "action.start" && event.attributes.navigation_kind === "route")+ expect(starts).toHaveLength(1)+ expect(starts[0]?.attributes).toMatchObject({ action_id: original!.id, start_ms: "1500" })+ const ready = events.filter(event => event.name === "navigation.ready" && event.attributes.navigation_kind === "route")+ expect(ready).toHaveLength(1)+ expect(ready[0]?.attributes).toMatchObject({ region: "messages", action_id: original!.id, navigation_id: original!.navigationId, start_ms: "1500", duration_ms: "60", trace_id: parent.traceId, span_id: parent.spanId })+ const navigationSpans = spans.filter(span => span.name === "navigation")+ expect(navigationSpans).toHaveLength(2)+ const back = navigationSpans.find(span => span.spanId === parent.spanId)!+ expect(back.traceId).toBe(parent.traceId)+ expect(Number(BigInt(String(back.endTimeUnixNano)) - BigInt(String(back.startTimeUnixNano))) / 1e6).toBeCloseTo(60, 2)+})diff --git a/src/web/src/lib/observability/navigation-ready-consent.dom.test.tsx b/src/web/src/lib/observability/navigation-ready-consent.dom.test.tsxnew file mode 100644index 000000000..6a0d70499--- /dev/null+++ b/src/web/src/lib/observability/navigation-ready-consent.dom.test.tsx@@ -0,0 +1,38 @@+import { afterEach, expect, it, vi } from "vitest"+import { act, render, waitFor } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"+import { useObservedRegion } from "./regions"++vi.mock("next/navigation", () => ({ usePathname: () => window.location.pathname, useSearchParams: () => new URLSearchParams() }))+let view: ReturnType<typeof render> | undefined+afterEach(async () => {+ await act(async () => { view?.unmount(); document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied"); await Promise.resolve() })+ window.history.replaceState(null, "", "/")+ vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.unstubAllGlobals()+})++it("does not backfill a pre-consent document visit and observes only later eligible navigation", async () => {+ sessionStorage.clear()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ vi.spyOn(performance, "getEntriesByType").mockReturnValue([])+ const sent: Array<{ events?: Array<{ name: string; attributes: Record<string, string> }> }> = []+ const fetch = vi.fn(async (_url: unknown, options?: RequestInit) => {+ if (options?.body) sent.push(JSON.parse(String(options.body)))+ return new Response(null, { status: 204 })+ })+ vi.stubGlobal("fetch", fetch)+ document.cookie = "alook_analytics_consent=v1.denied; path=/"+ const { bootstrapObservability, onObservedRouterTransition } = await import("./client")+ function Content() { useObservedRegion("page", true, { source: "unknown", version: "static", freshness: "unknown", count: 1 }); return <p>Ready page</p> }+ await act(async () => { bootstrapObservability("web"); view = render(<Content />) })+ expect(fetch).not.toHaveBeenCalled()+ await act(async () => { document.cookie = "alook_analytics_consent=v1.granted; path=/"; announceAnalyticsConsent("granted") })+ const events = () => sent.flatMap(body => body.events ?? [])+ await waitFor(() => expect(events().some(event => event.name === "region.ready_commit")).toBe(true), { timeout: 5000 })+ expect(events().some(event => event.name === "navigation.ready")).toBe(false)+ await act(async () => { onObservedRouterTransition("/pricing"); window.history.pushState(null, "", "/pricing"); view!.rerender(<Content />) })+ await waitFor(() => expect(events().filter(event => event.name === "navigation.ready")).toHaveLength(1), { timeout: 5000 })+ const ready = events().filter(event => event.name === "navigation.ready")+ expect(ready).toHaveLength(1)+ expect(ready[0]?.attributes).toMatchObject({ navigation_kind: "route", route_template: "/pricing", region: "page" })+})diff --git a/src/web/src/lib/observability/navigation-ready-revocation.dom.test.ts b/src/web/src/lib/observability/navigation-ready-revocation.dom.test.tsnew file mode 100644index 000000000..b841fd61e--- /dev/null+++ b/src/web/src/lib/observability/navigation-ready-revocation.dom.test.ts@@ -0,0 +1,36 @@+import { afterEach, expect, it, vi } from "vitest"+import { act } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"++afterEach(async () => {+ document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied")+ await vi.advanceTimersByTimeAsync(0)+ window.history.replaceState(null, "", "/")+ vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.unstubAllGlobals()+})++it("retires an initial visit revoked while waiting for identity instead of backfilling it on regrant", async () => {+ vi.useFakeTimers(); sessionStorage.clear()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ vi.spyOn(performance, "getEntriesByType").mockReturnValue([])+ const sent: Array<{ events?: Array<{ name: string; attributes: Record<string, string> }> }> = []+ const fetch = vi.fn(async (_url: unknown, options?: RequestInit) => {+ if (options?.body) sent.push(JSON.parse(String(options.body)))+ return new Response(null, { status: 204 })+ })+ vi.stubGlobal("fetch", fetch)+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ window.history.replaceState(null, "", "/c/me/bots")+ const { bootstrapObservability, setTelemetryUser } = await import("./client")+ const { navigationForHref } = await import("./context")+ await act(async () => { bootstrapObservability("web"); await vi.advanceTimersByTimeAsync(0) })+ expect(fetch).not.toHaveBeenCalled()+ await act(async () => {+ document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied")+ setTelemetryUser("account-a")+ document.cookie = "alook_analytics_consent=v1.granted; path=/"; announceAnalyticsConsent("granted")+ await vi.advanceTimersByTimeAsync(1500)+ })+ expect(navigationForHref(window.location.href)).toBeUndefined()+ expect(sent.flatMap(body => body.events ?? []).some(event => event.name === "navigation.intent")).toBe(false)+})diff --git a/src/web/src/lib/observability/navigation-ready-span-revocation.dom.test.ts b/src/web/src/lib/observability/navigation-ready-span-revocation.dom.test.tsnew file mode 100644index 000000000..2e082a9bd--- /dev/null+++ b/src/web/src/lib/observability/navigation-ready-span-revocation.dom.test.ts@@ -0,0 +1,48 @@+import { afterEach, expect, it, vi } from "vitest"+import { act } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"++const native = vi.hoisted(() => ({ release: undefined as (() => void) | undefined }))+vi.mock("@grafana/faro-web-sdk", async importOriginal => {+ const real = await importOriginal<typeof import("@grafana/faro-web-sdk")>()+ await new Promise<void>(resolve => { native.release = resolve })+ return real+})+afterEach(async () => {+ document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied")+ await vi.advanceTimersByTimeAsync(0)+ window.history.replaceState(null, "", "/")+ vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.unstubAllGlobals()+})++it("does not bind or export the completed document after consent and account retirement during import", async () => {+ vi.useFakeTimers(); sessionStorage.clear()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ vi.spyOn(performance, "getEntriesByType").mockReturnValue([])+ const sent: unknown[] = []+ vi.stubGlobal("fetch", vi.fn(async (_url: unknown, options?: RequestInit) => {+ if (options?.body) sent.push(JSON.parse(String(options.body)))+ return new Response(null, { status: 204 })+ }))+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ window.history.replaceState(null, "", "/c/me/bots")+ const { bootstrapObservability, setTelemetryUser } = await import("./client")+ const { navigationForHref, finishAction } = await import("./context")+ await act(async () => { bootstrapObservability("web"); setTelemetryUser("account-a") })+ await vi.waitFor(() => expect(native.release).toBeTypeOf("function"))+ const original = navigationForHref(window.location.href)!+ finishAction(original, "success", { phase: "primary", region: "bots" })+ expect(original.span).toBeUndefined()+ await act(async () => {+ document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied")+ setTelemetryUser("account-b")+ document.cookie = "alook_analytics_consent=v1.granted; path=/"; announceAnalyticsConsent("granted")+ native.release?.(); await vi.advanceTimersByTimeAsync(4000)+ })+ expect(sent.length).toBeGreaterThan(0)+ expect(original.span).toBeUndefined()+ expect(JSON.stringify(sent)).not.toContain(original.id)+ expect(JSON.stringify(sent)).not.toContain("navigation.ready")+ expect(JSON.stringify(sent)).not.toContain("account-a")+ expect(JSON.stringify(sent)).toContain("account-b")+})diff --git a/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsx b/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsxnew file mode 100644index 000000000..66a4dd14d--- /dev/null+++ b/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsx@@ -0,0 +1,84 @@+import { useLayoutEffect } from "react"+import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"+import { afterEach, expect, it, vi } from "vitest"+import { act, render } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"+import { useObservedQueryRegion } from "./query-regions"++const native = vi.hoisted(() => ({ release: undefined as (() => void) | undefined }))+vi.mock("@grafana/faro-web-sdk", async importOriginal => {+ const real = await importOriginal<typeof import("@grafana/faro-web-sdk")>()+ await new Promise<void>(resolve => { native.release = resolve })+ return real+})+vi.mock("next/navigation", () => ({ usePathname: () => window.location.pathname, useSearchParams: () => new URLSearchParams(window.location.search) }))+let view: ReturnType<typeof render> | undefined+let client: QueryClient | undefined+afterEach(async () => {+ await act(async () => { view?.unmount(); document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied"); client?.clear(); await vi.advanceTimersByTimeAsync(0) })+ window.history.replaceState(null, "", "/")+ vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.unstubAllGlobals()+})++it("binds the initial navigation before ready and parents a real native HTTP span", async () => {+ vi.useFakeTimers(); sessionStorage.clear()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ let now = 240+ vi.spyOn(performance, "now").mockImplementation(() => now)+ vi.spyOn(performance, "getEntriesByType").mockReturnValue([])+ const sent: unknown[] = []+ vi.stubGlobal("fetch", vi.fn(async (url: unknown, options?: RequestInit) => {+ if (String(url) === "https://collector.example/collect/public" && options?.body) sent.push(JSON.parse(String(options.body)))+ return new Response(null, { status: 204 })+ }))+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ window.history.replaceState(null, "", "/c/channels/server-a/channel-a")+ const { bootstrapObservability, setTelemetryUser } = await import("./client")+ const { navigationForHref } = await import("./context")+ client = new QueryClient()+ let resolve: ((value: never[]) => void) | undefined+ const data = new Promise<never[]>(done => { resolve = done })+ function Content() {+ const query = useQuery({ queryKey: ["messages"], queryFn: () => data, staleTime: Infinity })+ useObservedQueryRegion("messages", query, query.data?.length)+ return <p>{query.isPending ? "loading" : "empty"}</p>+ }+ function Root() {+ useLayoutEffect(() => setTelemetryUser("account-a"), [])+ return <QueryClientProvider client={client!}><Content /></QueryClientProvider>+ }+ await act(async () => { bootstrapObservability("web"); view = render(<Root />) })+ await vi.waitFor(() => expect(native.release).toBeTypeOf("function"))+ const navigation = navigationForHref(window.location.href)!+ expect(navigation.span).toBeUndefined()+ now = 900+ await act(async () => { native.release?.(); await vi.advanceTimersByTimeAsync(1500) })+ expect(navigation.span?.isRecording()).toBe(true)+ expect(navigationForHref(window.location.href)).toBe(navigation)+ const parent = navigation.span!.spanContext()+ const { apiFetchResponse } = await import("@/lib/api/client")+ await apiFetchResponse("/api/agents", { observation: { action: navigation, reason: "router" } })+ now = 1250+ await act(async () => { resolve?.([]); await vi.advanceTimersByTimeAsync(0); view!.rerender(<Root />) })+ expect(navigation.done).toBe(true)+ await act(async () => { await vi.advanceTimersByTimeAsync(3000) })+ const spans: Record<string, unknown>[] = []+ const events: Array<{ name: string; attributes: Record<string, string> }> = []+ const visit = (value: unknown) => {+ if (!value || typeof value !== "object") return+ const record = value as Record<string, unknown>+ if (typeof record.spanId === "string") spans.push(record)+ if (Array.isArray(record.events)) events.push(...record.events as typeof events)+ for (const child of Object.values(record)) visit(child)+ }+ visit(sent)+ const navigationSpan = spans.filter(span => span.spanId === parent.spanId)+ expect(navigationSpan).toHaveLength(1)+ expect(navigationSpan[0]).toMatchObject({ name: "navigation", traceId: parent.traceId })+ expect(Number(BigInt(String(navigationSpan[0]!.endTimeUnixNano)) - BigInt(String(navigationSpan[0]!.startTimeUnixNano))) / 1e6).toBeCloseTo(1250, 2)+ expect(spans.filter(span => span.parentSpanId === parent.spanId)).toMatchObject([{ name: "GET /api/agents", traceId: parent.traceId }])+ const ready = events.filter(event => event.name === "navigation.ready")+ expect(ready).toHaveLength(1)+ expect(ready[0]?.attributes).toMatchObject({ navigation_kind: "document", start_ms: "0", duration_ms: "1250", trace_id: parent.traceId, span_id: parent.spanId, action_id: navigation.id })+ expect(events.filter(event => event.name.startsWith("request.")).every(event => event.attributes.trace_id === parent.traceId && event.attributes.span_id === parent.spanId)).toBe(true)+})diff --git a/src/web/src/lib/observability/navigation-ready.dom.test.tsx b/src/web/src/lib/observability/navigation-ready.dom.test.tsxnew file mode 100644index 000000000..d003ca83e--- /dev/null+++ b/src/web/src/lib/observability/navigation-ready.dom.test.tsx@@ -0,0 +1,93 @@+import { useLayoutEffect } from "react"+import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"+import { afterEach, expect, it, vi } from "vitest"+import { act, render } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"+import { useObservedQueryRegion } from "./query-regions"++const native = vi.hoisted(() => ({ release: undefined as (() => void) | undefined }))+vi.mock("@grafana/faro-web-sdk", async importOriginal => {+ const real = await importOriginal<typeof import("@grafana/faro-web-sdk")>()+ await new Promise<void>(resolve => { native.release = resolve })+ return real+})+vi.mock("next/navigation", () => ({ usePathname: () => window.location.pathname, useSearchParams: () => new URLSearchParams(window.location.search) }))+let view: ReturnType<typeof render> | undefined+let client: QueryClient | undefined+afterEach(async () => {+ await act(async () => { view?.unmount(); document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied"); client?.clear(); await vi.advanceTimersByTimeAsync(0) })+ window.history.replaceState(null, "", "/")+ vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.unstubAllGlobals()+})++it("retains real ready time before a delayed SDK and records each later route once through native Faro", async () => {+ vi.useFakeTimers(); sessionStorage.clear()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ vi.stubEnv("NEXT_PUBLIC_FARO_ENVIRONMENT", undefined); vi.stubEnv("NEXT_PUBLIC_FARO_RELEASE", undefined)+ let now = 240+ vi.spyOn(performance, "now").mockImplementation(() => now)+ vi.spyOn(performance, "getEntriesByType").mockReturnValue([])+ type Exported = { name: string; timestamp: string; attributes: Record<string, string> }+ const sent: Array<{ events?: Exported[]; traces?: { resourceSpans: Array<{ scopeSpans: Array<{ spans: Array<{ name: string; traceId: string; spanId: string; startTimeUnixNano: string; endTimeUnixNano: string }> }> }> } }> = []+ vi.stubGlobal("fetch", vi.fn(async (_url: unknown, options?: RequestInit) => {+ if (options?.body) sent.push(JSON.parse(String(options.body)))+ return new Response(null, { status: 204 })+ }))+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ window.history.replaceState(null, "", "/c/channels/server-a/channel-a")+ const { bootstrapObservability, setTelemetryUser, onObservedRouterTransition } = await import("./client")+ const { navigationForHref } = await import("./context")+ client = new QueryClient()+ client.setQueryData(["messages"], []); client.setQueryData(["forum"], [])+ function Content({ region }: { region: "messages" | "forum" }) {+ const query = useQuery({ queryKey: [region], queryFn: async () => [], staleTime: Infinity })+ useObservedQueryRegion(region, query, query.data?.length)+ return <p>{region}: {query.isPending ? "loading" : "empty"}</p>+ }+ function Root({ region }: { region: "messages" | "forum" }) {+ useLayoutEffect(() => setTelemetryUser("account-a"), [])+ return <QueryClientProvider client={client!}><Content region={region} /></QueryClientProvider>+ }+ const readyAt = Date.now()+ await act(async () => { bootstrapObservability("web"); view = render(<Root region="messages" />) })+ await vi.waitFor(() => expect(native.release).toBeTypeOf("function"))+ expect(navigationForHref(window.location.href)).toBeUndefined()+ expect(sent).toEqual([])+ now = 900+ await act(async () => { native.release?.(); await vi.advanceTimersByTimeAsync(1500) })+ const exported = () => sent.flatMap(body => body.events ?? [])+ const metrics = () => exported().filter(event => event.name === "navigation.ready")+ expect(metrics()).toHaveLength(1)+ expect(metrics()[0]?.attributes).toMatchObject({ navigation_kind: "document", start_ms: "0", duration_ms: "240", region: "messages", outcome: "success" })+ expect(Date.parse(metrics()[0]!.timestamp)).toBe(readyAt)+ await act(async () => { await vi.advanceTimersByTimeAsync(3000) })+ const parent = sent.flatMap(body => body.traces?.resourceSpans.flatMap(resource => resource.scopeSpans.flatMap(scope => scope.spans)) ?? []).filter(span => span.name === "navigation")+ expect(parent).toHaveLength(1)+ expect(metrics()[0]?.attributes).toMatchObject({ trace_id: parent[0]!.traceId, span_id: parent[0]!.spanId })+ expect(Number(BigInt(parent[0]!.endTimeUnixNano) - BigInt(parent[0]!.startTimeUnixNano)) / 1e6).toBeCloseTo(240, 2)+ expect(Number(BigInt(parent[0]!.startTimeUnixNano)) / 1e6).toBeCloseTo(performance.timeOrigin, 2)+ expect(exported().filter(event => event.attributes.action_id === metrics()[0]!.attributes.action_id).every(event => event.attributes.trace_id === parent[0]!.traceId && event.attributes.span_id === parent[0]!.spanId)).toBe(true)+ expect(exported().filter(event => event.name === "action.start" && event.attributes.action_name === "navigation")).toHaveLength(1)+ await act(async () => {+ now = 1700+ onObservedRouterTransition("/c/channels/server-a/forum-a")+ window.history.pushState(null, "", "/c/channels/server-a/forum-a")+ now = 1750+ view!.rerender(<Root region="forum" />)+ })+ await act(async () => { await vi.advanceTimersByTimeAsync(1500) })+ expect(metrics()).toHaveLength(2)+ expect(metrics()[1]?.attributes).toMatchObject({ navigation_kind: "route", start_ms: "1700", duration_ms: "50", region: "forum", outcome: "success" })+ expect(metrics()[1]?.attributes.action_id).not.toBe(metrics()[0]?.attributes.action_id)+ await act(async () => { now = 2300; client!.setQueryData(["forum"], []); view!.rerender(<Root region="forum" />); await vi.advanceTimersByTimeAsync(1500) })+ expect(metrics()).toHaveLength(2)+ await act(async () => {+ document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied")+ onObservedRouterTransition("/c/me/bots")+ await vi.advanceTimersByTimeAsync(0)+ now = 3000+ document.cookie = "alook_analytics_consent=v1.granted; path=/"; announceAnalyticsConsent("granted")+ await vi.advanceTimersByTimeAsync(1500)+ })+ expect(metrics()).toHaveLength(2)+})diff --git a/src/web/src/lib/observability/provider-auth-null.dom.test.tsx b/src/web/src/lib/observability/provider-auth-null.dom.test.tsxnew file mode 100644index 000000000..4e455c2d3--- /dev/null+++ b/src/web/src/lib/observability/provider-auth-null.dom.test.tsx@@ -0,0 +1,74 @@+import "fake-indexeddb/auto"+import { createContext, useContext, useLayoutEffect } from "react"+import { useIsRestoring } from "@tanstack/react-query"+import { afterEach, expect, it, vi } from "vitest"+import { act, render, waitFor } from "@/test/react-dom-harness"+import { announceAnalyticsConsent } from "../analytics-consent"++type Identity = { data: { user: { id: string } } | null; isPending: boolean; error: Error | null }+const identityInput = createContext<Identity>({ data: null, isPending: true, error: null })+let viewer: string | null | undefined+vi.mock("@/lib/auth-client", () => ({ useSession: () => useContext(identityInput), currentSessionViewer: () => viewer }))+vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))+vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))+let old: ReturnType<typeof render> | undefined, current: ReturnType<typeof render> | undefined+afterEach(async () => {+ await act(async () => { old?.unmount(); current?.unmount(); old = current = undefined; document.cookie = "alook_analytics_consent=v1.denied; path=/"; announceAnalyticsConsent("denied"); await new Promise(resolve => setTimeout(resolve, 0)) })+ window.history.replaceState(null, "", "/")+ vi.unstubAllEnvs(); vi.unstubAllGlobals()+})+it("both actual account Providers retain pending/error and newer B, then retire telemetry on current confirmed SDK anonymous identity", async () => {+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ vi.stubEnv("NEXT_PUBLIC_FARO_ENVIRONMENT", "qa")+ vi.stubEnv("NEXT_PUBLIC_FARO_RELEASE", "a".repeat(40))+ Object.defineProperty(performance, "getEntriesByType", { configurable: true, value: () => [] })+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ window.history.replaceState(null, "", "/workspaces")+ const sent: Array<{ meta: { session: { id: string }; user?: { id: string } } }> = []+ vi.stubGlobal("fetch", vi.fn(async (_url: unknown, init?: RequestInit) => { if (init?.body) sent.push(JSON.parse(String(init.body))); return new Response(null, { status: 204 }) }))+ const { bootstrapObservability } = await import("./client")+ const { QueryProvider } = await import("@/app/c/QueryProvider")+ const { ApplicationQueryProvider } = await import("../application-owner")+ const { VolatileSessionsManager } = await import("@grafana/faro-web-sdk")+ const { emitTelemetry, isTelemetryEligible } = await import("./telemetry")+ bootstrapObservability("web")+ const known = (id: string): Identity => ({ data: { user: { id } }, isPending: false, error: null })+ const restoring = new Map<string, boolean>()+ function Probe({ id }: { id: string }) { const pending = useIsRestoring(); useLayoutEffect(() => { restoring.set(id, pending) }, [id, pending]); return <p>{id}</p> }+ for (const kind of ["application", "community"] as const) {+ const Provider = kind === "application" ? ApplicationQueryProvider : QueryProvider+ function Root({ id, identity }: { id: string; identity: Identity }) { return <identityInput.Provider value={identity}><Provider userId={id}><Probe id={id} /></Provider></identityInput.Provider> }+ const a = kind + "-a", b = kind + "-b"+ viewer = a+ await act(async () => { old = render(<Root id={a} identity={known(a)} />) })+ await waitFor(() => expect(restoring.get(a)).toBe(false))+ await waitFor(() => expect(isTelemetryEligible()).toBe(true))+ await waitFor(() => expect(sent.some(body => body.meta.user?.id === a)).toBe(true), { timeout: 5000 })+ const originalSession = VolatileSessionsManager.fetchUserSession()!.sessionId+ viewer = undefined+ await act(async () => old!.rerender(<Root id={a} identity={{ data: null, isPending: true, error: null }} />))+ expect(VolatileSessionsManager.fetchUserSession()!.sessionId).toBe(originalSession)+ await act(async () => old!.rerender(<Root id={a} identity={{ data: null, isPending: false, error: new Error("Auth pending") }} />))+ expect(VolatileSessionsManager.fetchUserSession()!.sessionId).toBe(originalSession)+ viewer = b+ await act(async () => { current = render(<Root id={b} identity={known(b)} />) })+ await waitFor(() => expect(restoring.get(b)).toBe(false))+ await waitFor(() => expect(isTelemetryEligible()).toBe(true))+ await waitFor(() => expect(VolatileSessionsManager.fetchUserSession()!.sessionId).not.toBe(originalSession))+ const replacementSession = VolatileSessionsManager.fetchUserSession()!.sessionId+ await act(async () => old!.rerender(<Root id={a} identity={{ data: null, isPending: false, error: null }} />))+ expect(VolatileSessionsManager.fetchUserSession()!.sessionId).toBe(replacementSession)+ emitTelemetry("business.result", { outcome: "success" })+ await waitFor(() => expect(sent.some(body => body.meta.session.id === replacementSession && body.meta.user?.id === b)).toBe(true), { timeout: 5000 })+ await act(async () => { old!.unmount(); old = undefined })+ viewer = null+ await act(async () => current!.rerender(<Root id={b} identity={{ data: null, isPending: false, error: null }} />))+ await waitFor(() => expect(isTelemetryEligible()).toBe(true))+ await waitFor(() => expect(VolatileSessionsManager.fetchUserSession()!.sessionId).not.toBe(replacementSession))+ const anonymousSession = VolatileSessionsManager.fetchUserSession()!.sessionId+ emitTelemetry("business.result", { outcome: "success" })+ await waitFor(() => expect(sent.some(body => body.meta.session.id === anonymousSession)).toBe(true), { timeout: 5000 })+ for (const body of sent.filter(body => body.meta.session.id === anonymousSession)) expect(body.meta.user).toBeUndefined()+ await act(async () => { current!.unmount(); current = undefined; await new Promise(resolve => setTimeout(resolve, 0)) })+ }+})diff --git a/src/web/src/lib/observability/query-observer.test.ts b/src/web/src/lib/observability/query-observer.test.tsnew file mode 100644index 000000000..a6e472e8f--- /dev/null+++ b/src/web/src/lib/observability/query-observer.test.ts@@ -0,0 +1,71 @@+import { afterEach, beforeEach, expect, it } from "vitest"+import { createMessageStreamStore } from "@/stores/community/message-stream-store"+import { QueryClient } from "@tanstack/react-query"+import { observeQueryClient, disposeQueryDiagnostics } from "./query-observer"+import { configureTelemetry, installTelemetrySink, retireTelemetry } from "./telemetry"+import { valueEvidence, withSource } from "./data-source"+import { commandObservation, clearActions } from "./context"+import { startRequest, requestHeaders, readObservedResponse } from "./requests"++let client: QueryClient+const events: Array<{ name: string; attributes: Record<string, string> }> = []+beforeEach(() => { client = observeQueryClient(new QueryClient()); events.length = 0; configureTelemetry({ session_id: "session-a" }, true); installTelemetrySink(event => events.push(event)) })+afterEach(() => { retireTelemetry(); clearActions(); disposeQueryDiagnostics(client); client.clear() })+it("distinguishes actual HTTP values from local Query functions and manual WS writes", async () => {+ const queryKey = ["remote"]+ const remote = await client.fetchQuery({ queryKey, queryFn: async () => {+ const request = startRequest("/api/agents"), response = new Response('[{"id":"private"}]')+ requestHeaders(request, response)+ return readObservedResponse(response, () => response.json())+ } })+ expect(valueEvidence(client, remote).source).toBe("network")+ const local = await client.fetchQuery({ queryKey: ["local"], queryFn: () => ({ status: "rendered" }) })+ expect(valueEvidence(client, local).source).toBe("unknown")+ withSource(client, "ws", () => client.setQueryData(queryKey, [{ id: "private", changed: true }]))+ expect(valueEvidence(client, client.getQueryData(queryKey)).source).toBe("mixed")+ expect(JSON.stringify(events)).not.toContain("private")+})+it("uses native mutation pending/terminal events once and binds each original request token", async () => {+ const one = { original: {} }, two = { original: {} }+ let resolve!: () => void+ const waiting = new Promise<void>(done => { resolve = done })+ const build = (name: string) => client.getMutationCache().build(client, { meta: { observabilityAction: name }, mutationFn: async (input: typeof one) => {+ expect(commandObservation(input.original)?.action?.name).toBe(name)+ await waiting+ } })+ const a = build("message.edit").execute(one), b = build("message.pin").execute(two)+ await Promise.resolve()+ expect(events.filter(event => event.name === "action.start")).toHaveLength(2)+ resolve(); await Promise.all([a, b])+ expect(events.filter(event => event.name === "action.finish")).toHaveLength(2)+ expect(new Set(events.filter(event => event.name === "action.start").map(event => event.attributes.action_id)).size).toBe(2)+ const delegated = client.getMutationCache().build(client, { meta: { observabilityAction: "member.management.command", observabilityDelegate: true }, mutationFn: async () => undefined })+ await delegated.execute(undefined)+ expect(events.filter(event => event.name === "action.start")).toHaveLength(2)+})++it("joins optimistic acceptance and the native send acknowledgment without a duplicate lifecycle", async () => {+ const stream = createMessageStreamStore(undefined, client)+ const scope = { kind: "channel" as const, id: "channel", serverId: "server" }+ const input = { original: {}, nonce: "private-nonce" }+ stream.actions.accept(scope, { nonce: input.nonce, tempId: "temp", message: { type: "chat", content: "private-body" }, localUploads: [] })+ const command = client.getMutationCache().build(client, { meta: { observabilityAction: "channel.message.send" }, mutationFn: async (args: typeof input) => {+ expect(commandObservation(args.original)?.action?.id).toBe(events.find(event => event.name === "action.start")?.attributes.action_id)+ stream.actions.dispatch(scope, { type: "postAck", nonce: args.nonce, message: { id: "message", seq: 1, type: "chat", content: "private-body" } })+ } })+ await command.execute(input)+ expect(events.filter(event => event.name === "action.start")).toHaveLength(1)+ expect(events.filter(event => event.name === "action.finish")).toHaveLength(1)+ expect(events.filter(event => event.name === "message.milestone").map(event => event.attributes.phase)).toEqual(["optimistic", "ack"])+ expect(JSON.stringify(events)).not.toContain("private")+ retireTelemetry(); configureTelemetry({ session_id: "session-b" }, true); installTelemetrySink(event => events.push(event))+ const count = events.length+ stream.actions.dispatch(scope, { type: "postFail", nonce: input.nonce })+ expect(events).toHaveLength(count)+})+it("keeps owner friend decisions as distinct stable native mutation semantics", async () => {+ for (const decision of ["approve", "deny"]) {+ await client.getMutationCache().build(client, { meta: { observabilityAction: "friend.owner_decision.command" }, mutationFn: async () => undefined }).execute({ decision, original: {} })+ }+ expect(events.filter(event => event.name === "action.start").map(event => event.attributes.action_name)).toEqual(["friend.request.approve", "friend.request.deny"])+})diff --git a/src/web/src/lib/observability/query-observer.ts b/src/web/src/lib/observability/query-observer.tsnew file mode 100644index 000000000..dde74e5f3--- /dev/null+++ b/src/web/src/lib/observability/query-observer.ts@@ -0,0 +1,50 @@+import type { QueryClient, Query, Mutation } from "@tanstack/react-query"+import { messageObservation, disposeMessageObservations } from "./messages"+import { actionNames } from "./coverage"+import { resolveActionName } from "./actions"+import { startAction, finishAction, bindCommandAction, type Action } from "./context"+import { currentSource, disposeSources, forgetCollection, tagValue, observedValueSource } from "./data-source"+import { isTelemetryEligible, emitTelemetry } from "./telemetry"++const clients = new WeakMap<QueryClient, () => void>()+const allowed = new Set<string>(actionNames)+export function observeQueryClient(client: QueryClient) {+ if (clients.has(client)) return client+ const actions = new WeakMap<Mutation, Action>()+ const data = new WeakMap<Query, unknown>()+ const stopQueries = client.getQueryCache().subscribe(event => {+ if (!isTelemetryEligible()) return+ if (event.type === "removed") {+ data.delete(event.query)+ if (event.query.queryKey[0] === "community" && event.query.queryKey[1] === "db") forgetCollection(client, String(event.query.queryKey[3]))+ return+ }+ if (event.type !== "updated" || event.action.type !== "success") return+ const query = event.query, value = query.state.data, previous = data.get(query)+ const source = event.action.manual ? currentSource(client) : observedValueSource(value)+ tagValue(client, value, source, previous)+ data.set(query, value)+ })+ const stopMutations = client.getMutationCache().subscribe(event => {+ if (event.type !== "updated") return+ const mutation = event.mutation+ if (mutation.options.meta?.observabilityDelegate === true) return+ if (event.action.type === "pending" && isTelemetryEligible()) {+ if (actions.has(mutation)) return+ const base = mutation.options.meta?.observabilityAction+ const name = typeof base === "string" ? resolveActionName(base, mutation.state.variables) : "command.unknown"+ const input = mutation.state.variables && typeof mutation.state.variables === "object" ? mutation.state.variables as Record<string, unknown> : {}+ const accepted = ["channel.message.send", "dm.message.send"].includes(name) ? messageObservation(client, input.nonce) : undefined+ const action = accepted ?? startAction(allowed.has(name) ? name : "command.unknown")+ if (action) { actions.set(mutation, action); bindCommandAction(mutation.state.variables, action) }+ if (name === "command.unknown") emitTelemetry("telemetry.coverage", { capability: "limited", action_name: name })+ } else if (event.action.type === "success" || event.action.type === "error") {+ const error = mutation.state.error+ finishAction(actions.get(mutation), event.action.type === "success" ? "success" : error instanceof Error && error.name === "AbortError" ? "cancelled" : "error", { phase: "primary" })+ actions.delete(mutation)+ }+ })+ clients.set(client, () => { stopQueries(); stopMutations(); disposeSources(client); disposeMessageObservations(client); clients.delete(client) })+ return client+}+export function disposeQueryDiagnostics(client: QueryClient) { clients.get(client)?.() }diff --git a/src/web/src/lib/observability/query-regions.ts b/src/web/src/lib/observability/query-regions.tsnew file mode 100644index 000000000..e2c14daaa--- /dev/null+++ b/src/web/src/lib/observability/query-regions.ts@@ -0,0 +1,13 @@+"use client"++import { useQueryClient } from "@tanstack/react-query"+import { valueEvidence, type Evidence } from "./data-source"+import { useObservedRegion } from "./regions"+import type { Attributes } from "./schema"++type Resource = { data: unknown; isPending: boolean; isError?: boolean; dataUpdatedAt?: number }+export function useObservedQueryRegion(region: Attributes["region"], resource: Resource, count?: number, ready = true) {+ const client = useQueryClient()+ const evidence: Evidence = resource.data && typeof resource.data === "object" ? valueEvidence(client, resource.data) : { source: "unknown", version: "query_" + String(resource.dataUpdatedAt ?? 0), freshness: "unknown", count: resource.data == null ? 0 : 1 }+ useObservedRegion(region, ready && !resource.isPending && resource.data !== undefined, { ...evidence, ...(count === undefined ? {} : { count }) })+}diff --git a/src/web/src/lib/observability/regions.dom.test.tsx b/src/web/src/lib/observability/regions.dom.test.tsxnew file mode 100644index 000000000..793f3f646--- /dev/null+++ b/src/web/src/lib/observability/regions.dom.test.tsx@@ -0,0 +1,40 @@+import { afterEach, expect, it, vi } from "vitest"+import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"+import { act, render, screen, setupUser, waitFor } from "@/test/react-dom-harness"+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"+import { configureTelemetry, installTelemetrySink, retireTelemetry } from "./telemetry"+import { clearActions } from "./context"+import { observeQueryClient, disposeQueryDiagnostics } from "./query-observer"+import { useObservedQueryRegion } from "./query-regions"+import { startRequest, requestHeaders, readObservedResponse } from "./requests"++vi.mock("next/navigation", () => ({ usePathname: () => "/", useSearchParams: () => new URLSearchParams() }))+const events: Array<{ name: string; attributes: Record<string, string> }> = []+let client: QueryClient+async function emptyResponse() {+ const request = startRequest("/api/agents"), response = new Response("[]")+ requestHeaders(request, response)+ return readObservedResponse(response, () => response.json()) as Promise<unknown[]>+}+function Panel({ name }: { name: string }) {+ const resource = useQuery({ queryKey: [name], queryFn: emptyResponse })+ useObservedQueryRegion(name === "active" ? "files" : "settings", resource, resource.data?.length)+ return <p>{name}: {resource.isPending ? "loading" : "empty"}</p>+}+afterEach(async () => { await act(async () => { retireTelemetry(); clearActions(); disposeQueryDiagnostics(client); client.clear() }) })+it("observes actual settled empty Query values only after a retained Base UI panel becomes visible", async () => {+ events.length = 0+ client = observeQueryClient(new QueryClient())+ configureTelemetry({ session_id: "session-a" }, true)+ installTelemetrySink(event => events.push(event))+ const view = render(<QueryClientProvider client={client}><Tabs defaultValue="active"><TabsList><TabsTrigger value="active">Active</TabsTrigger><TabsTrigger value="retained">Retained</TabsTrigger></TabsList><TabsContent value="active" keepMounted><Panel name="active" /></TabsContent><TabsContent value="retained" keepMounted><Panel name="retained" /></TabsContent></Tabs></QueryClientProvider>)+ await waitFor(() => expect(client.getQueryData(["retained"])).toEqual([]))+ await waitFor(() => expect(events.filter(event => event.name === "region.ready_commit" && event.attributes.region === "files")).toHaveLength(1))+ expect(events.filter(event => event.name === "region.ready_commit" && event.attributes.region === "settings")).toHaveLength(0)+ const empty = events.find(event => event.name === "region.ready_commit")!+ expect(empty.attributes).toMatchObject({ row_count: "0", outcome: "empty", source: "network" })+ await setupUser().click(screen.getByRole("tab", { name: "Retained" }))+ await waitFor(() => expect(events.filter(event => event.name === "region.ready_commit" && event.attributes.region === "settings")).toHaveLength(1))+ await act(async () => { view.rerender(<QueryClientProvider client={client}><Tabs defaultValue="active"><TabsList><TabsTrigger value="active">Active</TabsTrigger><TabsTrigger value="retained">Retained</TabsTrigger></TabsList><TabsContent value="active" keepMounted><Panel name="active" /></TabsContent><TabsContent value="retained" keepMounted><Panel name="retained" /></TabsContent></Tabs></QueryClientProvider>) })+ expect(events.filter(event => event.name === "region.ready_commit" && event.attributes.region === "settings")).toHaveLength(1)+})diff --git a/src/web/src/lib/observability/regions.tsx b/src/web/src/lib/observability/regions.tsxnew file mode 100644index 000000000..5d2763e18--- /dev/null+++ b/src/web/src/lib/observability/regions.tsx@@ -0,0 +1,62 @@+"use client"++import { createContext, useContext, type ReactNode, Suspense, useEffect, useMemo, useRef, useSyncExternalStore } from "react"+import { usePathname, useSearchParams } from "next/navigation"+import { commitNavigation, committedNavigationPathname, currentRoute, navigationForHref, finishAction, actionAttributes } from "./context"+import { emitTelemetry, isTelemetryEligible, telemetryGeneration, subscribeObservation, observationSnapshot } from "./telemetry"+import { viewEvidence, mergeEvidence, type Evidence } from "./data-source"+import type { Attributes } from "./schema"++export function windowEvidence(values: readonly unknown[], emptySource?: unknown): Evidence {+ return values.length ? { ...mergeEvidence(values.map(viewEvidence)), count: values.length } : { ...viewEvidence(emptySource ?? values), count: 0 }+}+const visibility = createContext(true)+export function ObservedRegionVisibility({ visible, children }: { visible: boolean; children: ReactNode }) {+ const parent = useContext(visibility)+ return <visibility.Provider value={parent && visible}>{children}</visibility.Provider>+}++export function useObservedRegion(region: Attributes["region"], ready: boolean, evidence: Evidence) {+ const visible = useContext(visibility)+ const revision = useSyncExternalStore(subscribeObservation, observationSnapshot, () => 0)+ const href = typeof window === "undefined" ? "/" : window.location.pathname + window.location.search+ const signature = evidence.version + ":" + evidence.source + ":" + evidence.freshness + ":" + evidence.count + ":" + (evidence.wsEventId ?? "")+ const rendered = useMemo(() => ({ ...evidence, signature, observationRevision: revision, pathname: committedNavigationPathname(), route: currentRoute(), href, action: navigationForHref(href), generation: telemetryGeneration() }), [evidence, signature, href, revision])+ const emitted = useRef("")+ useEffect(() => {+ if (!visible || !ready || !isTelemetryEligible() || rendered.generation !== telemetryGeneration() || rendered.href !== window.location.pathname + window.location.search) return+ if (rendered.pathname !== undefined && rendered.pathname !== window.location.pathname) return+ const action = rendered.action && !rendered.action.done ? rendered.action : undefined+ const baseIdentity = String(rendered.generation) + ":" + rendered.href + ":" + rendered.signature + ":"+ const identity = baseIdentity + (action?.id ?? "")+ if (identity === emitted.current || (!action && emitted.current.startsWith(baseIdentity))) return+ emitted.current = identity+ const fields = { ...actionAttributes(action), region, ws_event_id: rendered.wsEventId, ws_duration_ms: rendered.wsStart === undefined ? undefined : performance.now() - rendered.wsStart, route_template: rendered.route, source: rendered.source, data_version: rendered.version, freshness: rendered.freshness, row_count: rendered.count, eligibility: "eligible", outcome: rendered.count ? "success" : "empty", phase: action ? "primary" : "background" }+ emitTelemetry("region.read", fields)+ emitTelemetry("region.ready_commit", fields)+ const selectorReady = region === "sidebar" && ["/c/me", "/c/channels/[serverId]"].includes(rendered.route)+ if (selectorReady || !["shell", "rail", "sidebar", "members", "thread_opener"].includes(String(region))) finishAction(action, "success", { region, phase: "primary" })+ if (document.visibilityState !== "visible" || typeof requestAnimationFrame !== "function") {+ emitTelemetry("region.frame_estimate", { ...fields, capability: "unavailable", visibility: document.visibilityState })+ return+ }+ const start = performance.now()+ const handle = requestAnimationFrame(() => { if (rendered.generation === telemetryGeneration() && isTelemetryEligible()) emitTelemetry("region.frame_estimate", { ...fields, duration_ms: performance.now() - start, phase: "frame", capability: "limited", visibility: document.visibilityState }) })+ return () => cancelAnimationFrame(handle)+ }, [visible, ready, region, rendered, signature])+}+function RouteCommit() {+ const pathname = usePathname(), search = useSearchParams().toString()+ useEffect(() => {+ if (pathname.startsWith("/c")) return+ commitNavigation(pathname + (search ? "?" + search : ""), "page")+ }, [pathname, search])+ return null+}+export function ObservedRouteCommit() { return <Suspense fallback={null}><RouteCommit /></Suspense> }++export function ObservedStaticContent({ pathname }: { pathname?: string }) {+ const ready = pathname === undefined || (typeof window !== "undefined" && pathname === window.location.pathname)+ useObservedRegion("page", ready, { source: "unknown", version: "ssr_committed", freshness: "unknown", count: 1 })+ return null+}diff --git a/src/web/src/lib/observability/requests.ts b/src/web/src/lib/observability/requests.tsnew file mode 100644index 000000000..59280576b--- /dev/null+++ b/src/web/src/lib/observability/requests.ts@@ -0,0 +1,60 @@+import { actionAttributes, telemetryId, type Action } from "./context"+import { routeTemplate } from "./coverage"+import { emitTelemetry, isTelemetryEligible, telemetryGeneration } from "./telemetry"+import { tagNetworkResponse } from "./data-source"+import type { Attributes } from "./schema"+import { context, trace } from "@opentelemetry/api"++export type RequestObservation = { id: string; start: number; generation: number; fields: Attributes; done: boolean; action?: Action }+const responses = new WeakMap<Response, RequestObservation>()+export function startRequest(path: string, options?: { method?: string; observation?: { action?: Action; reason?: Attributes["request_reason"] } }): RequestObservation | undefined {+ if (!isTelemetryEligible()) return+ const origin = typeof window === "undefined" ? "https://alook.ai" : window.location.origin+ const fields = { ...actionAttributes(options?.observation?.action), route_template: routeTemplate(path, origin), method: options?.method ?? "GET", request_reason: options?.observation?.reason ?? "unknown", request_kind: "api", eligibility: "unknown" }+ const request = { id: telemetryId(), start: performance.now(), generation: telemetryGeneration(), fields, done: false, action: options?.observation?.action }+ emitTelemetry("request.start", { ...fields, request_id: request.id, start_ms: request.start })+ return request+}+export function runObservedFetch<T>(request: RequestObservation | undefined, execute: () => T): T {+ const action = request?.action+ return action?.span && !action.done && action.generation === telemetryGeneration() && isTelemetryEligible()+ ? context.with(trace.setSpan(context.active(), action.span), execute)+ : execute()+}+function fields(request?: RequestObservation): Attributes {+ const current = request?.action?.generation === telemetryGeneration() ? actionAttributes(request.action) : {}+ return request ? { ...request.fields, trace_id: current.trace_id ?? request.fields.trace_id, span_id: current.span_id ?? request.fields.span_id, request_id: request.id, start_ms: request.start, duration_ms: performance.now() - request.start } : {}+}+export function requestHeaders(request: RequestObservation | undefined, response: Response) {+ if (!request || request.generation !== telemetryGeneration()) return+ const ray = response.headers.get("cf-ray") ?? undefined+ request.fields = { ...request.fields, status: response.status, cf_ray: ray }+ responses.set(response, request)+ emitTelemetry("request.headers", { ...fields(request), phase: "headers" })+}+function requestBodyParsed(response: Response) {+ const request = responses.get(response)+ if (request && request.generation === telemetryGeneration()) emitTelemetry("request.body_parsed", { ...fields(request), phase: "body" })+}+export function requestRejected(request: RequestObservation | undefined) {+ if (request && request.generation === telemetryGeneration()) emitTelemetry("data.response_rejected", { ...fields(request), eligibility: "rejected", outcome: "rejected" })+}+export function finishRequest(request: RequestObservation | undefined, outcome: Attributes["outcome"], phase: "body" | "headers", eligibility: Attributes["eligibility"] = "unknown") {+ if (!request || request.done) return+ request.done = true+ if (request.generation === telemetryGeneration()) emitTelemetry("request.finish", { ...fields(request), outcome, phase, eligibility })+}+export async function readObservedResponse<T>(response: Response, read: () => Promise<T>, qualify?: () => void): Promise<T> {+ const request = responses.get(response)+ try {+ const value = await read()+ requestBodyParsed(response)+ try { qualify?.() } catch (error) { requestRejected(request); throw error }+ if (request?.generation === telemetryGeneration()) tagNetworkResponse(value)+ finishRequest(request, "success", "body", "eligible")+ return value+ } catch (error) {+ finishRequest(request, error instanceof Error && error.name === "AbortError" ? "cancelled" : "error", "body")+ throw error+ } finally { responses.delete(response) }+}diff --git a/src/web/src/lib/observability/restore.test.ts b/src/web/src/lib/observability/restore.test.tsnew file mode 100644index 000000000..3172f9ea4--- /dev/null+++ b/src/web/src/lib/observability/restore.test.ts@@ -0,0 +1,57 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest"+import { hashKey, hydrate, QueryClient } from "@tanstack/react-query"+import type { PersistedClient } from "@tanstack/react-query-persist-client"+import { observeRestoreRead, observeRestoreDecode, observeHydration } from "./restore"+import { valueEvidence } from "./data-source"+import { configureTelemetry, installTelemetrySink, retireTelemetry } from "./telemetry"++const snapshot = (): PersistedClient => ({ timestamp: Date.now(), buster: "current", clientState: { mutations: [], queries: [{ queryKey: ["community", "db", "account-a", "messages"], queryHash: hashKey(["community", "db", "account-a", "messages"]), state: { data: [{ id: "one", content: "private" }], dataUpdatedAt: Date.now(), dataUpdateCount: 1, error: null, errorUpdatedAt: 0, errorUpdateCount: 0, fetchFailureCount: 0, fetchFailureReason: null, fetchMeta: null, isInvalidated: false, status: "success", fetchStatus: "idle" } }] } })+describe("restore observation admission", () => {+ const events: Array<{ name: string; attributes: Record<string, string> }> = []+ let client: QueryClient+ const activate = (id: string) => { configureTelemetry({ session_id: id }, true); installTelemetrySink(event => events.push(event)) }+ beforeEach(() => { client = new QueryClient(); events.length = 0; activate("session-a") })+ afterEach(() => { retireTelemetry(); client.clear() })+ it("tags only the unchanged snapshot actually hydrated in the admitted generation", async () => {+ const persister = {}, data = snapshot()+ await observeRestoreRead(async () => JSON.stringify(data), persister)+ const decoded = observeRestoreDecode(persister, () => data, "current", 10000)+ hydrate(client, decoded.clientState); observeHydration(persister, client)+ expect(events.filter(event => event.name === "cache.restore.finish").map(event => event.attributes.outcome)).toEqual(["hit", "hit", "success"])+ expect(valueEvidence(client, client.getQueryData(["community", "db", "account-a", "messages"])).source).toBe("restored_idb")+ expect(JSON.stringify(events)).not.toContain("private")+ })+ it("does not emit a late read, decode or hydrate into a regranted account session", async () => {+ const persister = {}, data = snapshot()+ let resolve!: (value: string) => void+ const reading = observeRestoreRead(() => new Promise<string>(done => { resolve = done }), persister)+ retireTelemetry(); activate("session-b"); events.length = 0+ resolve(JSON.stringify(data)); await reading+ const decoded = observeRestoreDecode(persister, () => data, "current", 10000)+ hydrate(client, decoded.clientState); observeHydration(persister, client)+ expect(events).toEqual([])+ expect(valueEvidence(client, client.getQueryData(["community", "db", "account-a", "messages"])).source).toBe("unknown")+ })+ it("rejects an old hydration-helper callback and preserves a fresh replacement query", async () => {+ const persister = {}, data = snapshot()+ await observeRestoreRead(async () => JSON.stringify(data), persister)+ observeRestoreDecode(persister, () => data, "current", 10000)+ retireTelemetry(); activate("session-b"); events.length = 0+ client.setQueryData(["community", "db", "account-a", "messages"], [{ id: "new" }])+ observeHydration(persister, client)+ expect(events).toEqual([])+ expect(client.getQueryData(["community", "db", "account-a", "messages"])).toEqual([{ id: "new" }])+ })+ it("preserves original read/decode failures and records only eligible error phases", async () => {+ const failure = new Error("private-storage-error"), persister = {}+ await expect(observeRestoreRead(async () => { throw failure }, persister)).rejects.toBe(failure)+ expect(() => observeRestoreDecode(persister, () => { throw failure }, "current", 10000)).toThrow(failure)+ expect(events.filter(event => event.name === "cache.restore.finish").map(event => [event.attributes.phase, event.attributes.outcome])).toEqual([["idb_read", "error"], ["deserialize", "error"]])+ expect(JSON.stringify(events)).not.toContain(failure.message)+ retireTelemetry(); events.length = 0+ await expect(observeRestoreRead(async () => { throw failure })).rejects.toBe(failure)+ expect(() => observeRestoreDecode({}, () => { throw failure }, "current", 10000)).toThrow(failure)+ expect(events).toEqual([])+ })++})diff --git a/src/web/src/lib/observability/restore.ts b/src/web/src/lib/observability/restore.tsnew file mode 100644index 000000000..76e13b4de--- /dev/null+++ b/src/web/src/lib/observability/restore.ts@@ -0,0 +1,63 @@+import type { QueryClient } from "@tanstack/react-query"+import type { PersistedClient } from "@tanstack/react-query-persist-client"+import { recordRows, tagValue } from "./data-source"+import { emitTelemetry, isTelemetryEligible, telemetryGeneration } from "./telemetry"+import { telemetryId } from "./context"++const restored = new WeakMap<object, { snapshot: PersistedClient; start: number; id: string; generation: number }>()+const reads = new WeakMap<object, Array<{ generation: number; eligible: boolean }>>()+export async function observeRestoreRead<T>(operation: () => Promise<T>, persister?: object): Promise<T> {+ const generation = telemetryGeneration(), eligible = isTelemetryEligible()+ const start = performance.now(), id = telemetryId()+ if (eligible) emitTelemetry("cache.restore.start", { request_id: id, start_ms: start, phase: "idb_read", cache_stage: "idb" })+ try {+ const result = await operation()+ if (persister && result != null) {+ const pending = reads.get(persister) ?? []+ pending.push({ generation, eligible })+ if (pending.length > 4) for (const receipt of pending) { receipt.eligible = false; receipt.generation = -1 }+ reads.set(persister, pending.slice(-4))+ }+ if (eligible && generation === telemetryGeneration()) emitTelemetry("cache.restore.finish", { request_id: id, phase: "idb_read", outcome: result == null ? "miss" : "hit", duration_ms: performance.now() - start })+ return result+ } catch (error) {+ if (eligible && generation === telemetryGeneration()) emitTelemetry("cache.restore.finish", { request_id: id, phase: "idb_read", outcome: "error", duration_ms: performance.now() - start })+ throw error+ }+}+export function observeRestoreDecode(persister: object, operation: () => PersistedClient, expectedBuster: string, maxAge: number): PersistedClient {+ const admission = reads.get(persister)?.shift()+ const generation = admission?.generation ?? telemetryGeneration()+ const eligible = (reads.has(persister) ? admission?.eligible === true : isTelemetryEligible()) && generation === telemetryGeneration() && isTelemetryEligible()+ const start = performance.now(), id = telemetryId()+ if (eligible) emitTelemetry("cache.restore.start", { request_id: id, phase: "deserialize", start_ms: start })+ try {+ const snapshot = operation()+ const outcome = snapshot.buster !== expectedBuster ? "buster" : Date.now() - snapshot.timestamp > maxAge || !snapshot.timestamp ? "expired" : "hit"+ if (eligible && generation === telemetryGeneration()) {+ emitTelemetry("cache.restore.finish", { request_id: id, phase: "deserialize", outcome, duration_ms: performance.now() - start, count: snapshot.clientState.queries.length })+ if (outcome === "hit") restored.set(persister, { snapshot, start: performance.now(), id: telemetryId(), generation })+ }+ return snapshot+ } catch (error) {+ if (eligible && generation === telemetryGeneration()) emitTelemetry("cache.restore.finish", { request_id: id, phase: "deserialize", outcome: "error", duration_ms: performance.now() - start })+ throw error+ }+}+export function observeHydration(persister: object, client: QueryClient) {+ const evidence = restored.get(persister)+ restored.delete(persister)+ if (!evidence || !isTelemetryEligible() || evidence.generation !== telemetryGeneration()) return+ let count = 0+ emitTelemetry("cache.restore.start", { request_id: evidence.id, start_ms: evidence.start, phase: "hydrate" })+ for (const restoredQuery of evidence.snapshot.clientState.queries) {+ const query = client.getQueryCache().find({ queryKey: restoredQuery.queryKey, exact: true })+ if (!query || query.state.data !== restoredQuery.state.data || query.state.dataUpdatedAt <= 0) continue+ tagValue(client, query.state.data, "restored_idb")+ const key = query.queryKey+ if (key[0] === "community" && key[1] === "db" && Array.isArray(query.state.data)) recordRows(client, String(key[3]), query.state.data, row => String(row.id ?? row.userId ?? row.channelId ?? row.scopeId), "restored_idb")+ count+++ }+ emitTelemetry("cache.restore.finish", { request_id: evidence.id, phase: "hydrate", source: "restored_idb", outcome: count ? "success" : "miss", count, duration_ms: performance.now() - evidence.start })+}+export function discardHydration(persister: object) { restored.delete(persister); reads.delete(persister) }diff --git a/src/web/src/lib/observability/sanitize.test.ts b/src/web/src/lib/observability/sanitize.test.tsnew file mode 100644index 000000000..9dfcd1acd--- /dev/null+++ b/src/web/src/lib/observability/sanitize.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from "vitest"+import type { TransportItem } from "@grafana/faro-web-sdk"+import { sanitizeItem, sanitizeTrace } from "./sanitize"+import { cleanAttributes } from "./schema"+import { routeTemplate } from "./coverage"++const origin = "https://alook.ai", session = "safe-session"+const meta = { sdk: { name: "faro-web", version: "2.12.1", integrations: [{ name: "SECRET", version: "SECRET" }] }, session: { id: session }, page: { url: origin + "/c/invite/SECRET?token=SECRET#SECRET" }, user: { email: "[email protected]", fullName: "SECRET" } }+describe("outbound whitelist", () => {+ it("templates IDs, never exposes query or external arbitrary URLs", () => {+ expect(routeTemplate("/c/invite/SECRET?token=SECRET", origin)).toBe("/c/invite/[token]")+ expect(routeTemplate("/api/community/messages/SECRET/reactions/PRIVATE", origin)).toBe("/api/community/messages/[id]/reactions/[emoji]")+ expect(routeTemplate("https://private.example/SECRET", origin)).toBe("/external")+ expect(routeTemplate("/random/SECRET", origin)).toBe("/unmapped")+ })+ it("drops console text and all arbitrary business attributes", () => {+ expect(sanitizeItem({ type: "log", meta, payload: { message: "SECRET" } } as TransportItem, session, origin)).toBeNull()+ expect(cleanAttributes({ content: "SECRET", filename: "SECRET", token: "SECRET", action_name: "SECRET", route_template: "/c/SECRET" })).toEqual({})+ })+ it("omits absent IDs rather than manufacturing undefined or null receipts", () => {+ expect(cleanAttributes({ ws_event_id: undefined, action_id: null, request_id: "real-receipt" })).toEqual({ request_id: "real-receipt" })+ })+ it("retains the collector-required native SDK contract while rejecting missing or arbitrary SDK metadata", () => {+ const item = { type: "event", meta, payload: { name: "business.result", timestamp: "2026-10-05T00:00:00Z", attributes: { outcome: "success" } } } as TransportItem+ const clean = sanitizeItem(item, session, origin)!+ expect(clean.meta.sdk).toEqual({ name: "faro-web", version: "2.12.1" })+ expect(JSON.stringify(clean)).not.toContain("SECRET")+ for (const sdk of [undefined, { name: "faro-web" }, { name: "SECRET", version: "2.12.1" }, { name: "faro-web", version: "SECRET" }]) {+ expect(sanitizeItem({ ...item, meta: { ...meta, sdk } }, session, origin)).toBeNull()+ }+ })+ it("rebuilds automatic errors and metadata", () => {+ const item = { type: "exception", meta, payload: { type: "TypeError", value: "SECRET", timestamp: "2026-10-05T00:00:00Z", context: { token: "SECRET" }, originalError: new Error("SECRET"), stacktrace: { frames: [+ { filename: origin + "/_next/static/chunks/abcdef.js?token=SECRET", function: "SECRET", lineno: 10 },+ { filename: "https://private.example/SECRET", function: "SECRET" },+ ] } } } as TransportItem+ const clean = sanitizeItem(item, session, origin)+ expect(JSON.stringify(clean)).not.toContain("SECRET")+ expect(JSON.stringify(clean)).not.toContain("[email protected]")+ expect(JSON.stringify(clean)).toContain("/c/invite/[token]")+ expect(sanitizeItem(item, "different-session", origin)).toBeNull()+ })+ it("rebuilds traces, removes events/status messages/attributes and rejects retired spans", () => {+ const span = { traceId: "a".repeat(32), spanId: "b".repeat(16), name: "SECRET", kind: 3, startTimeUnixNano: "1000000000", endTimeUnixNano: "2000000000", status: { code: 2, message: "SECRET" }, events: [{ name: "SECRET" }], links: [{ attributes: "SECRET" }], attributes: [+ { key: "session.id", value: { stringValue: session } },+ { key: "http.url", value: { stringValue: origin + "/api/community/messages/SECRET?token=SECRET" } },+ { key: "authorization", value: { stringValue: "SECRET" } },+ ] }+ const clean = sanitizeTrace({ resourceSpans: [{ resource: { attributes: [{ key: "secret", value: "SECRET" }] }, scopeSpans: [{ scope: { name: "SECRET" }, spans: [span] }] }] }, session, origin)+ expect(JSON.stringify(clean)).not.toContain("SECRET")+ expect(JSON.stringify(clean)).toContain("/api/community/messages/[id]")+ expect(sanitizeTrace({ resourceSpans: [{ scopeSpans: [{ spans: [span] }] }] }, "new-session", origin)).toBeNull()+ })+ it("omits unknown HTTP methods without changing internal or real HTTP span identity", () => {+ const base = { traceId: "a".repeat(32), spanId: "b".repeat(16), name: "dm.message.send", kind: 1, startTimeUnixNano: "1000000000", endTimeUnixNano: "2000000000" }+ const clean = (method?: unknown, legacy = false) => sanitizeTrace({ resourceSpans: [{ scopeSpans: [{ spans: [{+ ...base, attributes: [+ { key: "session.id", value: { stringValue: session } },+ { key: "http.url", value: { stringValue: origin + "/api/community/channels/PRIVATE/messages" } },+ { key: "route_template", value: { stringValue: "/PRIVATE" } },+ ...(method === undefined ? [] : [{ key: legacy ? "http.method" : "http.request.method", value: { stringValue: method } }]),+ ],+ }] }] }] }, session, origin)!.resourceSpans[0]!.scopeSpans[0]!.spans[0]!+ for (const method of [undefined, null, "", "undefined", "PRIVATE", "CONNECT"]) {+ const span = clean(method)+ expect(span.name).toBe("dm.message.send")+ expect(span.kind).toBe(1)+ expect(span.traceId).toBe(base.traceId)+ expect(span.spanId).toBe(base.spanId)+ expect(span.attributes).toContainEqual({ key: "route_template", value: { stringValue: "/api/community/channels/[id]/messages" } })+ expect(JSON.stringify(span)).not.toContain("PRIVATE")+ expect(span.attributes.some(attribute => attribute.key === "http.request.method")).toBe(false)+ }+ for (const legacy of [false, true]) {+ const span = clean("POST", legacy)+ expect(span.attributes).toContainEqual({ key: "http.request.method", value: { stringValue: "POST" } })+ }+ })+ it("accepts installed native HTTP mirror names and rejects old span-start sessions", () => {+ const item = { type: "event", meta, payload: { name: "faro.tracing.fetch", timestamp: "2026-10-05T00:00:00Z", attributes: { "session.id": session, "http.url": origin + "/api/community/messages/SECRET?token=SECRET", "http.method": "PATCH", duration_ns: "2000000" } } } as TransportItem+ const clean = sanitizeItem(item, session, origin)+ expect(clean).not.toBeNull()+ expect(JSON.stringify(clean)).toContain("/api/community/messages/[id]")+ expect(JSON.stringify(clean)).not.toContain("SECRET")+ const old = { ...item, payload: { ...item.payload, attributes: { "session.id": "old-session" } } } as TransportItem+ expect(sanitizeItem(old, session, origin)).toBeNull()+ })++ it("retains only known native action names and finite nonnegative action timings", () => {+ const item = (attributes: Record<string, string>) => ({ type: "event", meta, payload: { name: "faro.user.action", timestamp: "2026-10-05T00:00:00Z", attributes } }) as TransportItem+ const clean = sanitizeItem(item({ userActionName: "ui_interaction", userActionDuration: "12", userActionStartTime: "0", userActionEndTime: "Infinity", private: "SECRET" }), session, origin)!+ expect(clean.payload).toMatchObject({ attributes: { userActionName: "ui_interaction", userActionDuration: "12", userActionStartTime: "0" } })+ expect(JSON.stringify(clean)).not.toContain("Infinity")+ expect(JSON.stringify(clean)).not.toContain("SECRET")+ expect(sanitizeItem(item({ userActionName: "SECRET" }), session, origin)).toBeNull()+ expect(sanitizeItem(item({}), session, origin)).toBeNull()+ })+ it("accepts whitelisted web vitals, rejects arbitrary measurements and invalid stack URLs", () => {+ const measurement = (type: string, values: Record<string, number>) => ({ type: "measurement", meta, payload: { type, timestamp: "2026-10-05T00:00:00Z", values } }) as TransportItem+ expect(sanitizeItem(measurement("web-vitals", { LCP: 10, cls: 0, SECRET: 1, inp: NaN, fcp: -1 }), session, origin)?.payload).toEqual({ type: "web-vitals", timestamp: "2026-10-05T00:00:00Z", values: { LCP: 10, cls: 0 } })+ expect(sanitizeItem(measurement("arbitrary", { LCP: 10 }), session, origin)).toBeNull()+ expect(sanitizeItem(measurement("web-vitals", { SECRET: 1 }), session, origin)).toBeNull()+ const exception = { type: "exception", meta, payload: { type: "Error", value: "SECRET", stacktrace: { frames: [{ filename: "http://[", lineno: 3 }] } } } as TransportItem+ expect(sanitizeItem(exception, session, origin)?.payload).toMatchObject({ value: "[redacted]", stacktrace: { frames: [] } })+ expect(sanitizeItem({ type: "unknown", meta, payload: {} } as unknown as TransportItem, session, origin)).toBeNull()+ })++})diff --git a/src/web/src/lib/observability/sanitize.ts b/src/web/src/lib/observability/sanitize.tsnew file mode 100644index 000000000..a81c66257--- /dev/null+++ b/src/web/src/lib/observability/sanitize.ts@@ -0,0 +1,114 @@+import type { TransportItem, EventEvent, ExceptionEvent, MeasurementEvent, TraceEvent } from "@grafana/faro-web-sdk"+import { actionNames, routeTemplate } from "./coverage"+import { cleanAttributes, eventNames } from "./schema"++const actions = new Set<string>(actionNames)+const events = new Set<string>([...eventNames, "session_start", "session_resume", "session_extend", "faro.user.action", "faro.tracing.fetch", "faro.tracing.xml-http-request"])+const errors = new Set(["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "URIError", "AbortError", "DOMException"])+const numeric = (value: unknown) => typeof value === "number" && Number.isFinite(value) && value >= 0+const record = (value: unknown): Record<string, unknown> => value && typeof value === "object" ? value as Record<string, unknown> : {}+const array = (value: unknown): unknown[] => Array.isArray(value) ? value : []+const hex = (value: unknown, size: number) => typeof value === "string" && new RegExp("^[0-9a-f]{" + size + "}$").test(value) ? value : undefined+const nano = (value: unknown) => typeof value === "string" && /^\d{1,22}$/.test(value) ? value : undefined++export function sanitizeTrace(input: unknown, sessionId: string, origin: string) {+ const resources = array(record(input).resourceSpans).flatMap(resource => {+ const scopes = array(record(resource).scopeSpans).flatMap(scope => {+ const spans = array(record(scope).spans).flatMap(raw => {+ const span = record(raw)+ const fields = Object.fromEntries(array(span.attributes).map(rawAttribute => {+ const attribute = record(rawAttribute)+ const value = record(attribute.value)+ return [String(attribute.key), value.stringValue ?? value.intValue ?? value.doubleValue]+ }))+ if (fields["session.id"] !== sessionId) return []+ const url = String(fields["url.full"] ?? fields["http.url"] ?? "")+ const rawMethod = fields["http.request.method"] ?? fields["http.method"]+ const method = typeof rawMethod === "string" && ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"].includes(rawMethod) ? rawMethod : undefined+ const template = cleanAttributes({ route_template: fields.route_template }).route_template ?? routeTemplate(url, origin)+ const attributes = cleanAttributes({ ...fields, route_template: template, session_id: sessionId })+ for (const key of ["http.status_code", "http.response.status_code"]) {+ if (numeric(Number(fields[key])) && Number(fields[key]) <= 599) attributes[key] = String(fields[key])+ }+ if (method !== undefined) attributes["http.request.method"] = method+ attributes["session.id"] = sessionId+ const traceId = hex(span.traceId, 32), spanId = hex(span.spanId, 16)+ const startTimeUnixNano = nano(span.startTimeUnixNano), endTimeUnixNano = nano(span.endTimeUnixNano)+ if (!traceId || !spanId || !startTimeUnixNano || !endTimeUnixNano) return []+ return [{+ traceId, spanId, parentSpanId: hex(span.parentSpanId, 16),+ name: actions.has(String(span.name)) ? String(span.name) : (method ? method + " " : "") + String(template),+ kind: (Number(span.kind) >= 0 && Number(span.kind) <= 5 ? Number(span.kind) : 0) as 0 | 1 | 2 | 3 | 4 | 5,+ startTimeUnixNano,+ endTimeUnixNano,+ attributes: Object.entries(attributes).map(([key,value]) => ({ key, value: { stringValue: value } })),+ status: { code: (Number(record(span.status).code) === 2 ? 2 : 0) as 0 | 2 },+ droppedAttributesCount: 0, droppedEventsCount: 0, droppedLinksCount: 0,+ events: [], links: [],+ }]+ })+ return spans.length ? [{ scope: { name: "alook.frontend" }, spans }] : []+ })+ return scopes.length ? [{ resource: { attributes: [{ key: "service.name", value: { stringValue: "alook-web" } }], droppedAttributesCount: 0 }, scopeSpans: scopes }] : []+ })+ return resources.length ? { resourceSpans: resources } : null+}++export function sanitizeItem(item: TransportItem, sessionId: string, origin: string): TransportItem | null {+ if (item.meta.session?.id !== sessionId) return null+ const sdk = item.meta.sdk+ if (sdk?.name !== "faro-web" || !/^\d{1,3}\.\d{1,3}\.\d{1,3}(?:-[a-zA-Z0-9.-]{1,32})?$/.test(sdk.version ?? "")) return null+ const meta = {+ sdk: { name: sdk.name, version: sdk.version },+ app: { name: "alook-web", version: item.meta.app?.release, ...cleanAttributes({ release: item.meta.app?.release, environment: item.meta.app?.environment }) },+ session: { id: sessionId, attributes: { isSampled: "true" } },+ page: { id: item.meta.page?.id, url: origin + routeTemplate(item.meta.page?.url ?? "/", origin) },+ ...(item.meta.user?.id && /^[a-zA-Z0-9_-]{8,64}$/.test(item.meta.user.id) ? { user: { id: item.meta.user.id } } : {}),+ }+ if (item.type === "log") return null+ if (item.type === "event") {+ const payload = item.payload as EventEvent+ if (!events.has(payload.name)) return null+ if (payload.name.startsWith("faro.tracing.") && payload.attributes?.["session.id"] !== sessionId) return null+ if (payload.attributes?.session_id && payload.attributes.session_id !== sessionId) return null+ const attrs = cleanAttributes(payload.attributes ?? {})+ if (payload.name.startsWith("faro.tracing.")) {+ const fields = payload.attributes ?? {}+ const url = String(fields["url.full"] ?? fields["http.url"] ?? "")+ let kind = "unknown"+ try { const parsed = new URL(url, origin); kind = parsed.origin !== origin ? "external" : parsed.searchParams.has("_rsc") ? "rsc" : parsed.pathname.startsWith("/api/") ? "api" : "resource" } catch {}+ Object.assign(attrs, cleanAttributes({ route_template: routeTemplate(url, origin), request_kind: kind, duration_ms: Number(fields.duration_ns) / 1e6, method: fields["http.request.method"] ?? fields["http.method"], status: fields["http.response.status_code"] ?? fields["http.status_code"], session_id: sessionId }))+ }+ if (payload.name === "faro.user.action") {+ const name = payload.attributes?.["userActionName"]+ if (!name || !actions.has(name)) return null+ attrs.userActionName = name+ for (const field of ["userActionDuration", "userActionStartTime", "userActionEndTime"]) {+ const value = Number(payload.attributes?.[field])+ if (numeric(value)) attrs[field] = String(value)+ }+ }+ return { ...item, meta, payload: { name: payload.name, timestamp: payload.timestamp, domain: "alook.frontend", attributes: attrs, ...(payload.trace && hex(payload.trace.trace_id, 32) && hex(payload.trace.span_id, 16) ? { trace: payload.trace } : {}) } }+ }+ if (item.type === "exception") {+ const payload = item.payload as ExceptionEvent+ return { ...item, meta, payload: { timestamp: payload.timestamp, type: errors.has(payload.type) ? payload.type : "Error", value: "[redacted]", stacktrace: { frames: (payload.stacktrace?.frames ?? []).slice(0,20).flatMap(frame => {+ try {+ const url = new URL(frame.filename, origin)+ if (url.origin !== origin || !/^\/(?:blog-static\/)?_next\/static\/[a-zA-Z0-9_./-]+\.js$/.test(url.pathname)) return []+ return [{ filename: origin + url.pathname, function: "[redacted]", ...(numeric(frame.lineno) ? { lineno: frame.lineno } : {}), ...(numeric(frame.colno) ? { colno: frame.colno } : {}) }]+ } catch { return [] }+ }) } } }+ }+ if (item.type === "measurement") {+ const payload = item.payload as MeasurementEvent+ if (payload.type !== "web-vitals") return null+ const values = Object.fromEntries(Object.entries(payload.values).filter(([key,value]) => /^(LCP|CLS|INP|FCP|TTFB|FID|lcp|cls|inp|fcp|ttfb|fid)$/.test(key) && numeric(value)))+ return Object.keys(values).length ? { ...item, meta, payload: { type: payload.type, timestamp: payload.timestamp, values } } : null+ }+ if (item.type === "trace") {+ const payload = sanitizeTrace(item.payload, sessionId, origin)+ return payload ? { ...item, meta, payload: payload as TraceEvent } : null+ }+ return null+}diff --git a/src/web/src/lib/observability/schema.ts b/src/web/src/lib/observability/schema.tsnew file mode 100644index 000000000..f735d5fe6--- /dev/null+++ b/src/web/src/lib/observability/schema.ts@@ -0,0 +1,56 @@+import { actionNames, apiRoutes, pageRoutes } from "./coverage"++export const eventNames = [+ "action.start", "action.finish", "navigation.intent", "navigation.commit", "navigation.ready",+ "cache.restore.start", "cache.restore.finish", "region.read",+ "region.ready_commit", "region.frame_estimate", "request.start", "request.headers",+ "request.body_parsed", "request.finish", "data.publish", "data.response_rejected",+ "ws.connect", "ws.ready", "ws.close", "ws.reconnect", "ws.event_applied",+ "resource.finish", "main_thread.longtask", "telemetry.coverage", "telemetry.drop", "business.result", "message.milestone",+] as const+export type TelemetryEvent = typeof eventNames[number]+export type Attributes = Record<string, string | number | boolean | undefined>+export type Source = "restored_idb" | "network" | "ws" | "local_mutation" | "mixed" | "unknown"++const names = new Set<string>(actionNames)+const routes = new Set<string>([...pageRoutes, ...apiRoutes, "/external", "/unmapped", "/_next/resource"])+const enumValues: Record<string, ReadonlySet<string>> = Object.fromEntries(Object.entries({+ environment: ["production", "qa"],+ frontend_surface: ["web", "blog", "webview"],+ navigation_kind: ["document", "route"],+ phase: ["intent", "headers", "body", "read", "primary", "background", "hydrate", "idb_read", "deserialize", "commit", "frame", "interaction", "optimistic", "ack", "upload", "transport", "auth", "token", "validation"],+ outcome: ["success", "error", "cancelled", "superseded", "timeout", "noop", "observed", "unknown", "empty", "miss", "hit", "expired", "buster", "rejected", "disabled", "unavailable", "partial"],+ source: ["restored_idb", "network", "ws", "local_mutation", "mixed", "unknown"],+ freshness: ["restored", "validated", "changed", "unknown"],+ eligibility: ["eligible", "rejected", "unknown", "denied"],+ request_reason: ["foreground", "background", "restore_invalidate", "pagination", "command", "router", "unknown"],+ request_kind: ["api", "rsc", "resource", "document", "external", "unknown"],+ method: ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],+ region: ["shell", "rail", "sidebar", "messages", "forum", "thread_opener", "friends", "bots", "machines", "members", "settings", "calendar", "billing", "workspaces", "files", "file_preview", "traces", "trace_detail", "agents", "issues", "email", "chat", "runtimes", "inbox", "activity", "meetings", "email_body", "issue_detail", "page"],+ visibility: ["visible", "hidden", "unknown"],+ capability: ["available", "limited", "unavailable"],+ drop_reason: ["early_queue_full", "transport_failure", "withdrawal", "account_switch", "stale_session", "sdk_load", "invalid_config", "unload_unknown"],+ delivery_failure_reason: ["queue_full", "retries_exhausted", "rate_limit", "http_error", "network", "timeout", "abort", "unknown"],+ cache_stage: ["idb", "query", "router", "http", "canonical"],+}).map(([key, values]) => [key, new Set(values)]))+const numberFields = new Set(["start_ms", "duration_ms", "ws_duration_ms", "count", "row_count", "changed_count", "removed_count", "status", "schema_version", "revision", "attempt", "collection_rate", "drop_count", "delivery_failure_count", "transfer_bytes", "encoded_bytes", "decoded_bytes"])+const idFields = new Set(["ws_event_id", "session_id", "page_instance_id", "action_id", "navigation_id", "request_id", "data_version", "user_key"])++export function cleanAttributes(input: Record<string, unknown>): Record<string, string> {+ const result: Record<string, string> = {}+ for (const [key, value] of Object.entries(input)) {+ if (value === undefined || value === null) continue+ const text = String(value)+ if (enumValues[key]?.has(text)) result[key] = text+ else if (numberFields.has(key) && value !== undefined && text.trim() !== "" && Number.isFinite(Number(value)) && Number(value) >= 0 && Number(value) <= 1e15) result[key] = text+ else if (idFields.has(key) && /^[a-zA-Z0-9_-]{1,80}$/.test(text)) result[key] = text+ else if (key === "release" && /^[0-9a-f]{40}$/.test(text)) result[key] = text+ else if (key === "route_template" && routes.has(text)) result[key] = text+ else if (key === "action_name" && names.has(text)) result[key] = text+ else if (key === "cf_ray" && /^[0-9a-f]{16}-[A-Z]{3}$/.test(text)) result[key] = text+ else if (key === "trace_id" && /^[0-9a-f]{32}$/.test(text)) result[key] = text+ else if (key === "span_id" && /^[0-9a-f]{16}$/.test(text)) result[key] = text+ else if (key === "event_type" && /^(community:|connection\.|auth\.)[a-z_.]{1,50}$/.test(text)) result[key] = text+ }+ return result+}diff --git a/src/web/src/lib/observability/telemetry.ts b/src/web/src/lib/observability/telemetry.tsnew file mode 100644index 000000000..0ea4d74ff--- /dev/null+++ b/src/web/src/lib/observability/telemetry.ts@@ -0,0 +1,75 @@+import { cleanAttributes, type Attributes, type TelemetryEvent } from "./schema"++type RecordEvent = { name: TelemetryEvent; attributes: Record<string, string>; timestamp: number }+type Sink = (event: RecordEvent) => void+let eligible = false+let sink: Sink | undefined+let queue: RecordEvent[] = []+let dropped = 0+let generation = 0+let nativeContinuationFrom = -1+let base: Record<string, string> = {}+const LIMIT = 256+let revision = 0+const listeners = new Set<() => void>()+let notificationPending = false+export function observationSnapshot() { return revision }+export function subscribeObservation(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener) } }+export function notifyObservation() {+ revision+++ if (notificationPending) return+ notificationPending = true+ queueMicrotask(() => { notificationPending = false; for (const listener of listeners) listener() })+}++export function isTelemetryEligible() { return eligible }+export function telemetryGeneration() { return generation }+export function configureTelemetry(attributes: Attributes, enabled: boolean) {+ base = cleanAttributes(attributes)+ eligible = enabled+ notifyObservation()+}+export function alignInitialTelemetrySession(previous: string, next: string) {+ if (!eligible || sink || base.session_id !== previous || !/^[a-zA-Z0-9_-]{1,80}$/.test(next) || queue.some(event => event.attributes.session_id !== previous)) return false+ base = { ...base, session_id: next }+ queue = queue.map(event => ({ ...event, attributes: { ...event.attributes, session_id: next } }))+ notifyObservation()+ return true+}+export function linkQueuedActionTrace(actionId: string, ownerGeneration: number, traceId: Attributes["trace_id"], spanId: Attributes["span_id"]) {+ if (!eligible || sink || ownerGeneration !== generation) return+ const fields = cleanAttributes({ trace_id: traceId, span_id: spanId })+ if (!fields.trace_id || !fields.span_id) return+ queue = queue.map(event => event.attributes.action_id === actionId ? { ...event, attributes: { ...event.attributes, ...fields } } : event)+}+export function retireTelemetry(reason: "boundary" | "native_session" = "boundary") {+ eligible = false+ nativeContinuationFrom = reason === "native_session" ? generation : -1+ generation+++ queue = []+ sink = undefined+ dropped = 0+ notifyObservation()+}+export function isNativeSessionContinuation(original: number) { return eligible && nativeContinuationFrom === original }+export function emitTelemetry(name: TelemetryEvent, attributes: Attributes = {}) {+ if (!eligible) return+ const event = { name, attributes: cleanAttributes({ ...base, ...attributes, schema_version: 1 }), timestamp: Date.now() }+ if (sink) { try { sink(event) } catch { dropped++ } }+ else if (queue.length < LIMIT) queue.push(event)+ else dropped+++}+export function installTelemetrySink(next: Sink) {+ if (!eligible) return+ sink = next+ const pending = queue+ queue = []+ for (const event of pending) { try { next(event) } catch { dropped++ } }+ reportTelemetryDrops()+}+export function reportTelemetryDrops(reason: Attributes["drop_reason"] = "early_queue_full") {+ if (!eligible || !sink || dropped === 0) return+ const count = dropped+ dropped = 0+ emitTelemetry("telemetry.drop", { drop_count: count, drop_reason: reason })+}diff --git a/src/web/src/lib/observability/virtual-window.dom.test.tsx b/src/web/src/lib/observability/virtual-window.dom.test.tsxnew file mode 100644index 000000000..b16dccd61--- /dev/null+++ b/src/web/src/lib/observability/virtual-window.dom.test.tsx@@ -0,0 +1,114 @@+import { useCallback, useLayoutEffect, useRef } from "react"+import { useVirtualizer, type ReactVirtualizer } from "@tanstack/react-virtual"+import { afterEach, beforeEach, expect, it, vi } from "vitest"+import { act, fireEvent, render, waitFor } from "@/test/react-dom-harness"+import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "@/hooks/community/virtualizer-react-options"+import { VirtualRows } from "@/components/community/messages/virtual-cursor-list"+import { tagView, type Evidence } from "./data-source"+import { useObservedRegion, windowEvidence } from "./regions"+import { configureTelemetry, installTelemetrySink, retireTelemetry } from "./telemetry"+import { visibleVirtualItems } from "./virtual-window"++vi.mock("next/navigation", () => ({ usePathname: () => "/", useSearchParams: () => new URLSearchParams() }))+const events: Array<{ name: string; attributes: Record<string, string> }> = []+const observers = new Map<Element, ResizeObserverCallback>()+let height: number+let native: ReactVirtualizer<HTMLDivElement, Element>+let mounted: ReturnType<typeof render> | undefined+type Row = { id: string }+function WindowPanel({ rows, overscan, attached = true }: { rows: Row[]; overscan: number; attached?: boolean }) {+ const root = useRef<HTMLDivElement | null>(null)+ const bind = useCallback((element: HTMLDivElement | null) => {+ root.current = element+ if (!element) return+ Object.defineProperties(element, {+ clientHeight: { configurable: true, get: () => height },+ offsetHeight: { configurable: true, get: () => height },+ offsetWidth: { configurable: true, value: 320 },+ scrollHeight: { configurable: true, value: 2000 },+ scrollTo: { configurable: true, value: ({ top }: ScrollToOptions) => { element.scrollTop = top ?? 0 } },+ })+ }, [])+ // eslint-disable-next-line react-hooks/incompatible-library -- native Virtual regression+ const virtualizer = useVirtualizer({+ ...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,+ count: rows.length, getScrollElement: () => root.current,+ estimateSize: () => 100, measureElement: () => 100,+ getItemKey: index => rows[index]!.id, overscan,+ initialRect: { width: 320, height: 800 }, initialOffset: 500,+ })+ useLayoutEffect(() => { native = virtualizer })+ const selected = visibleVirtualItems(virtualizer).map(item => rows[item.index]!)+ useObservedRegion("messages", selected.length > 0, windowEvidence(selected, rows))+ return attached ? <div ref={bind} data-testid="viewport"><VirtualRows items={rows} virtualizer={virtualizer} itemKey={row => row.id} renderItem={row => <p>{row.id}</p>} /></div> : null+}+function rows() {+ return Array.from({ length: 20 }, (_, index) => tagView({ id: "row-" + index }, {+ source: "network", version: String(index), freshness: "changed", count: 1,+ }))+}+const ready = () => events.filter(event => event.name === "region.ready_commit")+const indexes = () => visibleVirtualItems(native).map(item => item.index)+beforeEach(() => {+ height = 200; events.length = 0; observers.clear()+ vi.stubGlobal("ResizeObserver", class {+ constructor(private callback: ResizeObserverCallback) {}+ observe(element: Element) { observers.set(element, this.callback) }+ unobserve(element: Element) { observers.delete(element) }+ disconnect() { observers.clear() }+ })+ configureTelemetry({ session_id: "window-session" }, true)+ installTelemetrySink(event => events.push(event))+})+afterEach(async () => {+ await act(async () => { mounted?.unmount(); mounted = undefined; retireTelemetry() })+ vi.unstubAllGlobals()+})++it.each([8, 5])("excludes mounted overscan %s from source, version and WS receipt until it enters the viewport", async overscan => {+ const values = rows()+ const ws: Evidence = { source: "ws", version: "ws-outside", freshness: "changed", count: 1, wsEventId: "outside-receipt", wsStart: performance.now() }+ values[8] = tagView({ id: "row-8" }, ws)+ mounted = render(<WindowPanel rows={values} overscan={overscan} />)+ await waitFor(() => expect(ready().at(-1)?.attributes.row_count).toBe("2"))+ expect(indexes()).toEqual([5, 6])+ expect(native.getVirtualItems().some(item => item.index === 8)).toBe(true)+ expect(mounted.getByText("row-8")).toBeInTheDocument()+ expect(ready().at(-1)!.attributes).toMatchObject({ source: "network", row_count: "2" })+ expect(ready().at(-1)!.attributes.ws_event_id).toBeUndefined()+ const initialVersion = ready().at(-1)!.attributes.data_version+ values[8] = tagView({ id: "row-8" }, { ...ws, version: "ws-outside-new", wsEventId: "new-outside-receipt" })+ mounted.rerender(<WindowPanel rows={values} overscan={overscan} />)+ expect(ready()).toHaveLength(1)+ expect(ready()[0]!.attributes.data_version).toBe(initialVersion)+ const viewport = mounted.getByTestId("viewport")+ await act(async () => { viewport.scrollTop = 650; fireEvent.scroll(viewport) })+ await waitFor(() => expect(indexes()).toEqual([6, 7, 8]))+ expect(ready().at(-1)!.attributes).toMatchObject({ source: "mixed", row_count: "3", ws_event_id: "new-outside-receipt" })+ expect(ready().at(-1)!.attributes.data_version).not.toBe(initialVersion)+ await act(async () => {+ height = 50+ observers.get(viewport)!([], {} as ResizeObserver)+ })+ await waitFor(() => expect(indexes()).toEqual([6]))+ expect(ready().at(-1)!.attributes).toMatchObject({ source: "network", row_count: "1" })+ expect(ready().at(-1)!.attributes.ws_event_id).toBeUndefined()+})++it("counts partial rows and excludes rows touching only an outside boundary", async () => {+ mounted = render(<WindowPanel rows={rows()} overscan={8} />)+ await waitFor(() => expect(indexes()).toEqual([5, 6]))+ const viewport = mounted.getByTestId("viewport")+ await act(async () => { viewport.scrollTop = 550; fireEvent.scroll(viewport) })+ await waitFor(() => expect(indexes()).toEqual([5, 6, 7]))+ await act(async () => { viewport.scrollTop = 600; fireEvent.scroll(viewport) })+ await waitFor(() => expect(indexes()).toEqual([6, 7]))+})++it.each(["unattached", "zero-height"])("does not certify the initialRect as a %s viewport", async mode => {+ if (mode === "zero-height") height = 0+ mounted = render(<WindowPanel rows={rows()} overscan={5} attached={mode !== "unattached"} />)+ await act(async () => {})+ expect(indexes()).toEqual([])+ expect(ready()).toEqual([])+})diff --git a/src/web/src/lib/observability/virtual-window.ts b/src/web/src/lib/observability/virtual-window.tsnew file mode 100644index 000000000..f8f7677a6--- /dev/null+++ b/src/web/src/lib/observability/virtual-window.ts@@ -0,0 +1,11 @@+import type { Virtualizer } from "@tanstack/react-virtual"++type VirtualWindow = Pick<Virtualizer<Element, Element>, "getVirtualItems" | "scrollElement" | "scrollOffset">++export function visibleVirtualItems(virtualizer: VirtualWindow) {+ const root = virtualizer.scrollElement+ const start = virtualizer.scrollOffset+ if (!root || start === null || !Number.isFinite(start) || root.clientHeight <= 0) return []+ const end = start + root.clientHeight+ return virtualizer.getVirtualItems().filter(item => item.end > start && item.start < end)+}diff --git a/src/web/src/lib/query-client.ts b/src/web/src/lib/query-client.tsindex 19d094b1e..0cf90d282 100644--- a/src/web/src/lib/query-client.ts+++ b/src/web/src/lib/query-client.ts@@ -1,5 +1,6 @@import { QueryClient } from "@tanstack/react-query"import { PERSIST_MAX_AGE_MS } from "@/lib/query-persister"+import { observeQueryClient } from "@/lib/observability/query-observer"/*** Factory for a QueryClient with app defaults.@@ -16,7 +17,7 @@ import { PERSIST_MAX_AGE_MS } from "@/lib/query-persister"* caches for anything the user hasn't touched in the current session.*/export function createQueryClient(): QueryClient {- return new QueryClient({+ return observeQueryClient(new QueryClient({defaultOptions: {queries: {staleTime: 5_000,@@ -25,5 +26,5 @@ export function createQueryClient(): QueryClient {retry: 1,},},- })+ }))}diff --git a/src/web/src/lib/query-persister.ts b/src/web/src/lib/query-persister.tsindex 08454b635..586939406 100644--- a/src/web/src/lib/query-persister.ts+++ b/src/web/src/lib/query-persister.ts@@ -1,4 +1,5 @@import { clearLegacyChatCaches, getLegacyChatCacheSizeBytes } from "@/lib/legacy-chat-persistence"+import { observeRestoreRead, observeRestoreDecode } from "@/lib/observability/restore"import { createStore as createNativeStore } from "@tanstack/store"import { scrubApplicationClient } from "@/lib/workspace-chat-persistence"import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister"@@ -361,10 +362,10 @@ export function createIdbPersister(userId: string | null, domain: PersistDomainvoid eligibility.catch(() => undefined)const persister = createAsyncStoragePersister({storage: {- getItem: () => withEligiblePersister(key, userId, eligibility, "readonly", null, async (store) => {+ getItem: () => observeRestoreRead(() => withEligiblePersister(key, userId, eligibility, "readonly", null, async (store) => {const value = await promisifyRequest<unknown>(store.get(key))return typeof value === "string" ? value : null- }),+ }), persister),setItem: (_k: string, value: string) => withEligiblePersister(key, userId, eligibility, "readwrite", undefined, async (store) => { store.put(value, key) },),@@ -376,7 +377,7 @@ export function createIdbPersister(userId: string | null, domain: PersistDomain},key: "alook-query-cache",serialize: (client) => JSON.stringify(domain === "application" ? scrubApplicationClient(client, userId) : scrubDehydratedClient(client, userId)),- deserialize: (raw) => domain === "application" ? scrubApplicationClient(JSON.parse(raw) as PersistedClient, userId) : scrubDehydratedClient(JSON.parse(raw) as PersistedClient, userId),+ deserialize: (raw) => observeRestoreDecode(persister, () => domain === "application" ? scrubApplicationClient(JSON.parse(raw) as PersistedClient, userId) : scrubDehydratedClient(JSON.parse(raw) as PersistedClient, userId), domain === "application" ? PERSIST_BUSTER + "-application" : PERSIST_BUSTER, PERSIST_MAX_AGE_MS),})return Object.assign(persister, {isCurrent: () => withEligiblePersister(key, userId, eligibility, "readonly", false, async () => true),diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.tsindex 99740d70d..33b4ac4bb 100644--- a/src/web/src/lib/use-user-ws.ts+++ b/src/web/src/lib/use-user-ws.ts@@ -1,4 +1,5 @@"use client"+import { emitTelemetry, isTelemetryEligible, telemetryGeneration } from "@/lib/observability/telemetry"import { useEffect, useRef, useCallback } from "react"import {COMMUNITY_BROWSER_EVENT_BATCH_MAX_BYTES,@@ -50,6 +51,7 @@ type PendingTokenAttempt = {generation: numberstartedAt: numberreported: boolean+ observationGeneration: number}function isPageHidden(): boolean {@@ -233,11 +235,14 @@ export function useUserWs(requestDaemonStatusOnAuthRef.current = options?.requestDaemonStatusOnAuth ?? true}, [options?.requestDaemonStatusOnAuth])+ const observedSockets = useRef(new WeakMap<WebSocket, { generation: number; start: number }>())const connectRef = useRef<(() => Promise<void>) | null>(null)const publishConnectionPhase = useCallback((phase: UserWsConnectionPhase) => {if (lastConnectionPhaseRef.current === phase) returnlastConnectionPhaseRef.current = phase+ const observed = wsRef.current ? observedSockets.current.get(wsRef.current) : undefined+ if (phase === "authenticated" && observed?.generation === telemetryGeneration()) emitTelemetry("ws.ready", { phase: "auth", outcome: "success", duration_ms: performance.now() - observed.start })runLifecycleCallback("connection-state", () =>onConnectionStateChangeRef.current?.(phase))}, [])@@ -273,6 +278,7 @@ export function useUserWs() => {if (attempt.reported) returnattempt.reported = true+ if (attempt.observationGeneration === telemetryGeneration()) emitTelemetry("ws.connect", { phase: "token", outcome: result === "success" ? "success" : result === "aborted" ? "cancelled" : result === "timeout" ? "timeout" : "error", duration_ms: boundedDurationMs(attempt.startedAt) })trackCommunityWsLifecycleStage({stage: "token",result,@@ -317,6 +323,8 @@ export function useUserWs(: "remote")if (!reportedCloseSocketsRef.current.has(ws)) {reportedCloseSocketsRef.current.add(ws)+ const observed = observedSockets.current.get(ws)+ if (observed?.generation === telemetryGeneration()) emitTelemetry("ws.close", { phase: "transport", outcome: "observed", duration_ms: performance.now() - observed.start, status: code })trackCommunityWsLifecycleClose({initiator,code,@@ -453,6 +461,7 @@ export function useUserWs(const attempt = reconnectAttemptRef.current + 1reconnectAttemptRef.current = attemptreconnectDelay.current = Math.min(windowMs * 2, WS_RECONNECT_MAX)+ emitTelemetry("ws.reconnect", { phase: "transport", attempt, duration_ms: delayMs, outcome: "observed" })trackCommunityWsRetryScheduled({ attempt, delayMs, windowMs })reconnectTimerRef.current = setTimeout(() => {reconnectTimerRef.current = null@@ -495,7 +504,9 @@ export function useUserWs(generation,startedAt: Date.now(),reported: false,+ observationGeneration: telemetryGeneration(),}+ if (isTelemetryEligible()) emitTelemetry("ws.connect", { phase: "token", start_ms: performance.now(), outcome: "observed" })pendingTokenRef.current = tokenAttemptlet tokenTimedOut = falsetokenTimeoutRef.current = setTimeout(() => {@@ -610,6 +621,8 @@ export function useUserWs(scheduleReconnect(generation)return}+ observedSockets.current.set(ws, { generation: tokenAttempt.observationGeneration, start: performance.now() })+ if (tokenAttempt.observationGeneration === telemetryGeneration()) emitTelemetry("ws.connect", { phase: "transport", outcome: "observed" })wsRef.current = wsconnectStartedAtRef.current = Date.now()connectTimeoutRef.current = setTimeout(() => {diff --git a/src/web/src/stores/community/message-stream-store.ts b/src/web/src/stores/community/message-stream-store.tsindex e1a267cdd..73869ca35 100644--- a/src/web/src/stores/community/message-stream-store.ts+++ b/src/web/src/stores/community/message-stream-store.ts@@ -1,3 +1,5 @@+import { sourceEvidence } from "@/lib/observability/data-source"+import { beginMessageObservation, messageMilestone, disposeMessageObservations } from "@/lib/observability/messages"import { createStore } from "@tanstack/store"import {getOutboxRetryPayload,@@ -42,7 +44,7 @@ function executeEffects(effects: ReturnType<typeof reduceMessageOverlay>["effectfor (const effect of effects) URL.revokeObjectURL(effect.url)}-export function createMessageStreamStore(readMessages: () => ReadonlyMap<string, CanonicalMessage> = () => new Map()) {+export function createMessageStreamStore(readMessages: () => ReadonlyMap<string, CanonicalMessage> = () => new Map(), diagnosticOwner?: object) {return createStore({ entries: new Map<string, ScopeEntry>() as ReadonlyMap<string, ScopeEntry>, nextOrdinal: 1 }, ({ setState, get }): Omit<MessageStreamStoreState, "entries" | "nextOrdinal"> => ({accept: (scope, intent) => {@@ -54,10 +56,12 @@ export function createMessageStreamStore(readMessages: () => ReadonlyMap<string,type: "submit",intent: { ...intent, localOrdinal: current.nextOrdinal },})+ beginMessageObservation(diagnosticOwner, intent.nonce, scope.kind)const entries = new Map(current.entries)entries.set(key, { scope, state: storeOverlay(transition.state) })setState((state) => ({ ...state, ...{ entries, nextOrdinal: current.nextOrdinal + 1 } }))executeEffects(transition.effects)+ messageMilestone(diagnosticOwner, intent.nonce, "optimistic", "success")return true},@@ -65,13 +69,23 @@ export function createMessageStreamStore(readMessages: () => ReadonlyMap<string,const key = messageScopeKey(scope)const current = get()const overlay = hydrate(current.entries.get(key)?.state ?? EMPTY_STORED, readMessages())- const transition = reduceMessageOverlay(overlay, event.type === "postAck" ? { type: "wsMessage", message: { ...event.message, clientNonce: event.nonce } } : event)+ if (event.type === "retry" && overlay.outboxByNonce.has(event.nonce)) beginMessageObservation(diagnosticOwner, event.nonce, scope.kind)+ const applied = event.type === "postAck" ? { type: "wsMessage" as const, message: { ...event.message, clientNonce: event.nonce } } : event+ if (applied.type === "wsMessage") sourceEvidence(applied.message, event.type === "postAck" ? "network" : "ws")+ const transition = reduceMessageOverlay(overlay, applied)if (transition.state !== overlay) {const entries = new Map(current.entries)entries.set(key, { scope, state: storeOverlay(transition.state) })setState((state) => ({ ...state, ...{ entries } }))}executeEffects(transition.effects)+ if (transition.state !== overlay && "nonce" in event) {+ const phase = event.type.startsWith("upload") ? "upload" : event.type === "retry" ? "optimistic" : "ack"+ const failed = ["uploadFailed", "postFail", "terminalReject"].includes(event.type)+ messageMilestone(diagnosticOwner, event.nonce, phase, failed ? "error" : "success", failed || event.type === "postAck")+ } else if (transition.state !== overlay && event.type === "wsMessage" && event.message.clientNonce) {+ messageMilestone(diagnosticOwner, event.message.clientNonce, "ack", "success", true)+ }},getRetryPayload: (scope, nonce) => {@@ -112,6 +126,7 @@ export function createMessageStreamStore(readMessages: () => ReadonlyMap<string,reduceMessageOverlay(hydrate(entry.state, readMessages()), { type: "clear" }).effects)setState((state) => ({ ...state, ...{ entries: new Map(), nextOrdinal: 1 } }))executeEffects(effects)+ if (diagnosticOwner) disposeMessageObservations(diagnosticOwner)},overlayFor: (scope) => hydrate(get().entries.get(messageScopeKey(scope))?.state ?? EMPTY_STORED, readMessages()),}))diff --git a/src/web/src/stores/community/message-stream.test.ts b/src/web/src/stores/community/message-stream.test.tsindex 9b784447f..9788cab99 100644--- a/src/web/src/stores/community/message-stream.test.ts+++ b/src/web/src/stores/community/message-stream.test.ts@@ -1,5 +1,7 @@import { createMessageStreamStore } from "./message-stream"+import { configureTelemetry, installTelemetrySink, retireTelemetry } from "@/lib/observability/telemetry"+import { clearActions } from "@/lib/observability/context"const nativeStore = createMessageStreamStore()import { beforeEach, describe, expect, it, vi } from "vitest"import type { MessageScope } from "@/lib/community/message-stream"@@ -66,4 +68,21 @@ describe("message stream store", () => {expect(URL.revokeObjectURL).toHaveBeenCalledTimes(1)})+ it("finishes the original send observation when a websocket echo acknowledges its client nonce", () => {+ const owner = {}, store = createMessageStreamStore(() => new Map(), owner)+ const events: Array<{ name: string; attributes: Record<string, string> }> = []+ configureTelemetry({ session_id: "message-session" }, true)+ installTelemetrySink(event => events.push(event))+ try {+ store.actions.accept(channel("c1"), { ...acceptedIntent("private-nonce"), message: { type: "chat", content: "private-body", authorId: "viewer-a" } })+ store.actions.dispatch(channel("c1"), { type: "wsMessage", message: { id: "message-a", seq: 1, type: "chat", content: "private-body", authorId: "viewer-a", clientNonce: "private-nonce" } })+ expect(store.get().entries.get("channel:c1")?.state.outboxByNonce.size).toBe(0)+ expect(events.filter(event => event.name === "action.finish")).toHaveLength(1)+ expect(events.filter(event => event.name === "message.milestone").map(event => event.attributes.phase)).toEqual(["optimistic", "ack"])+ const started = events.find(event => event.name === "action.start")!+ expect(events.filter(event => event.name === "message.milestone").every(event => event.attributes.action_id === started.attributes.action_id)).toBe(true)+ expect(JSON.stringify(events)).not.toMatch(/private-(?:nonce|body)/)+ } finally { store.actions.resetAll(); retireTelemetry(); clearActions() }+ })+})diff --git a/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.ts b/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.tsindex 9ba27e806..b6cea5bd5 100644--- a/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.ts+++ b/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.ts@@ -151,6 +151,22 @@ async function settledRailMetrics(page: Page, finalMessageId?: string): Promise<return settled!}+async function setSettledViewport(+ page: Page,+ width: number,+ height: number,+ finalMessageId?: string,+): Promise<void> {+ await page.setViewportSize({ width, height })+ await expect.poll(() => page.getByTestId(tid.channelComposerShell).evaluate((element, viewportWidth) => {+ const rect = element.getBoundingClientRect()+ return viewportWidth < 640+ ? Math.abs(rect.left) <= 1 && Math.abs(rect.right - viewportWidth) <= 1+ : rect.left > 1 && Math.abs(rect.right - viewportWidth) <= 1+ }, width)).toBe(true)+ await settledRailMetrics(page, finalMessageId)+}+function expectContained(metrics: RailMetrics, state: string, width: number): void {const evidence = `${state}@${width}: ${JSON.stringify(metrics)}`expect(metrics.documentScrollWidth, evidence).toBe(metrics.documentClientWidth)@@ -246,20 +262,13 @@ async function captureState(args: {} = argsconst evidence: Record<number, RailMetrics> = {}for (const width of widths) {- await page.setViewportSize({ width, height: width >= 768 ? 900 : 844 })+ await setSettledViewport(page, width, width >= 768 ? 900 : 844, finalMessageId)const scrollRoot = page.getByTestId(tid.messageScroller)await scrollRoot.evaluate((element, showScrollControl) => {element.scrollTop = showScrollControl ? 0 : element.scrollHeightelement.dispatchEvent(new Event("scroll"))}, center && !selection)await expect(page.getByTestId(tid.scrollToPresent)).toHaveCount(center && !selection ? 1 : 0)- const composer = page.getByTestId(tid.channelComposerShell)- await expect.poll(() => composer.evaluate((element, viewportWidth) => {- const rect = element.getBoundingClientRect()- return viewportWidth < 640- ? Math.abs(rect.left) <= 1 && Math.abs(rect.right - viewportWidth) <= 1- : rect.left > 1 && Math.abs(rect.right - viewportWidth) <= 1- }, width)).toBe(true)const rail = page.getByTestId(tid.composerAccessoryRail)await expect(rail).toHaveCount((center || typing) && !selection ? 1 : 0)if ((center || typing) && !selection) await expect(rail).toHaveAttribute("data-layout", layout!)@@ -332,7 +341,7 @@ async function captureEmptyState(finalMessageId: string,): Promise<void> {for (const width of VIEWPORT_WIDTHS) {- await page.setViewportSize({ width, height: 844 })+ await setSettledViewport(page, width, 844, finalMessageId)await page.getByTestId(tid.messageScroller).evaluate((element) => {element.scrollTop = element.scrollHeightelement.dispatchEvent(new Event("scroll"))@@ -341,6 +350,9 @@ async function captureEmptyState(await expect(page.getByTestId(tid.composerAccessoryRail)).toHaveCount(0)await expect(page.getByTestId(tid.channelComposerShell)).toBeVisible()const metrics = await settledRailMetrics(page, finalMessageId)+ expect(metrics.scroller.scrollHeight - metrics.scroller.clientHeight - metrics.scroller.scrollTop)+ .toBeLessThanOrEqual(1)+ await expect(page.getByTestId(tid.scrollToPresent)).toHaveCount(0)const expectedTailGap = width < 640 ? 40 : 48expect(metrics.contentPaddingBottom).toBe(0)expect(metrics.scroller.bottom - metrics.finalMessage!.bottom)@@ -480,6 +492,14 @@ test("composer accessory rail reallocates every occupied slot without overflow",await expect(alice.page.getByTestId(tid.scrollToPresent)).toHaveCount(0)await expect(alice.page.locator("[data-e2e-node-identity='typing-survived']")).toHaveCount(1)await expect(alice.page.locator("[data-e2e-dot-identity='dot-survived']")).toHaveCount(1)+ for (const width of [639, 640]) {+ await alice.page.setViewportSize({ width, height: 844 })+ await expect.poll(() => scrollRoot.evaluate((element) =>+ Math.abs(element.scrollHeight - element.clientHeight - element.scrollTop),+ )).toBeLessThanOrEqual(1)+ await expect(alice.page.getByTestId(tid.scrollToPresent)).toHaveCount(0)+ await expect(alice.page.getByTestId(tid.message(finalMessageId))).toBeVisible()+ }const leftOnly = await captureState({page: alice.page,testInfo,diff --git a/src/web/src/test/message-scroll-fixture.ts b/src/web/src/test/message-scroll-fixture.tsindex 486d5f089..2e3a7b811 100644--- a/src/web/src/test/message-scroll-fixture.ts+++ b/src/web/src/test/message-scroll-fixture.ts@@ -10,6 +10,7 @@ type Input = Parameters<typeof useScrollAnchor>[0]type Result = ReturnType<typeof useScrollAnchor>let latest: Resultlet height: number+let width: numberlet firstPrefix: numberlet bodyHeights: Map<string, number>let frames: Map<number, FrameRequestCallback>@@ -37,9 +38,9 @@ function rowGeometry(node: HTMLElement) {const translation = wrapper?.style.transform.match(/translate3d\(0,\s*(-?[\d.]+)px/)const start = Number.parseFloat(translation?.[1] ?? wrapper?.style.top ?? "0") || 0const y = start - (root?.scrollTop ?? 0)- if (node.matches('[data-msg-id]')) return DOMRect.fromRect({ y: y + before, width: 320, height: size })- if (node.matches('[data-new-divider]')) return DOMRect.fromRect({ y: y + before - 24, width: 320, height: 24 })- return DOMRect.fromRect({ y, width: 320, height: size + before })+ if (node.matches('[data-msg-id]')) return DOMRect.fromRect({ y: y + before, width, height: size })+ if (node.matches('[data-new-divider]')) return DOMRect.fromRect({ y: y + before - 24, width, height: 24 })+ return DOMRect.fromRect({ y, width, height: size + before })}function Probe({ input, onLayout }: { input: Input; onLayout?: (result: Result) => void }) {const result = useScrollAnchor(input)@@ -80,7 +81,7 @@ export function resize(frameCount = 26) {act(() => {for (const observer of [...resizeObservers]) {const entries = [...observer.elements].filter(element => element.isConnected).map(target => ({- target, borderBoxSize: [{ blockSize: (target as HTMLElement).offsetHeight, inlineSize: 320 }],+ target, borderBoxSize: [{ blockSize: (target as HTMLElement).offsetHeight, inlineSize: width }],} as unknown as ResizeObserverEntry))if (entries.length) observer.callback(entries, {} as ResizeObserver)}@@ -106,6 +107,7 @@ export function bodyTop(root: HTMLElement, id: string) { return root.querySelectexport function installMessageScrollFixture() {height = 500+ width = 320firstPrefix = 88bodyHeights = new Map()frames = new Map()@@ -124,14 +126,15 @@ export function installMessageScrollFixture() {})vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockImplementation(function (this: HTMLElement) { return isScrollRoot(this) ? height : rowGeometry(this).height })vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockImplementation(function (this: HTMLElement) { return this.clientHeight })- vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(320)+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockImplementation(() => width)+ vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockImplementation(() => width)vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockImplementation(function (this: HTMLElement) {return isScrollRoot(this)? Math.max(height, Number.parseFloat(this.querySelector<HTMLElement>('[data-message-list-content] > div')?.style.height ?? "0") || 0): rowGeometry(this).height})vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {- return isScrollRoot(this) ? DOMRect.fromRect({ width: 320, height }) : rowGeometry(this)+ return isScrollRoot(this) ? DOMRect.fromRect({ width, height }) : rowGeometry(this)})scrollDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "scrollTo")Object.defineProperty(HTMLElement.prototype, "scrollTo", { configurable: true, value(this: HTMLElement, options: ScrollToOptions) {@@ -150,6 +153,8 @@ export function restoreMessageScrollFixture() {export const scrollFixture = {get latest() { return latest },+ get width() { return width },+ set width(value: number) { width = value },get height() { return height },set height(value: number) { height = value },get firstPrefix() { return firstPrefix },