<?xml version="1.0" encoding="UTF-8" ?>
    <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
      <channel>
        <title>Kotree | Deo Subarno - Software &amp; Game Developer — Building Kotree</title>
        <link>https://kotree.netlify.app/notes/series/building-kotree</link>
        <description>Kotree notes in the series &quot;Building Kotree&quot;</description>
        <language>en</language>
        <lastBuildDate>Sat, 08 Aug 2026 00:00:00 GMT</lastBuildDate>
        <atom:link href="https://kotree.netlify.app/notes/series/building-kotree/feed.xml" rel="self" type="application/rss+xml" />
        
      <item>
        <title>Case study: making Kotree fast</title>
        <link>https://kotree.netlify.app/notes/2026-02-21-case-study-kotree-performance</link>
        <guid>https://kotree.netlify.app/notes/2026-02-21-case-study-kotree-performance</guid>
        <pubDate>Sat, 21 Feb 2026 00:00:00 GMT</pubDate>
        <category>case-study</category>
        <category>performance</category>
        <category>next.js</category>
        <description><![CDATA[<p>Kotree started as a link list and grew into a playground. The links stayed fast because they were static; everything added around them did not. This is the account of what was slow, what was cut, and what the local measurements said afterwards. The numbers are lab numbers from one Windows machine, not field data.</p><h2>The starting point</h2><p>The measurement method mattered as much as the result. Each run used a production build, a fresh browser context with an empty cache, the service worker unregistered, and the CPU throttled to a quarter speed through the Chrome DevTools Protocol. The largest paint was read from a buffered `PerformanceObserver`, and each figure is the median of five runs. The bundle figures came from the build output, counting decoded JavaScript, not compressed transfer size.</p><p>On that method, the home route shipped 663 kB of initial JavaScript and painted its largest element at 948 ms. The full build contained 1,563 kB of JavaScript across every route and lazy chunk. Neither number is catastrophic on a desktop, and both are heavy for a page whose main job is showing a name and a list of links.</p><p>The budgets already existed in spirit: a largest paint under 2.5 seconds, a layout shift under 0.1, and a response within 800 milliseconds. The byte budget was the one that did not flex, because bytes come from the build rather than the machine. It was set at 800 kB per route, and the home page was close enough to it that one more feature would have crossed it.</p><h2>Where the bytes were</h2><p>The route-level bundle was the first useful view. A script summed each route&apos;s scripts from the build manifest and printed the decoded size. The offenders were not mysterious:</p><ul><li>The Windows 95 desktop and its four apps were in the initial graph, even though the desktop is an easter egg behind a secret.</li><li>A charting component used on the stats page was imported by a shared module, so its cost leaked into routes that never drew a chart.</li><li>The command palette was mounted on every page and loaded its fuzzy-search and dialog code before anyone pressed the shortcut.</li><li>Several small client components imported the same utility barrel, which defeated tree-shaking and pulled in code for features that were not on screen.</li><li>The font was loaded at three weights, and the heading that won the largest paint was waiting for all of them.</li></ul><p>The total was a collection of reasonable local decisions. Nobody adds 663 kB in one commit; it arrives forty kilobytes at a time, each with a plausible reason.</p><h2>The cuts</h2><p>The desktop became a dynamic import, loaded only when the secret opens. The apps inside it were already separate components, so they moved with it into a chunk that loads on demand. That one change removed the largest single block from the initial graph.</p><p>The charts moved behind the stats route&apos;s own boundary. A shared module no longer re-exported them, which also fixed the barrel file. The command palette stayed mounted for the keyboard shortcut, but its dialog, search and result rendering load on first open. The shortcut handler is a few hundred bytes; the palette is not.</p><p>The utility barrel was replaced with direct imports. This is unglamorous and easy to postpone, and it is usually worth more than a new abstraction. A barrel that re-exports everything is a promise that every consumer pays for every export.</p><p>The font went from three files to one variable file, subset to Latin, preloaded once. The fallback was adjusted with `size-adjust` and the vertical overrides so the heading did not move when the real face arrived. That work belongs to the largest paint, not to a separate typography project.</p><h2>Hydration is not just download</h2><p>The second cost was hydration. A page can download little and still feel slow if the main thread spends a second attaching listeners to markup that did not need them.</p><p>The fix was boundary placement rather than a new state library. The page is a server component by default. The interactive parts are small islands: the theme switch, the guestbook form, the click counters, the command palette trigger. A provider that used to wrap the whole page now wraps only the components that read it. The Win95 desktop is not hydrated at all until it is imported.</p><p>This is the part that is hard to see in a bundle report. A component can be small and still cost a lot if it forces a large subtree to become client code. Moving one `useState` to the leaf is often worth more than deleting a dependency.</p><h2>Budgets that fail</h2><p>The byte check runs after the build and sums the decoded scripts each route needs before its load event. It fails above 700 kB. There is no CI multiplier because the number does not depend on the runner.</p><p>The timing checks run in Playwright against a production build with the CPU throttled. Largest paint must stay under 2.5 seconds, layout shift under 0.1, and the response proxy under 800 milliseconds. On shared CI runners those time ceilings double, because the runner is not the page. The byte ceiling does not.</p><p>The budget is not a target to spend. It is a tripwire. When a feature crosses it, the conversation is about what to remove, not about raising the number in the same commit.</p><h2>The result</h2><p>The current build ships 663 kB of initial JavaScript on the home route and 1,563 kB across every route and lazy chunk. The largest paint on the same machine and method is 948 ms, with a response proxy time well under the 800 ms ceiling. Those are local numbers from a quarter-speed CPU. They are useful for comparing builds and useless as a claim about visitors. The sampled field data is separate, and at the sample size this site has, it is not stable enough to quote as an outcome.</p><p>The result is not a finished win; it is a baseline with a tripwire around it. The remaining weight is mostly the framework runtime and the interactive shell. Removing either would cost more than it saves.</p><h2>What I would do differently</h2><p>The first attempt lazy-loaded the palette trigger as well, which meant the keyboard shortcut did nothing until a chunk arrived. That is a bad trade: the shell of an interaction should be present, even if the expensive part is not. The second attempt kept the trigger and deferred the rest.</p><p>The other lesson is that a bundle budget needs a route-level view. A total is easy to report and hard to act on. The route is where a person waits.</p>]]></description>
        <content:encoded><![CDATA[<p>Kotree started as a link list and grew into a playground. The links stayed fast because they were static; everything added around them did not. This is the account of what was slow, what was cut, and what the local measurements said afterwards. The numbers are lab numbers from one Windows machine, not field data.</p><h2>The starting point</h2><p>The measurement method mattered as much as the result. Each run used a production build, a fresh browser context with an empty cache, the service worker unregistered, and the CPU throttled to a quarter speed through the Chrome DevTools Protocol. The largest paint was read from a buffered `PerformanceObserver`, and each figure is the median of five runs. The bundle figures came from the build output, counting decoded JavaScript, not compressed transfer size.</p><p>On that method, the home route shipped 663 kB of initial JavaScript and painted its largest element at 948 ms. The full build contained 1,563 kB of JavaScript across every route and lazy chunk. Neither number is catastrophic on a desktop, and both are heavy for a page whose main job is showing a name and a list of links.</p><p>The budgets already existed in spirit: a largest paint under 2.5 seconds, a layout shift under 0.1, and a response within 800 milliseconds. The byte budget was the one that did not flex, because bytes come from the build rather than the machine. It was set at 800 kB per route, and the home page was close enough to it that one more feature would have crossed it.</p><h2>Where the bytes were</h2><p>The route-level bundle was the first useful view. A script summed each route&apos;s scripts from the build manifest and printed the decoded size. The offenders were not mysterious:</p><ul><li>The Windows 95 desktop and its four apps were in the initial graph, even though the desktop is an easter egg behind a secret.</li><li>A charting component used on the stats page was imported by a shared module, so its cost leaked into routes that never drew a chart.</li><li>The command palette was mounted on every page and loaded its fuzzy-search and dialog code before anyone pressed the shortcut.</li><li>Several small client components imported the same utility barrel, which defeated tree-shaking and pulled in code for features that were not on screen.</li><li>The font was loaded at three weights, and the heading that won the largest paint was waiting for all of them.</li></ul><p>The total was a collection of reasonable local decisions. Nobody adds 663 kB in one commit; it arrives forty kilobytes at a time, each with a plausible reason.</p><h2>The cuts</h2><p>The desktop became a dynamic import, loaded only when the secret opens. The apps inside it were already separate components, so they moved with it into a chunk that loads on demand. That one change removed the largest single block from the initial graph.</p><p>The charts moved behind the stats route&apos;s own boundary. A shared module no longer re-exported them, which also fixed the barrel file. The command palette stayed mounted for the keyboard shortcut, but its dialog, search and result rendering load on first open. The shortcut handler is a few hundred bytes; the palette is not.</p><p>The utility barrel was replaced with direct imports. This is unglamorous and easy to postpone, and it is usually worth more than a new abstraction. A barrel that re-exports everything is a promise that every consumer pays for every export.</p><p>The font went from three files to one variable file, subset to Latin, preloaded once. The fallback was adjusted with `size-adjust` and the vertical overrides so the heading did not move when the real face arrived. That work belongs to the largest paint, not to a separate typography project.</p><h2>Hydration is not just download</h2><p>The second cost was hydration. A page can download little and still feel slow if the main thread spends a second attaching listeners to markup that did not need them.</p><p>The fix was boundary placement rather than a new state library. The page is a server component by default. The interactive parts are small islands: the theme switch, the guestbook form, the click counters, the command palette trigger. A provider that used to wrap the whole page now wraps only the components that read it. The Win95 desktop is not hydrated at all until it is imported.</p><p>This is the part that is hard to see in a bundle report. A component can be small and still cost a lot if it forces a large subtree to become client code. Moving one `useState` to the leaf is often worth more than deleting a dependency.</p><h2>Budgets that fail</h2><p>The byte check runs after the build and sums the decoded scripts each route needs before its load event. It fails above 700 kB. There is no CI multiplier because the number does not depend on the runner.</p><p>The timing checks run in Playwright against a production build with the CPU throttled. Largest paint must stay under 2.5 seconds, layout shift under 0.1, and the response proxy under 800 milliseconds. On shared CI runners those time ceilings double, because the runner is not the page. The byte ceiling does not.</p><p>The budget is not a target to spend. It is a tripwire. When a feature crosses it, the conversation is about what to remove, not about raising the number in the same commit.</p><h2>The result</h2><p>The current build ships 663 kB of initial JavaScript on the home route and 1,563 kB across every route and lazy chunk. The largest paint on the same machine and method is 948 ms, with a response proxy time well under the 800 ms ceiling. Those are local numbers from a quarter-speed CPU. They are useful for comparing builds and useless as a claim about visitors. The sampled field data is separate, and at the sample size this site has, it is not stable enough to quote as an outcome.</p><p>The result is not a finished win; it is a baseline with a tripwire around it. The remaining weight is mostly the framework runtime and the interactive shell. Removing either would cost more than it saves.</p><h2>What I would do differently</h2><p>The first attempt lazy-loaded the palette trigger as well, which meant the keyboard shortcut did nothing until a chunk arrived. That is a bad trade: the shell of an interaction should be present, even if the expensive part is not. The second attempt kept the trigger and deferred the rest.</p><p>The other lesson is that a bundle budget needs a route-level view. A total is easy to report and hard to act on. The route is where a person waits.</p>]]></content:encoded>
      </item>
      <item>
        <title>Case study: a guestbook that survives the internet</title>
        <link>https://kotree.netlify.app/notes/2026-04-18-case-study-guestbook</link>
        <guid>https://kotree.netlify.app/notes/2026-04-18-case-study-guestbook</guid>
        <pubDate>Sat, 18 Apr 2026 00:00:00 GMT</pubDate>
        <category>case-study</category>
        <category>mongodb</category>
        <category>security</category>
        <description><![CDATA[<p>A guestbook is a small feature with a large attack surface. It accepts text from strangers, stores it, shows it to other strangers and, if it is any good, lets them write while offline. The design here assumes that most submissions are fine, a few are advertising, and a handful are actively hostile. The job is to handle all three without a moderation queue that never ends.</p><h2>The shape</h2><p>A message is a name, a short body and a timestamp. The body is limited to 100 characters. On the way out, the client applies a light obfuscation: a character shift, then Base64, with a prefix. The server stores that string. The wall shows the obfuscated text until a reader chooses to reveal it.</p><p>This is obfuscation, not encryption. There is no key, and anyone who looks at the JavaScript can reverse it. The point is to stop a message being readable in a screenshot or a page source at a glance, and to make the wall feel like a wall of secrets. Calling it encryption would be a lie that someone might rely on. The privacy note says what it is.</p><p>The API is a POST with a JSON body, an origin check and a CSRF token. MongoDB is the only store. There are no accounts, no email addresses and no profiles.</p><h2>The abuse surface</h2><p>The first layer is cheap and catches the obvious. The request must come from the site&apos;s own origin; a cross-site form post is rejected before the body is parsed. The body size is capped. The message length is capped again on the server, because a client-side `maxlength` is a suggestion. A hidden field that should stay empty catches bots that fill every input.</p><p>The second layer is rate limiting in MongoDB, not in memory. An in-memory counter resets with every cold serverless instance, which makes the limit decorative. The keys are an IP and an IP plus a route, the window is a minute, and there is a daily cap. A global budget catches a flood spread across many addresses.</p><p>The third layer is a spam score. It is deliberately not a classifier. Each signal adds points and a reason:</p><ul><li>A link adds two points, and each additional link adds one.</li><li>Advertising phrases add three each.</li><li>Mostly capitals add one.</li><li>Six or more repeated characters add one.</li><li>A link with four words or fewer adds two.</li><li>A message that repeats the same words adds one.</li></ul><p>At four points the message is stored hidden and sent to moderation. The wall does not reject it outright, because a false positive that vanishes is worse than one a human can release. The stored reasons are shown next to the entry in the admin queue, so the decision takes seconds.</p><h2>Moderation</h2><p>The queue is a list of held entries with their score and reasons. Approve publishes; reject hides permanently. A repeated offender can be banned by hashed IP, with an expiry. Bans expire on their own, because a permanent ban for one bad afternoon is more administration than it prevents.</p><p>Every decision writes an audit row: what happened, to which entry, when, and a hashed, truncated IP. The hash is enough to correlate an afternoon of abuse and not enough to know where someone lives. The raw address is not stored in the audit log.</p><p>The admin routes are separate from the public ones and require a session. Their rate limit is tighter, and the session row expires on its own. The guestbook&apos;s public read path does not touch the admin code at all.</p><h2>The offline queue</h2><p>The interesting failure is the message written on a train. The form submits optimistically: a temporary entry appears on the wall with a pending marker, and the payload goes into IndexedDB. A service worker replays it when the connection returns, even if the tab is closed, where Background Sync is available.</p><p>Two details make the replay safe. The record carries a client-generated id that the server stores under a unique index, so a retry after a dropped response returns the original entry instead of creating a second one. And the CSRF token is stashed next to the queue, because a service worker cannot read the page&apos;s memory or `localStorage`. Without the token, the replay would be rejected as a forgery.</p><p>The queue drains on the `online` event, on `visibilitychange`, and on the next page load. Background Sync is treated as a bonus, not a guarantee: Safari does not implement it, and iOS can evict the worker. The UI says &quot;waiting to send&quot;, not &quot;sent&quot;.</p><p>The hardest bug in this area was not the network. It was two tabs draining the same queue at once. A `navigator.locks` lock fixes it where supported; the server&apos;s idempotency key is the backstop everywhere else.</p><h2>Privacy</h2><p>The site stores a hashed, truncated IP for rate limiting and moderation, not the address itself. The hash expires with the rate-limit bucket or the ban. There is no account, no email and no cookie for the guestbook. A message can be removed on request, and the privacy note explains what is kept and for how long.</p><p>The obfuscated body is still user content. It is escaped on render, parsed as Markdown-lite rather than HTML, and links are rendered with a safe `rel`. That removes a class of injection problems at the cost of a feature nobody asked for.</p><h2>What broke</h2><p>The first spam wave was not sophisticated. It was links with three words around them, and the score held them. The first false positive was a real person quoting a URL with a short message; the reasons made that obvious in the queue, and the threshold stayed where it was.</p><p>The offline queue produced one duplicate in testing before the idempotency index existed. The fix was a unique index and a retry that treats a conflict as success. The second version has not duplicated a message.</p><p>The moderation queue is the real cost. It is small because the wall is small, and it would not stay small if the site were popular. That is a reasonable limit for a personal guestbook, and it is worth saying out loud rather than pretending the scoring solves it.</p>]]></description>
        <content:encoded><![CDATA[<p>A guestbook is a small feature with a large attack surface. It accepts text from strangers, stores it, shows it to other strangers and, if it is any good, lets them write while offline. The design here assumes that most submissions are fine, a few are advertising, and a handful are actively hostile. The job is to handle all three without a moderation queue that never ends.</p><h2>The shape</h2><p>A message is a name, a short body and a timestamp. The body is limited to 100 characters. On the way out, the client applies a light obfuscation: a character shift, then Base64, with a prefix. The server stores that string. The wall shows the obfuscated text until a reader chooses to reveal it.</p><p>This is obfuscation, not encryption. There is no key, and anyone who looks at the JavaScript can reverse it. The point is to stop a message being readable in a screenshot or a page source at a glance, and to make the wall feel like a wall of secrets. Calling it encryption would be a lie that someone might rely on. The privacy note says what it is.</p><p>The API is a POST with a JSON body, an origin check and a CSRF token. MongoDB is the only store. There are no accounts, no email addresses and no profiles.</p><h2>The abuse surface</h2><p>The first layer is cheap and catches the obvious. The request must come from the site&apos;s own origin; a cross-site form post is rejected before the body is parsed. The body size is capped. The message length is capped again on the server, because a client-side `maxlength` is a suggestion. A hidden field that should stay empty catches bots that fill every input.</p><p>The second layer is rate limiting in MongoDB, not in memory. An in-memory counter resets with every cold serverless instance, which makes the limit decorative. The keys are an IP and an IP plus a route, the window is a minute, and there is a daily cap. A global budget catches a flood spread across many addresses.</p><p>The third layer is a spam score. It is deliberately not a classifier. Each signal adds points and a reason:</p><ul><li>A link adds two points, and each additional link adds one.</li><li>Advertising phrases add three each.</li><li>Mostly capitals add one.</li><li>Six or more repeated characters add one.</li><li>A link with four words or fewer adds two.</li><li>A message that repeats the same words adds one.</li></ul><p>At four points the message is stored hidden and sent to moderation. The wall does not reject it outright, because a false positive that vanishes is worse than one a human can release. The stored reasons are shown next to the entry in the admin queue, so the decision takes seconds.</p><h2>Moderation</h2><p>The queue is a list of held entries with their score and reasons. Approve publishes; reject hides permanently. A repeated offender can be banned by hashed IP, with an expiry. Bans expire on their own, because a permanent ban for one bad afternoon is more administration than it prevents.</p><p>Every decision writes an audit row: what happened, to which entry, when, and a hashed, truncated IP. The hash is enough to correlate an afternoon of abuse and not enough to know where someone lives. The raw address is not stored in the audit log.</p><p>The admin routes are separate from the public ones and require a session. Their rate limit is tighter, and the session row expires on its own. The guestbook&apos;s public read path does not touch the admin code at all.</p><h2>The offline queue</h2><p>The interesting failure is the message written on a train. The form submits optimistically: a temporary entry appears on the wall with a pending marker, and the payload goes into IndexedDB. A service worker replays it when the connection returns, even if the tab is closed, where Background Sync is available.</p><p>Two details make the replay safe. The record carries a client-generated id that the server stores under a unique index, so a retry after a dropped response returns the original entry instead of creating a second one. And the CSRF token is stashed next to the queue, because a service worker cannot read the page&apos;s memory or `localStorage`. Without the token, the replay would be rejected as a forgery.</p><p>The queue drains on the `online` event, on `visibilitychange`, and on the next page load. Background Sync is treated as a bonus, not a guarantee: Safari does not implement it, and iOS can evict the worker. The UI says &quot;waiting to send&quot;, not &quot;sent&quot;.</p><p>The hardest bug in this area was not the network. It was two tabs draining the same queue at once. A `navigator.locks` lock fixes it where supported; the server&apos;s idempotency key is the backstop everywhere else.</p><h2>Privacy</h2><p>The site stores a hashed, truncated IP for rate limiting and moderation, not the address itself. The hash expires with the rate-limit bucket or the ban. There is no account, no email and no cookie for the guestbook. A message can be removed on request, and the privacy note explains what is kept and for how long.</p><p>The obfuscated body is still user content. It is escaped on render, parsed as Markdown-lite rather than HTML, and links are rendered with a safe `rel`. That removes a class of injection problems at the cost of a feature nobody asked for.</p><h2>What broke</h2><p>The first spam wave was not sophisticated. It was links with three words around them, and the score held them. The first false positive was a real person quoting a URL with a short message; the reasons made that obvious in the queue, and the threshold stayed where it was.</p><p>The offline queue produced one duplicate in testing before the idempotency index existed. The fix was a unique index and a retry that treats a conflict as success. The second version has not duplicated a message.</p><p>The moderation queue is the real cost. It is small because the wall is small, and it would not stay small if the site were popular. That is a reasonable limit for a personal guestbook, and it is worth saying out loud rather than pretending the scoring solves it.</p>]]></content:encoded>
      </item>
      <item>
        <title>Case study: a tip jar without a wallet library</title>
        <link>https://kotree.netlify.app/notes/2026-06-06-case-study-tip-jar</link>
        <guid>https://kotree.netlify.app/notes/2026-06-06-case-study-tip-jar</guid>
        <pubDate>Sat, 06 Jun 2026 00:00:00 GMT</pubDate>
        <category>case-study</category>
        <category>ethereum</category>
        <category>security</category>
        <description><![CDATA[<p>The tip jar has one job: let someone send a small amount of Ether without asking them to install anything else. The obvious implementation is a wallet library. The library would add tens of kilobytes to a page that is mostly links, for three JSON-RPC calls. The version that shipped talks to the injected provider directly and owns the small amount of parsing that requires.</p><h2>Three calls</h2><p>An EIP-1193 provider is available as `window.ethereum` in a browser with a wallet extension. The send flow uses three methods:</p><ul><li>`eth_requestAccounts` asks for permission and returns the selected address.</li><li>`wallet_switchEthereumChain` asks the wallet to change networks.</li><li>`eth_sendTransaction` sends the transfer.</li></ul><p>Nothing is requested on page load. The connect button is a user gesture, and the account prompt appears only after it. Auto-connecting on load is a privacy leak and a hostile first impression; the page should not learn an address before the visitor asks it to.</p><p>The provider API is promise-based and rejects with an error object. EIP-1193 defines a `code` on that object, and the codes are the difference between a useful message and &quot;something went wrong&quot;. `4001` is a user rejection. `4902` is an unrecognised chain. `-32002` means a request is already pending in the wallet. Those three cover most of the unhappy paths.</p><h2>Switching chains</h2><p>The jar expects mainnet, chain id `0x1`. The wallet may be on another network, so the flow checks `eth_chainId` before sending and calls `wallet_switchEthereumChain` with `{ chainId: &apos;0x1&apos; }` if needed.</p><p>If the wallet does not know the chain, it rejects with `4902`. The fallback is `wallet_addEthereumChain`, with the chain id, a name, the RPC URL and a block explorer. That is a wallet-specific prompt and a place to be careful: the values should come from a constant, not from a response, and the user should understand that they are adding a network, not just switching one.</p><p>A rejection at either step ends the flow without a transaction. The button returns to its normal state, and the message says the request was cancelled. That is not an error; it is the user exercising the only control they have.</p><p>The provider can change underneath the page. `chainChanged` and `accountsChanged` are subscribed while the jar is mounted. A chain change resets the connected state and asks the user to try again; an account change updates the displayed address. Ignoring these events produces a page that looks connected to an account that is no longer selected.</p><h2>Wei without a library</h2><p>The amount is a decimal string, not a number. `0.001` cannot be represented exactly as a binary float, and multiplying it by `1e18` is a way to send the wrong amount. The parser splits on the decimal point, pads the fractional part to eighteen digits, and builds a `BigInt`.</p><pre><code>const [whole, frac = &apos;&apos;] = amount.split(&apos;.&apos;);
const wei = BigInt(whole) * 10n ** 18n + BigInt((frac + &apos;0&apos;.repeat(18)).slice(0, 18));</code></pre><p>The result is converted to a hex string for the transaction&apos;s `value` field. The same treatment applies to any gas fields the wallet returns; they are hex strings, not numbers, and parsing them with `Number` loses precision above 2^53.</p><p>The recipient address is a constant. The jar does not resolve ENS names, because that would require an RPC call and another failure mode. It displays the address truncated and offers a copy button, so a visitor can verify it in their wallet.</p><h2>The failure states</h2><p>The UI has a state for each of these, and none of them is a generic toast:</p><ul><li>**No provider.** The connect button is disabled with a short explanation and a link to a wallet, not a broken click.</li><li>**Request pending.** The wallet is already showing a prompt; the button says so and does not send a second request.</li><li>**Rejected.** The user cancelled. The jar says the request was cancelled and leaves the form as it was.</li><li>**Wrong chain.** The jar offers the switch and explains why. If the switch is rejected, nothing is sent.</li><li>**Insufficient funds.** The wallet usually catches this before the page does; if the transaction fails, the error is shown with the hash if one exists.</li><li>**Pending.** The hash is shown with an explorer link, and the jar says the transaction is pending rather than confirmed. A pending transaction is not a completed tip.</li><li>**Replaced or dropped.** A transaction can be replaced with a higher fee or dropped by the network. The explorer is the source of truth; the page does not poll forever.</li></ul><p>The state machine is small but explicit. A boolean `isConnected` is not enough, because &quot;connected&quot; does not mean &quot;on the right chain&quot; or &quot;able to send&quot;.</p><h2>What was deliberately left out</h2><p>The jar does not use WalletConnect, so it only works with an injected provider. It does not use ethers or viem, so it has no contract calls and no ABI handling. It does not support ERC-20 tokens, because approvals and decimals are a different feature with a different risk profile. It does not resolve ENS, index transactions, send notifications, or offer fiat on-ramps.</p><p>It also does not report transaction volume, because the site has no indexer and the numbers would be invented. The only honest metric is the block explorer.</p><h2>Testing</h2><p>The unit tests cover the wei parser at the boundaries: whole numbers, one decimal place, eighteen, more than eighteen, an empty fraction and a leading dot. The end-to-end tests inject a fake `window.ethereum` with `addInitScript`, then assert the exact sequence of methods and the shape of the transaction. No test touches a real chain.</p><p>A manual pass on a testnet is still necessary. The mocked provider cannot reproduce the wallet&apos;s own prompts, the chain-switch rejection or the way a pending transaction looks. Those are the states that matter, and they are the ones a mock will happily pretend to have.</p>]]></description>
        <content:encoded><![CDATA[<p>The tip jar has one job: let someone send a small amount of Ether without asking them to install anything else. The obvious implementation is a wallet library. The library would add tens of kilobytes to a page that is mostly links, for three JSON-RPC calls. The version that shipped talks to the injected provider directly and owns the small amount of parsing that requires.</p><h2>Three calls</h2><p>An EIP-1193 provider is available as `window.ethereum` in a browser with a wallet extension. The send flow uses three methods:</p><ul><li>`eth_requestAccounts` asks for permission and returns the selected address.</li><li>`wallet_switchEthereumChain` asks the wallet to change networks.</li><li>`eth_sendTransaction` sends the transfer.</li></ul><p>Nothing is requested on page load. The connect button is a user gesture, and the account prompt appears only after it. Auto-connecting on load is a privacy leak and a hostile first impression; the page should not learn an address before the visitor asks it to.</p><p>The provider API is promise-based and rejects with an error object. EIP-1193 defines a `code` on that object, and the codes are the difference between a useful message and &quot;something went wrong&quot;. `4001` is a user rejection. `4902` is an unrecognised chain. `-32002` means a request is already pending in the wallet. Those three cover most of the unhappy paths.</p><h2>Switching chains</h2><p>The jar expects mainnet, chain id `0x1`. The wallet may be on another network, so the flow checks `eth_chainId` before sending and calls `wallet_switchEthereumChain` with `{ chainId: &apos;0x1&apos; }` if needed.</p><p>If the wallet does not know the chain, it rejects with `4902`. The fallback is `wallet_addEthereumChain`, with the chain id, a name, the RPC URL and a block explorer. That is a wallet-specific prompt and a place to be careful: the values should come from a constant, not from a response, and the user should understand that they are adding a network, not just switching one.</p><p>A rejection at either step ends the flow without a transaction. The button returns to its normal state, and the message says the request was cancelled. That is not an error; it is the user exercising the only control they have.</p><p>The provider can change underneath the page. `chainChanged` and `accountsChanged` are subscribed while the jar is mounted. A chain change resets the connected state and asks the user to try again; an account change updates the displayed address. Ignoring these events produces a page that looks connected to an account that is no longer selected.</p><h2>Wei without a library</h2><p>The amount is a decimal string, not a number. `0.001` cannot be represented exactly as a binary float, and multiplying it by `1e18` is a way to send the wrong amount. The parser splits on the decimal point, pads the fractional part to eighteen digits, and builds a `BigInt`.</p><pre><code>const [whole, frac = &apos;&apos;] = amount.split(&apos;.&apos;);
const wei = BigInt(whole) * 10n ** 18n + BigInt((frac + &apos;0&apos;.repeat(18)).slice(0, 18));</code></pre><p>The result is converted to a hex string for the transaction&apos;s `value` field. The same treatment applies to any gas fields the wallet returns; they are hex strings, not numbers, and parsing them with `Number` loses precision above 2^53.</p><p>The recipient address is a constant. The jar does not resolve ENS names, because that would require an RPC call and another failure mode. It displays the address truncated and offers a copy button, so a visitor can verify it in their wallet.</p><h2>The failure states</h2><p>The UI has a state for each of these, and none of them is a generic toast:</p><ul><li>**No provider.** The connect button is disabled with a short explanation and a link to a wallet, not a broken click.</li><li>**Request pending.** The wallet is already showing a prompt; the button says so and does not send a second request.</li><li>**Rejected.** The user cancelled. The jar says the request was cancelled and leaves the form as it was.</li><li>**Wrong chain.** The jar offers the switch and explains why. If the switch is rejected, nothing is sent.</li><li>**Insufficient funds.** The wallet usually catches this before the page does; if the transaction fails, the error is shown with the hash if one exists.</li><li>**Pending.** The hash is shown with an explorer link, and the jar says the transaction is pending rather than confirmed. A pending transaction is not a completed tip.</li><li>**Replaced or dropped.** A transaction can be replaced with a higher fee or dropped by the network. The explorer is the source of truth; the page does not poll forever.</li></ul><p>The state machine is small but explicit. A boolean `isConnected` is not enough, because &quot;connected&quot; does not mean &quot;on the right chain&quot; or &quot;able to send&quot;.</p><h2>What was deliberately left out</h2><p>The jar does not use WalletConnect, so it only works with an injected provider. It does not use ethers or viem, so it has no contract calls and no ABI handling. It does not support ERC-20 tokens, because approvals and decimals are a different feature with a different risk profile. It does not resolve ENS, index transactions, send notifications, or offer fiat on-ramps.</p><p>It also does not report transaction volume, because the site has no indexer and the numbers would be invented. The only honest metric is the block explorer.</p><h2>Testing</h2><p>The unit tests cover the wei parser at the boundaries: whole numbers, one decimal place, eighteen, more than eighteen, an empty fraction and a leading dot. The end-to-end tests inject a fake `window.ethereum` with `addInitScript`, then assert the exact sequence of methods and the shape of the transaction. No test touches a real chain.</p><p>A manual pass on a testnet is still necessary. The mocked provider cannot reproduce the wallet&apos;s own prompts, the chain-switch rejection or the way a pending transaction looks. Those are the states that matter, and they are the ones a mock will happily pretend to have.</p>]]></content:encoded>
      </item>
      <item>
        <title>Case study: shipping a Win95 desktop</title>
        <link>https://kotree.netlify.app/notes/2026-08-08-case-study-win95</link>
        <guid>https://kotree.netlify.app/notes/2026-08-08-case-study-win95</guid>
        <pubDate>Sat, 08 Aug 2026 00:00:00 GMT</pubDate>
        <category>case-study</category>
        <category>accessibility</category>
        <category>react</category>
        <description><![CDATA[<p>The Windows 95 desktop began as a screenshot joke: grey chrome, a taskbar, a window that could be dragged. The risk with a joke is that it stays a screenshot. The version that shipped is a small window manager with four working apps, a keyboard model, a mobile layout and its own audit. The scope was the hard part.</p><h2>Scope</h2><p>The desktop is not an operating system. It has no file system, no networking, no sound and no installable programs. It has a window manager, a Start menu, a taskbar, Notepad, Paint, Calculator and Minesweeper. Notepad persists a draft to `localStorage`; Paint exports a PNG; Calculator calculates; Minesweeper is playable and finished.</p><p>Everything else was cut on purpose. A file explorer would need a virtual file system and a permission model. A browser inside the desktop would need an iframe and a policy conversation. Clippy would need a personality. The four apps are enough to make the desktop feel inhabited, and each one is small enough to test.</p><p>The scope list was written before the code. That is the only reason the desktop shipped.</p><h2>Window state</h2><p>One reducer owns the desktop: an array of windows, a z-index counter and the active id. Each window has an app key, position, size, z-index, minimised and maximised flags, and a `restoreRect`. Opening, closing, focusing, moving, resizing, minimising and maximising are actions. The reducer is pure, which makes the geometry testable without a browser.</p><p>Dragging is the exception to the state rule. A pointer move writes a CSS transform on the window element, and the final position is dispatched on pointer up. Dispatching every move would re-render the whole desktop at pointer frequency. The transform keeps the drag on the compositor and the React tree quiet.</p><p>Maximising stores the previous rectangle before filling the desktop. Restoring returns to it. Without that, a maximised window that is restored to a default size loses the arrangement the user made, which is a small betrayal that makes the whole thing feel fake.</p><h2>The keyboard model</h2><p>The desktop is usable without a mouse, and the model is explained where it is used. The title bar is focusable with `tabIndex={0}`, labelled &quot;Move Notepad, arrow keys, Shift to jump&quot;, and handles arrows at 16 pixels or 48 with Shift. The handler is on the title bar, so typing in Notepad does not move the window.</p><p>Closing a window returns focus to its taskbar button. The taskbar uses roving tabindex: one button is in the tab sequence, and the arrow keys move between the open windows. That keeps the tab order short and still exposes every window.</p><p>The apps have their own keys. Minesweeper uses arrows to move, Enter to dig and F to flag; right-click also flags. Calculator listens for digits, operators, Enter, Escape and Backspace while focused. The keys are printed in the window, because a shortcut nobody can find is not a feature.</p><p>The desktop does not intercept `Alt+Tab`, `Ctrl+W` or other browser and operating-system shortcuts. A page that fights the window manager it lives in is not more authentic; it is just broken. The shortcuts it does own are the ones a page can own.</p><h2>Focus and screen readers</h2><p>Windows are non-modal dialogs, not a modal trap. Each has a label, a role and a focusable title bar. The taskbar is a toolbar with buttons. Opening a window moves focus into it; closing it restores focus to the opener. An `aria-live` region announces the window that opened or closed, so the change is not silent.</p><p>The desktop passes axe with zero serious or critical violations. That is not the same as being pleasant with a screen reader, so the keyboard journey is also tested end to end: open the desktop, open Notepad, type, minimise, restore, close, and return to the taskbar.</p><h2>Mobile and small screens</h2><p>The desktop does not pretend a 320-pixel phone is a desktop. Windows become full-screen sheets, dragging is disabled, and the taskbar stays at the bottom with 44-pixel buttons. The apps reflow rather than scale: Notepad is a text area, Paint is a canvas with a toolbar that wraps, Calculator is a keypad, Minesweeper&apos;s grid fits.</p><p>The page still has to pass the same checks at 320 pixels: no horizontal scroll, no control under 24 pixels, and the text-spacing override does not break the layout. The Win95 chrome is small by design, so the hit areas are expanded with padding and checked for overlap.</p><h2>Bundle isolation</h2><p>The desktop is not in the initial bundle. It is a dynamic import loaded when the secret opens. The four apps are components inside that chunk, so opening the desktop downloads all four, but the home page downloads none of them.</p><p>The CSS is scoped to the desktop container. The grey palette and the pixel borders do not leak into the rest of the site, and the site&apos;s theme tokens do not leak in. That isolation is what lets the desktop look wrong on purpose without making the rest of the page look wrong by accident.</p><h2>Testing</h2><p>The reducer has unit tests for z-order, minimise and restore, and the geometry of snapping. The end-to-end suite covers the keyboard journey, the mobile layout, forced-colours mode, reduced motion and the axe audit. Visual baselines seed the random window placement, because a screenshot test that compares random positions fails for the wrong reason.</p><p>The drag test uses pointer events rather than mouse events, and it asserts the committed position after release, not the transform during the drag. That is the part a screenshot cannot check.</p><h2>What it taught</h2><p>The desktop is the most elaborate easter egg on the site and the one most likely to be dismissed as decoration. Building it properly took longer than the joke deserved, and the result is better for it: a keyboard user can open Minesweeper and play, a phone user gets a usable layout, and the page it lives on does not pay for it until the secret is found.</p><p>The lesson is not that every joke needs this much work. It is that the scope list is the feature. Four apps and one window manager is a desktop. A fifth app would have been a second project.</p>]]></description>
        <content:encoded><![CDATA[<p>The Windows 95 desktop began as a screenshot joke: grey chrome, a taskbar, a window that could be dragged. The risk with a joke is that it stays a screenshot. The version that shipped is a small window manager with four working apps, a keyboard model, a mobile layout and its own audit. The scope was the hard part.</p><h2>Scope</h2><p>The desktop is not an operating system. It has no file system, no networking, no sound and no installable programs. It has a window manager, a Start menu, a taskbar, Notepad, Paint, Calculator and Minesweeper. Notepad persists a draft to `localStorage`; Paint exports a PNG; Calculator calculates; Minesweeper is playable and finished.</p><p>Everything else was cut on purpose. A file explorer would need a virtual file system and a permission model. A browser inside the desktop would need an iframe and a policy conversation. Clippy would need a personality. The four apps are enough to make the desktop feel inhabited, and each one is small enough to test.</p><p>The scope list was written before the code. That is the only reason the desktop shipped.</p><h2>Window state</h2><p>One reducer owns the desktop: an array of windows, a z-index counter and the active id. Each window has an app key, position, size, z-index, minimised and maximised flags, and a `restoreRect`. Opening, closing, focusing, moving, resizing, minimising and maximising are actions. The reducer is pure, which makes the geometry testable without a browser.</p><p>Dragging is the exception to the state rule. A pointer move writes a CSS transform on the window element, and the final position is dispatched on pointer up. Dispatching every move would re-render the whole desktop at pointer frequency. The transform keeps the drag on the compositor and the React tree quiet.</p><p>Maximising stores the previous rectangle before filling the desktop. Restoring returns to it. Without that, a maximised window that is restored to a default size loses the arrangement the user made, which is a small betrayal that makes the whole thing feel fake.</p><h2>The keyboard model</h2><p>The desktop is usable without a mouse, and the model is explained where it is used. The title bar is focusable with `tabIndex={0}`, labelled &quot;Move Notepad, arrow keys, Shift to jump&quot;, and handles arrows at 16 pixels or 48 with Shift. The handler is on the title bar, so typing in Notepad does not move the window.</p><p>Closing a window returns focus to its taskbar button. The taskbar uses roving tabindex: one button is in the tab sequence, and the arrow keys move between the open windows. That keeps the tab order short and still exposes every window.</p><p>The apps have their own keys. Minesweeper uses arrows to move, Enter to dig and F to flag; right-click also flags. Calculator listens for digits, operators, Enter, Escape and Backspace while focused. The keys are printed in the window, because a shortcut nobody can find is not a feature.</p><p>The desktop does not intercept `Alt+Tab`, `Ctrl+W` or other browser and operating-system shortcuts. A page that fights the window manager it lives in is not more authentic; it is just broken. The shortcuts it does own are the ones a page can own.</p><h2>Focus and screen readers</h2><p>Windows are non-modal dialogs, not a modal trap. Each has a label, a role and a focusable title bar. The taskbar is a toolbar with buttons. Opening a window moves focus into it; closing it restores focus to the opener. An `aria-live` region announces the window that opened or closed, so the change is not silent.</p><p>The desktop passes axe with zero serious or critical violations. That is not the same as being pleasant with a screen reader, so the keyboard journey is also tested end to end: open the desktop, open Notepad, type, minimise, restore, close, and return to the taskbar.</p><h2>Mobile and small screens</h2><p>The desktop does not pretend a 320-pixel phone is a desktop. Windows become full-screen sheets, dragging is disabled, and the taskbar stays at the bottom with 44-pixel buttons. The apps reflow rather than scale: Notepad is a text area, Paint is a canvas with a toolbar that wraps, Calculator is a keypad, Minesweeper&apos;s grid fits.</p><p>The page still has to pass the same checks at 320 pixels: no horizontal scroll, no control under 24 pixels, and the text-spacing override does not break the layout. The Win95 chrome is small by design, so the hit areas are expanded with padding and checked for overlap.</p><h2>Bundle isolation</h2><p>The desktop is not in the initial bundle. It is a dynamic import loaded when the secret opens. The four apps are components inside that chunk, so opening the desktop downloads all four, but the home page downloads none of them.</p><p>The CSS is scoped to the desktop container. The grey palette and the pixel borders do not leak into the rest of the site, and the site&apos;s theme tokens do not leak in. That isolation is what lets the desktop look wrong on purpose without making the rest of the page look wrong by accident.</p><h2>Testing</h2><p>The reducer has unit tests for z-order, minimise and restore, and the geometry of snapping. The end-to-end suite covers the keyboard journey, the mobile layout, forced-colours mode, reduced motion and the axe audit. Visual baselines seed the random window placement, because a screenshot test that compares random positions fails for the wrong reason.</p><p>The drag test uses pointer events rather than mouse events, and it asserts the committed position after release, not the transform during the drag. That is the part a screenshot cannot check.</p><h2>What it taught</h2><p>The desktop is the most elaborate easter egg on the site and the one most likely to be dismissed as decoration. Building it properly took longer than the joke deserved, and the result is better for it: a keyboard user can open Minesweeper and play, a phone user gets a usable layout, and the page it lives on does not pay for it until the secret is found.</p><p>The lesson is not that every joke needs this much work. It is that the scope list is the feature. Four apps and one window manager is a desktop. A fifth app would have been a second project.</p>]]></content:encoded>
      </item>
      <item>
        <title>Building Win95 in React</title>
        <link>https://kotree.netlify.app/notes/2026-06-27-building-win95-in-react</link>
        <guid>https://kotree.netlify.app/notes/2026-06-27-building-win95-in-react</guid>
        <pubDate>Sat, 27 Jun 2026 00:00:00 GMT</pubDate>
        <category>react</category>
        <category>win95</category>
        <category>accessibility</category>
        <description><![CDATA[<p>A Windows 95 desktop in React is mostly a window manager with a dress code. The grey chrome is the memorable part, but the behaviour is what makes it feel real: windows that stack, minimise, restore, move and hand focus to each other without losing the plot.</p><h2>One reducer for the desktop</h2><p>All window state lives in one reducer: an array of windows, a z-index counter and the id of the active window. Each window carries its app, position, size, z-index, minimised and maximised flags, and a `restoreRect` so maximising and restoring does not lose the previous geometry.</p><p>Dragging does not go through React state on every pointer move. The pointer down captures the pointer, the move writes a transform, and the final position is committed on pointer up. A dispatch per mouse event re-renders every window and makes the drag feel heavy, especially on a laptop trackpad.</p><p>Opening an app is a registry lookup, not a switch in the JSX. The registry holds the title, the icon, the initial size and a lazy component. Adding a fifth app should not require editing the window manager.</p><h2>Focus is the feature</h2><p>The active window is the one with the highest z-index, and focusing a window brings it forward. That sounds trivial until the keyboard is involved. The title bar is focusable and labelled: &quot;Move Notepad, arrow keys, Shift to jump&quot;. The label is the documentation; a keyboard feature nobody can find is not an accessibility feature.</p><p>The title bar handles arrow keys at 16 pixels, or 48 with Shift. The window does not move while a field inside it has focus, because the handler is on the title bar, not on the document. That distinction prevents the desktop from stealing keystrokes from Notepad.</p><p>Closing a window returns focus to the taskbar button that opened it, or to the next window in the stack. Losing focus to the body after closing a dialog is the most common keyboard bug in fake desktops, and it is easy to miss with a mouse.</p><h2>The keyboard model, honestly</h2><p>The desktop does not try to own `Alt+Tab`. That belongs to the operating system, and a web page that intercepts it is a web page fighting the window manager it runs inside. Browser shortcuts such as `Ctrl+W` and `Ctrl+T` are also off limits. The shortcuts that remain are the ones a page can own without a fight: arrows to nudge, Enter to open, Escape to close a menu, and the app-specific keys.</p><p>Minesweeper is the best example. Arrows move the cursor, Enter digs, F plants a flag, and right-click does the same for people with a mouse. Calculator listens for digits, operators, Enter, Escape and Backspace while it has focus. Both are documented in the window, not in a help page nobody opens.</p><p>The taskbar uses roving tabindex: one button is in the tab order, and the arrow keys move between the others. That keeps the tab sequence short while still exposing every window. Without it, eight open windows means eight tab stops before the page content.</p><h2>Borders made of pixels</h2><p>The chrome is drawn with two-pixel borders in four colours and a hard shadow. `border-style: outset` looks tempting, but the browser chooses the shades and they differ between engines. Explicit colours keep the look stable: white and light grey on the top-left, dark grey and black on the bottom-right, with a navy title bar.</p><p>The icons are small images rendered with `image-rendering: pixelated`, so they stay crisp when the desktop scales. The font stack prefers a bitmap-era face and falls back to Tahoma and Verdana, which have the right proportions even if the pixels are smoother. No web font is loaded for the joke.</p><p>The title bar buttons keep their 16-pixel look but get a larger hit area, because the accessibility floor still applies inside an easter egg. The visual joke and the pointer target are separate measurements.</p><h2>Keeping it off the first paint</h2><p>The desktop is not part of the home page&apos;s critical path. It is loaded when someone opens the secret, in its own chunk; the apps are components inside that chunk. That keeps the window manager, the paint canvas and Minesweeper&apos;s game loop out of the initial bundle.</p><p>Inside the desktop, each window is memoised on its own props. Moving one window does not re-render the others. The drag uses a transform rather than `left` and `top`, so the compositor can handle it, and the desktop container gets `contain: layout paint` to stop the windows from affecting the rest of the page.</p><p>The result is a toy that does not tax the page it lives on. That is the whole trick: the costume is elaborate, but the machinery is small.</p>]]></description>
        <content:encoded><![CDATA[<p>A Windows 95 desktop in React is mostly a window manager with a dress code. The grey chrome is the memorable part, but the behaviour is what makes it feel real: windows that stack, minimise, restore, move and hand focus to each other without losing the plot.</p><h2>One reducer for the desktop</h2><p>All window state lives in one reducer: an array of windows, a z-index counter and the id of the active window. Each window carries its app, position, size, z-index, minimised and maximised flags, and a `restoreRect` so maximising and restoring does not lose the previous geometry.</p><p>Dragging does not go through React state on every pointer move. The pointer down captures the pointer, the move writes a transform, and the final position is committed on pointer up. A dispatch per mouse event re-renders every window and makes the drag feel heavy, especially on a laptop trackpad.</p><p>Opening an app is a registry lookup, not a switch in the JSX. The registry holds the title, the icon, the initial size and a lazy component. Adding a fifth app should not require editing the window manager.</p><h2>Focus is the feature</h2><p>The active window is the one with the highest z-index, and focusing a window brings it forward. That sounds trivial until the keyboard is involved. The title bar is focusable and labelled: &quot;Move Notepad, arrow keys, Shift to jump&quot;. The label is the documentation; a keyboard feature nobody can find is not an accessibility feature.</p><p>The title bar handles arrow keys at 16 pixels, or 48 with Shift. The window does not move while a field inside it has focus, because the handler is on the title bar, not on the document. That distinction prevents the desktop from stealing keystrokes from Notepad.</p><p>Closing a window returns focus to the taskbar button that opened it, or to the next window in the stack. Losing focus to the body after closing a dialog is the most common keyboard bug in fake desktops, and it is easy to miss with a mouse.</p><h2>The keyboard model, honestly</h2><p>The desktop does not try to own `Alt+Tab`. That belongs to the operating system, and a web page that intercepts it is a web page fighting the window manager it runs inside. Browser shortcuts such as `Ctrl+W` and `Ctrl+T` are also off limits. The shortcuts that remain are the ones a page can own without a fight: arrows to nudge, Enter to open, Escape to close a menu, and the app-specific keys.</p><p>Minesweeper is the best example. Arrows move the cursor, Enter digs, F plants a flag, and right-click does the same for people with a mouse. Calculator listens for digits, operators, Enter, Escape and Backspace while it has focus. Both are documented in the window, not in a help page nobody opens.</p><p>The taskbar uses roving tabindex: one button is in the tab order, and the arrow keys move between the others. That keeps the tab sequence short while still exposing every window. Without it, eight open windows means eight tab stops before the page content.</p><h2>Borders made of pixels</h2><p>The chrome is drawn with two-pixel borders in four colours and a hard shadow. `border-style: outset` looks tempting, but the browser chooses the shades and they differ between engines. Explicit colours keep the look stable: white and light grey on the top-left, dark grey and black on the bottom-right, with a navy title bar.</p><p>The icons are small images rendered with `image-rendering: pixelated`, so they stay crisp when the desktop scales. The font stack prefers a bitmap-era face and falls back to Tahoma and Verdana, which have the right proportions even if the pixels are smoother. No web font is loaded for the joke.</p><p>The title bar buttons keep their 16-pixel look but get a larger hit area, because the accessibility floor still applies inside an easter egg. The visual joke and the pointer target are separate measurements.</p><h2>Keeping it off the first paint</h2><p>The desktop is not part of the home page&apos;s critical path. It is loaded when someone opens the secret, in its own chunk; the apps are components inside that chunk. That keeps the window manager, the paint canvas and Minesweeper&apos;s game loop out of the initial bundle.</p><p>Inside the desktop, each window is memoised on its own props. Moving one window does not re-render the others. The drag uses a transform rather than `left` and `top`, so the compositor can handle it, and the desktop container gets `contain: layout paint` to stop the windows from affecting the rest of the page.</p><p>The result is a toy that does not tax the page it lives on. That is the whole trick: the costume is elaborate, but the machinery is small.</p>]]></content:encoded>
      </item>
      <item>
        <title>An AI terminal without a backend</title>
        <link>https://kotree.netlify.app/notes/2026-07-25-an-ai-terminal-without-a-backend</link>
        <guid>https://kotree.netlify.app/notes/2026-07-25-an-ai-terminal-without-a-backend</guid>
        <pubDate>Sat, 25 Jul 2026 00:00:00 GMT</pubDate>
        <category>ai</category>
        <category>react</category>
        <category>privacy</category>
        <description><![CDATA[<p>An AI terminal sounds like a server: an API key, a queue, a database of conversations, a bill. It can also be a static page. The commands run in the browser, the model call goes straight to a provider that allows browser requests, and the key belongs to the person using it. No backend means no transcript to leak and no quota to fund, at the cost of a narrower set of things the feature can do.</p><h2>Commands before chat</h2><p>The first token decides where the input goes. A registry maps names and aliases to local functions: `help`, `notes`, `theme`, `goto`, `clear`, `whoami`. These never touch the network. They are fast, they work offline, and they are the part people use most.</p><p>Only the leftover text becomes a prompt. That split keeps the terminal useful without a key, makes the common actions deterministic, and gives the model a smaller job. A failed command can be fixed; a model that mishears &quot;open notes&quot; is a mystery.</p><p>The registry is a plain array, so help and autocomplete share one source.</p><h2>Streaming without a framework</h2><p>The provider returns a stream, usually server-sent events. `fetch` gives a `ReadableStream`; a `TextDecoder` turns bytes into text; a small buffer splits on blank lines and parses the `data:` payloads. The parser has to tolerate a chunk boundary in the middle of an event, which is the part most hand-rolled SSE readers get wrong.</p><p>Tokens arrive faster than a React render should. Appending each one to state produces hundreds of renders and a janky cursor. The terminal buffers tokens and flushes once per animation frame, or every 50 milliseconds, whichever comes first. Markdown is rendered at the end of the stream, not on every token; halfway through a code fence is not a useful parse.</p><p>An `AbortController` is wired to the Stop button and to unmount. Without it, a closed tab keeps reading a stream until the provider gives up. The abort error is not shown as a failure; it is a normal way to stop.</p><h2>Citations or silence</h2><p>The prompt includes a short context built from the site&apos;s own search index. A local scoring pass picks the three or four notes that share the most terms with the question, and the prompt says to answer from those excerpts and to say when they do not cover it. The response is asked to end with links in a fixed form.</p><p>The renderer only accepts links whose URLs are in the index it supplied. A model can invent a plausible URL, and a terminal that turns that into a clickable link is a small phishing engine. Anything unrecognised is shown as text, not as an anchor. Model output is never inserted as HTML; it goes through the same Markdown renderer as the rest of the site, with raw HTML disabled.</p><p>If no note scores above a threshold, the terminal says it does not know rather than answering from general knowledge. That is a deliberate limitation. A personal site&apos;s assistant should be able to say &quot;not in the notes&quot;.</p><h2>Limits, visible and enforced</h2><p>The provider&apos;s rate limit is the real limit, but the page should not discover it by burning a request. A token bucket in memory caps requests per minute and per session. The input is disabled during a request, which also limits concurrency.</p><p>A 429 is handled with `Retry-After` if the provider sends it, and a capped exponential backoff if not. A 401 means the key is wrong; say so and offer the settings field again. A 5xx is a provider problem, not a user error. None of these should wipe the prompt.</p><p>Output tokens are capped, the prompt is capped, and the request has a timeout. An unbounded response feels broken and expensive at the same time.</p><h2>Falling back</h2><p>Without a key, the terminal still works. Local commands answer, and a short list of example questions explains what the model would add. When offline, it says so and suggests the notes, which are cached. When the provider fails, the last answer stays on screen with a retry action rather than being replaced by an error page.</p><p>The key lives in memory and, if the user asks, in `sessionStorage`. It is never put in a URL, never logged, and never sent anywhere except the provider&apos;s endpoint. The privacy note says the provider sees the prompt; pretending otherwise would be dishonest. The terminal does not store transcripts, which also means it cannot offer history. That is a feature with a cost, and the cost is worth stating.</p><p>No backend is not a moral position. It is a set of trade-offs: no server bill, no transcript database, no shared key to abuse, and no ability to hide the provider from the visitor. For a terminal on a personal site, those are the right trades.</p>]]></description>
        <content:encoded><![CDATA[<p>An AI terminal sounds like a server: an API key, a queue, a database of conversations, a bill. It can also be a static page. The commands run in the browser, the model call goes straight to a provider that allows browser requests, and the key belongs to the person using it. No backend means no transcript to leak and no quota to fund, at the cost of a narrower set of things the feature can do.</p><h2>Commands before chat</h2><p>The first token decides where the input goes. A registry maps names and aliases to local functions: `help`, `notes`, `theme`, `goto`, `clear`, `whoami`. These never touch the network. They are fast, they work offline, and they are the part people use most.</p><p>Only the leftover text becomes a prompt. That split keeps the terminal useful without a key, makes the common actions deterministic, and gives the model a smaller job. A failed command can be fixed; a model that mishears &quot;open notes&quot; is a mystery.</p><p>The registry is a plain array, so help and autocomplete share one source.</p><h2>Streaming without a framework</h2><p>The provider returns a stream, usually server-sent events. `fetch` gives a `ReadableStream`; a `TextDecoder` turns bytes into text; a small buffer splits on blank lines and parses the `data:` payloads. The parser has to tolerate a chunk boundary in the middle of an event, which is the part most hand-rolled SSE readers get wrong.</p><p>Tokens arrive faster than a React render should. Appending each one to state produces hundreds of renders and a janky cursor. The terminal buffers tokens and flushes once per animation frame, or every 50 milliseconds, whichever comes first. Markdown is rendered at the end of the stream, not on every token; halfway through a code fence is not a useful parse.</p><p>An `AbortController` is wired to the Stop button and to unmount. Without it, a closed tab keeps reading a stream until the provider gives up. The abort error is not shown as a failure; it is a normal way to stop.</p><h2>Citations or silence</h2><p>The prompt includes a short context built from the site&apos;s own search index. A local scoring pass picks the three or four notes that share the most terms with the question, and the prompt says to answer from those excerpts and to say when they do not cover it. The response is asked to end with links in a fixed form.</p><p>The renderer only accepts links whose URLs are in the index it supplied. A model can invent a plausible URL, and a terminal that turns that into a clickable link is a small phishing engine. Anything unrecognised is shown as text, not as an anchor. Model output is never inserted as HTML; it goes through the same Markdown renderer as the rest of the site, with raw HTML disabled.</p><p>If no note scores above a threshold, the terminal says it does not know rather than answering from general knowledge. That is a deliberate limitation. A personal site&apos;s assistant should be able to say &quot;not in the notes&quot;.</p><h2>Limits, visible and enforced</h2><p>The provider&apos;s rate limit is the real limit, but the page should not discover it by burning a request. A token bucket in memory caps requests per minute and per session. The input is disabled during a request, which also limits concurrency.</p><p>A 429 is handled with `Retry-After` if the provider sends it, and a capped exponential backoff if not. A 401 means the key is wrong; say so and offer the settings field again. A 5xx is a provider problem, not a user error. None of these should wipe the prompt.</p><p>Output tokens are capped, the prompt is capped, and the request has a timeout. An unbounded response feels broken and expensive at the same time.</p><h2>Falling back</h2><p>Without a key, the terminal still works. Local commands answer, and a short list of example questions explains what the model would add. When offline, it says so and suggests the notes, which are cached. When the provider fails, the last answer stays on screen with a retry action rather than being replaced by an error page.</p><p>The key lives in memory and, if the user asks, in `sessionStorage`. It is never put in a URL, never logged, and never sent anywhere except the provider&apos;s endpoint. The privacy note says the provider sees the prompt; pretending otherwise would be dishonest. The terminal does not store transcripts, which also means it cannot offer history. That is a feature with a cost, and the cost is worth stating.</p><p>No backend is not a moral position. It is a set of trade-offs: no server bill, no transcript database, no shared key to abuse, and no ability to hide the provider from the visitor. For a terminal on a personal site, those are the right trades.</p>]]></content:encoded>
      </item>
      <item>
        <title>A service worker update people trust</title>
        <link>https://kotree.netlify.app/notes/2026-05-30-a-service-worker-update-people-trust</link>
        <guid>https://kotree.netlify.app/notes/2026-05-30-a-service-worker-update-people-trust</guid>
        <pubDate>Sat, 30 May 2026 00:00:00 GMT</pubDate>
        <category>pwa</category>
        <category>service-worker</category>
        <category>ux</category>
        <description><![CDATA[<p>The first version of a service worker is easy. The update is where it earns trust. A new worker installs, finds an old page still open, and waits. The page can ignore it, reload under the user, or ask. The default lifecycle already chooses the safest option; the temptation is to override it for a faster deploy.</p><h2>Why not skipWaiting by default</h2><p>`self.skipWaiting()` moves the new worker from waiting to active immediately and lets it claim the open pages. That sounds clean. In practice the old page is still running old JavaScript while the new worker serves a new cache. A lazy-loaded chunk from the old build may no longer exist, or may arrive with a different hash. The page half-works until it is reloaded, which is worse than a clearly stale page.</p><p>There is also the human cost. Someone typing a guestbook message, editing a Notepad draft or halfway through a form does not want the page to reload because a deploy happened. The safe default is to let the old worker control the old page, install the new one in the background, and ask.</p><h2>Making the prompt honest</h2><p>The page can detect a waiting worker in two places. On load, `navigator.serviceWorker.ready` resolves to a registration whose `waiting` property may already be set. During the session, the `updatefound` event fires, and the new worker&apos;s `state` moves to `installed`; if there is already a controller, that worker is waiting.</p><p>When that happens, show a persistent but non-blocking message: a new version is ready, with Refresh and Later. Do not use a modal for a deploy. Do not reload on a timer. If the page has unsaved state, the Refresh action should warn first, and the warning should name the state rather than saying &quot;unsaved changes&quot;.</p><p>On accept, post `SKIP_WAITING` to the waiting worker. The worker calls `self.skipWaiting()`, activates, and the page listens for `controllerchange`. Reload once, guarded by a flag, because `controllerchange` can fire more than once in a messy update and a reload loop is a memorable bug.</p><pre><code>navigator.serviceWorker.addEventListener(&apos;controllerchange&apos;, () =&gt; {
  if (refreshing) return;
  refreshing = true;
  location.reload();
});</code></pre><p>The prompt should also survive a reload. If the user chooses Later, the waiting worker is still there on the next visit; the page should find it again rather than pretending the update never happened.</p><h2>Cache versions and the queue</h2><p>The cache name carries the build id or a version number. On activate, delete every cache that is not in the keep-list. The keep-list must include the data cache used by the offline queue, or an update becomes a data-loss event.</p><p>The HTML strategy matters too. A network-first page with a cache fallback gets the new document when online and the old one when not. A cache-first page can serve an old document that references assets the new worker has already deleted. If the app uses cache-first HTML, keep the previous build&apos;s assets for at least one release.</p><p>The worker script should be served with `Cache-Control: no-cache` so a proxy does not keep an old copy; the browser revalidates it on update anyway. Checks run on navigation and at most once every 24 hours, so a long-lived tab may need a nudge. `registration.update()` on `visibilitychange`, throttled to a few hours, is enough.</p><h2>Testing an update</h2><p>The update path is hard to test because it needs two versions. A unit test can cover the cache-name and keep-list logic. An end-to-end test needs a fixture worker, or a build step that changes the version and serves the new script.</p><p>The useful assertions are behavioural: the old page still works after the new worker installs; the prompt appears; Later leaves the page alone; Refresh activates the new worker and reloads once; the old cache is gone; the queue still holds its item. A test that only checks that `sw.js` was fetched proves nothing.</p><p>It is also worth testing the failure. If the new worker&apos;s install throws, the old worker should keep controlling the page. A failed update should leave the site working, not unregister the worker in a panic.</p><h2>The edge cases</h2><p>Safari does not support Background Sync, and iOS can evict a service worker after disuse. The prompt still works while the page is open, but &quot;it will update in the background&quot; is not a promise there. Say &quot;refresh to update&quot; instead.</p><p>A hard reload bypasses the worker, which is useful for debugging and confusing for support. The page should say what happened after the reload: the version, in the footer or the about panel, is enough.</p><p>Keep the old worker&apos;s caches until the new one is active. Deleting them during install leaves a window where neither version can serve the page. Activate is the right place, after the new worker is in control.</p>]]></description>
        <content:encoded><![CDATA[<p>The first version of a service worker is easy. The update is where it earns trust. A new worker installs, finds an old page still open, and waits. The page can ignore it, reload under the user, or ask. The default lifecycle already chooses the safest option; the temptation is to override it for a faster deploy.</p><h2>Why not skipWaiting by default</h2><p>`self.skipWaiting()` moves the new worker from waiting to active immediately and lets it claim the open pages. That sounds clean. In practice the old page is still running old JavaScript while the new worker serves a new cache. A lazy-loaded chunk from the old build may no longer exist, or may arrive with a different hash. The page half-works until it is reloaded, which is worse than a clearly stale page.</p><p>There is also the human cost. Someone typing a guestbook message, editing a Notepad draft or halfway through a form does not want the page to reload because a deploy happened. The safe default is to let the old worker control the old page, install the new one in the background, and ask.</p><h2>Making the prompt honest</h2><p>The page can detect a waiting worker in two places. On load, `navigator.serviceWorker.ready` resolves to a registration whose `waiting` property may already be set. During the session, the `updatefound` event fires, and the new worker&apos;s `state` moves to `installed`; if there is already a controller, that worker is waiting.</p><p>When that happens, show a persistent but non-blocking message: a new version is ready, with Refresh and Later. Do not use a modal for a deploy. Do not reload on a timer. If the page has unsaved state, the Refresh action should warn first, and the warning should name the state rather than saying &quot;unsaved changes&quot;.</p><p>On accept, post `SKIP_WAITING` to the waiting worker. The worker calls `self.skipWaiting()`, activates, and the page listens for `controllerchange`. Reload once, guarded by a flag, because `controllerchange` can fire more than once in a messy update and a reload loop is a memorable bug.</p><pre><code>navigator.serviceWorker.addEventListener(&apos;controllerchange&apos;, () =&gt; {
  if (refreshing) return;
  refreshing = true;
  location.reload();
});</code></pre><p>The prompt should also survive a reload. If the user chooses Later, the waiting worker is still there on the next visit; the page should find it again rather than pretending the update never happened.</p><h2>Cache versions and the queue</h2><p>The cache name carries the build id or a version number. On activate, delete every cache that is not in the keep-list. The keep-list must include the data cache used by the offline queue, or an update becomes a data-loss event.</p><p>The HTML strategy matters too. A network-first page with a cache fallback gets the new document when online and the old one when not. A cache-first page can serve an old document that references assets the new worker has already deleted. If the app uses cache-first HTML, keep the previous build&apos;s assets for at least one release.</p><p>The worker script should be served with `Cache-Control: no-cache` so a proxy does not keep an old copy; the browser revalidates it on update anyway. Checks run on navigation and at most once every 24 hours, so a long-lived tab may need a nudge. `registration.update()` on `visibilitychange`, throttled to a few hours, is enough.</p><h2>Testing an update</h2><p>The update path is hard to test because it needs two versions. A unit test can cover the cache-name and keep-list logic. An end-to-end test needs a fixture worker, or a build step that changes the version and serves the new script.</p><p>The useful assertions are behavioural: the old page still works after the new worker installs; the prompt appears; Later leaves the page alone; Refresh activates the new worker and reloads once; the old cache is gone; the queue still holds its item. A test that only checks that `sw.js` was fetched proves nothing.</p><p>It is also worth testing the failure. If the new worker&apos;s install throws, the old worker should keep controlling the page. A failed update should leave the site working, not unregister the worker in a panic.</p><h2>The edge cases</h2><p>Safari does not support Background Sync, and iOS can evict a service worker after disuse. The prompt still works while the page is open, but &quot;it will update in the background&quot; is not a promise there. Say &quot;refresh to update&quot; instead.</p><p>A hard reload bypasses the worker, which is useful for debugging and confusing for support. The page should say what happened after the reload: the version, in the footer or the about panel, is enough.</p><p>Keep the old worker&apos;s caches until the new one is active. Deleting them during install leaves a window where neither version can serve the page. Activate is the right place, after the new worker is in control.</p>]]></content:encoded>
      </item>
      </channel>
    </rss>