<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Enzo Junior Vezzaro on Medium]]></title>
        <description><![CDATA[Stories by Enzo Junior Vezzaro on Medium]]></description>
        <link>https://medium.com/@enzovezzaro?source=rss-a225e16db862------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lH2PW7fOGHTn2mTfivIKFA.jpeg</url>
            <title>Stories by Enzo Junior Vezzaro on Medium</title>
            <link>https://medium.com/@enzovezzaro?source=rss-a225e16db862------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 09:43:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@enzovezzaro/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I built a Mac menu bar app that pauses music while AI talks]]></title>
            <link>https://medium.com/@enzovezzaro/how-i-built-a-mac-menu-bar-app-that-pauses-music-while-ai-talks-9aefa9d55562?source=rss-a225e16db862------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aefa9d55562</guid>
            <dc:creator><![CDATA[Enzo Junior Vezzaro]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 18:03:20 GMT</pubDate>
            <atom:updated>2026-11-18T18:03:20.010Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m the maker of Oreja. I built it to solve a small annoyance in my own day, and I want to be honest about what it does, how it works, and which parts I have actually tested.</p><h3>The small annoyance</h3><p>If you talk to a voice assistant on your Mac while music is playing, you know the problem. You ask a question, the assistant starts answering, and your music keeps playing over it. You end up reaching for the volume or pausing the track by hand, then remembering to start it again when the answer finishes.</p><p>I wanted the music to step aside on its own while the assistant spoke, and come back when it stopped. That is the whole idea behind Oreja de Van Gogh, a free and open source menu bar app for macOS 14.2 and later. It is released under GPL-3.0.</p><h3>What Oreja actually does</h3><p>Oreja watches a set of apps you choose, like ChatGPT, Claude, coding agents, call apps, or browsers. When one of them starts producing speech, Oreja pauses or lowers Apple Music. When the speech stops, it restores your music. You pick which processes to watch from the menu bar.</p><p>The app is independent. It is not affiliated with OpenAI or Apple. There is no account to create, no API key to paste in, and no network connection at all. Once it is installed, it works entirely on your machine.</p><h3>The in-memory audio level and why nothing is stored</h3><p>This part matters to me, so I’ll be specific. Oreja taps the audio output of the Core Audio processes you select. From that tap it derives a single number, a dBFS level, which is a measure of loudness. It keeps that number in memory just long enough to decide whether speech is happening, then discards it immediately.</p><p>That is the entire data path. There is no recording, no transcription, no storage, and no upload. Nothing is written to disk, and nothing leaves the machine. If you are cautious about an app listening to your audio, I think this design is worth understanding before you decide whether to trust it.</p><h3>The deterministic state machine</h3><p>The decision about when to duck or pause the music lives in a module I call OrejaCore. It is a deterministic state machine. Given the same sequence of audio levels, it always produces the same decisions.</p><p>I kept that module deliberately free of AppKit, Core Audio, and AppleScript. Those are the parts that talk to the operating system, and they are hard to test in isolation. By keeping them out of the decision logic, I can unit test the state machine directly with plain inputs. It is a small design choice, but it is what lets me reason about the behavior without launching the full app.</p><h3>What the controlled fixture proved and the measured latency</h3><p>Here is what I have actually verified. I set up a controlled fixture that feeds a known audio signal into the capture path. Against that fixture, I confirmed that Core Audio capture works and that Apple Music pause and resume works. I also measured the time from the start of the signal to the music pausing. It came out around 187 to 201 milliseconds in that fixture.</p><p>That number comes from a controlled setup. I would not treat it as a promise about how every machine behaves. Real devices and real audio chains will vary.</p><h3>What is still untested</h3><p>There are things I have not proven, and I would rather say so plainly.</p><p>I have not tested Oreja against a live ChatGPT Voice session. The fixture tells me the pieces work together, but it is not the same as a real voice conversation on a real account. I have also not tested AirPods or switching between audio devices. Device switching on macOS has its own set of quirks, and until I have tested it I will not claim it works.</p><p>Two other limits are worth knowing. Spotify native is not supported, and neither is Firefox.</p><h3>The signing reality on macOS</h3><p>Oreja is ad hoc signed and not notarized. On macOS that means the first launch takes one extra step. When you open it, macOS will block it, and you need to go to System Settings, then Privacy and Security, and choose Open Anyway. You only need to do this once. It is a normal consequence of distributing an app outside the App Store without notarization, and I decided to be upfront about it rather than bury it.</p><h3>What is next</h3><p>The next thing I want to do is test against a live voice session and work through device switching. Those are the two gaps between the controlled fixture and everyday use. After that, I will look at broader browser and music app support if there is real demand.</p><p>If you try it, I would like to hear what happened, especially where it did not work.</p><p>https://oreja-tau.vercel.app/</p><p>https://github.com/EnzoVezzaro/oreja/releases/latest</p><p>What app or device combination would you need Oreja to support before it would be useful in your daily work?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aefa9d55562" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The portfolio you have to find in the street]]></title>
            <link>https://medium.com/@enzovezzaro/the-portfolio-you-have-to-find-in-the-street-59cee33537aa?source=rss-a225e16db862------2</link>
            <guid isPermaLink="false">https://medium.com/p/59cee33537aa</guid>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Enzo Junior Vezzaro]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 15:15:19 GMT</pubDate>
            <atom:updated>2026-09-18T15:32:09.690Z</atom:updated>
            <content:encoded><![CDATA[<p>The site won’t open until you’re holding a sticker that’s somewhere in New York.</p><p>This is literal. There’s no login form and no password and no email address to type in. You find a sticker — they’re taped around the city — and you point a camera at the QR code. The page checks the code on your phone: is it real, is it still active? Nothing asks a server to look you up. The check happens in your browser, in a second. If the code is good, the site opens. If the sticker was retired, you get four words: ARTIFACT REVOKED. That’s the end of the ride.</p><p>So this is what 25 stickers, a little cryptography, and a static site look like. We’re Underground Software Engineers of NYC, a crew that builds web software with AI doing much of the generation. This project is our portfolio, and it lives on the street.</p><h3>The door is a sticker</h3><p>A sticker has a QR code and nothing else. No URL printed under it. Scan it and you get a token — a short strip of text that looks like this:</p><pre>UG3.&lt;one long string of characters&gt;</pre><p>That string is three things in one:</p><ul><li>a signature — a sealed stamp proving the code was written by us and not altered since. A trip through the browser’s built-in crypto handles it.</li><li>an encrypted contact card — the operator’s card, and it only decrypts after the signature checks out, so only the person holding the sticker can read it.</li><li>a serial number — linked to the public registry, which is just the plain list of every sticker we’ve minted and its status today.</li></ul><p>Scan, verify, check the registry, open. Four steps, all on your phone, no server to call home.</p><h3>The part we had to decide</h3><p>Generating a QR code is the easy fifty percent. Any AI does it, and our AI generates a lot here: the React components, the TypeScript, the whole visual journey behind the door.</p><p>The part that took an engineer was deciding what a sticker means. Signatures, retirement rules, a registry that stays public, a deployment you can pin to a hash — those seams are the system. The machine wrote the code; we drew the track.</p><h3>Out on the street</h3><p>Twenty-five stickers minted. Fourteen live in the city right now. Five are the generic door — a newcomer who finds one walks in. The rest are field pieces at posted locations.</p><p>One field sticker taught us more than a blog post would have. We minted it under our first token format (version 2), then moved to version 3 with the full contact card. The old sticker is still signed and still verifiable; it reads REVOKED in the registry. Tokens get retired, never destroyed, and the registry keeps the whole history public.</p><p>The deploy loop is mostly walking, by the way. Some of our best architecture is the part where someone tapes a sticker to a pole.</p><h3>No server to keep awake</h3><p>Every build ships as one immutable snapshot, identified by a content hash — deploy thirteen is live now. Rolling back is republishing an older snapshot, not a late-night git emergency.</p><p>And every link we put out runs through a shortener we self-host. One per campaign, so we know exactly which post drove somebody toward a sticker, and there’s no third-party tracker on the site.</p><p>Honest disclaimer we put on everything: nothing here is unhackable. Signatures and a ledger do what they can, and the registry is public so anyone can check.</p><h3>That’s the whole thing</h3><p>We build web software for people who need a system that holds, not a demo that photographs well. The machine generates; the crew navigates.</p><p>If you’re in New York, the map is the city. Find a sticker, scan it, get in — <a href="https://sink.undergroundsoftwareengineersnyc.workers.dev/c-434d0ac0">the door is a QR code</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59cee33537aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The last 10% is the product: shipping an AI-built, engineer-held web system in NYC]]></title>
            <link>https://medium.com/@enzovezzaro/the-last-10-is-the-product-shipping-an-ai-built-engineer-held-web-system-in-nyc-35131ead2151?source=rss-a225e16db862------2</link>
            <guid isPermaLink="false">https://medium.com/p/35131ead2151</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[new-york-city]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Enzo Junior Vezzaro]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 00:09:28 GMT</pubDate>
            <atom:updated>2026-09-14T00:09:28.592Z</atom:updated>
            <content:encoded><![CDATA[<p>Every engineering demo dies in the same place: the gap between 80% and 100%.</p><p>AI closes most of that gap on its own. It scaffolds the app, wires the flows, generates the screens. What it does not do is hold production — the failure modes, the load, the edge cases nobody wrote a prompt for. That last stretch is not typing. It is judgment.</p><p>We are Underground Software Engineers of NYC, and we built our own proof of that judgment: a city-scale artifact system that most teams would never attempt with generated code alone.</p><p>The system works like this. We mint physical QR stickers — each one encodes a versioned token with a packed binary layout, AES-256-GCM encrypted, signed with ECDSA P-256. A phone that scans one verifies the entire chain in the browser: signature, registry status, revocation state. No server. No accounts. The site itself is a pure static build pinned to IPFS, republished through IPNS on every deploy, with hash routing so it works unchanged behind any gateway.</p><p>Scans run through our own self-hosted link engine on Cloudflare — Workers and D1 we operate ourselves — so every touch is attributable without a third-party tracker in sight. Stickers can be revoked cryptographically; version upgrades keep the old ones verifying. Nothing about the system depends on trusting a vendor.</p><p>What did the AI generate? Scaffolding, components, first drafts of flows — real leverage, we are not pretending otherwise. What did the crew engineer? The token format and its versioning, the crypto verification path, the WebGL budget that stopped the sticker board from melting phones, the deploy pipeline that pins one immutable DAG and republishes IPNS on every push, and the decision — repeatedly — to delete the clever thing and ship the boring one that holds.</p><p>That is the last 10%. It is not the remaining work; it is the remaining accountability.</p><p>The field has 14 active signed stickers. Thirteen deploys. Zero rollbacks. The numbers are small and public and checkable, which is the point — the work verifies itself the same way its artifacts do.</p><p>We take on web systems of any stack and any language across NYC: the AI-built app that needs to survive its first thousand real users, the landing experience that has to load behind a QR printed on a wall, the pipeline someone has to own when it fails at 2 a.m.</p><p>If your team has a demo stuck at 80%, we are the crew that takes it to 100%. The gate is sealed; the work speaks through it.</p><p>Start here: <a href="https://sink.undergroundsoftwareengineersnyc.workers.dev/c-76c7f851">https://sink.undergroundsoftwareengineersnyc.workers.dev/c-76c7f851</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35131ead2151" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Markdown Is All You Need — So I Built ACC]]></title>
            <link>https://medium.com/@enzovezzaro/markdown-is-all-you-need-so-i-built-acc-6f9f7283b758?source=rss-a225e16db862------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f9f7283b758</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Enzo Junior Vezzaro]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 16:45:33 GMT</pubDate>
            <atom:updated>2026-08-16T22:00:42.868Z</atom:updated>
            <content:encoded><![CDATA[<p><em>by Enzo Vezzaro — the story behind </em><a href="https://github.com/EnzoVezzaro/agents-code-context"><em>ACC, Agent Code Context</em></a></p><p>In 2017, eight Google researchers published a paper with one of the most confident titles in computer science:</p><p><strong>Attention Is All You Need.</strong></p><p>I love that title.</p><p>It’s almost arrogant.</p><p>Not <em>“Attention Is One Important Part of a New Architecture.”</em></p><p>Not <em>“Attention Is Useful.”</em></p><p>No.</p><p><strong>Attention is all you need.</strong></p><p>And, well… they were onto something.</p><p>That paper introduced the Transformer architecture, which ended up becoming one of the foundations of basically everything we’re doing with LLMs today.</p><p>Almost ten years later, I started seeing another sentence popping up everywhere:</p><p><strong>Markdown is all you need.</strong></p><p>And I thought:</p><blockquote><em>Wait… what? </em>😂</blockquote><p>Markdown?</p><p>The thing we use for README files?</p><p>The thing John Gruber created in 2004 because he wanted to write HTML without actually writing HTML?</p><p>Apparently, yes.</p><p>So I started reading.</p><p>And the more I read, the more I realized that a lot of people were independently arriving at the same idea.</p><p>There was:</p><ul><li><a href="https://jackpal.github.io/2025/03/07/Create_a_prompt_from_your_sources.html"><strong>“Markdown is all you need to get LLMs to read your source code”</strong></a> — Jack Palevich</li><li><a href="https://medium.com/@byeole88/markdown-is-all-you-need-1b8ffb2c9ab6"><strong>“Markdown is all you need!?”</strong></a> — Bhavesh Yeole</li><li><a href="https://blog.hartleybrody.com/markdown-research-planning/"><strong>“Markdown is the new source code”</strong></a> — Hartley Brody</li><li><a href="https://www.linkedin.com/pulse/markdown-all-you-need-york-yong-yeo-h6n9c"><strong>“Markdown is All You Need”</strong></a> — York Yong Yeo</li><li><a href="https://www.linkedin.com/pulse/markdown-new-source-code-gouri-shankar-swamy-nn6cc"><strong>“Markdown Is the New Source Code”</strong></a> — Gouri Shankar Swamy</li><li><a href="https://juliofalbo.medium.com/markdown-is-the-new-api-how-skill-md-and-ai-gateways-unlock-ai-native-organizations-e929d05c0470"><strong>“Markdown is the New API”</strong></a> — Júlio Falbo</li></ul><p>the whole <strong>Skills vs MCP</strong> conversation around OpenClaw</p><ul><li><strong>JUMON</strong></li><li><strong>Scratch</strong></li></ul><p>the recent discussion around <strong>spec-driven development</strong></p><ul><li>and Mr. Kelly’s idea that maybe we shouldn’t build more agents at all — maybe we should just <strong>redirect the agents we already have</strong>.</li></ul><p>I read all of them.</p><p>And honestly?</p><p>I agree with almost all of them.</p><p>But after reading all of this, I ended up asking myself a slightly different question:</p><blockquote><strong><em>Okay… if everyone is right, what would this actually look like inside a real repository?</em></strong></blockquote><p>So, naturally…</p><p>I built something.</p><h3>The problem started much earlier</h3><p>I’ve been working extensively with AI coding agents for years now (since they we’re call “autocomplete”).</p><p>And this has been one of the most interesting changes in the way I write software.</p><p>The agents are now good.</p><p>Really good.</p><p>Sometimes they do things that still surprise me (good and bad).</p><p>Give them a repository and a reasonably clear task and they’ll start exploring, finding files, understanding dependencies, writing code, running tests…</p><p>It’s pretty damn impressive.</p><p>But there was always one thing that annoyed me.</p><p>Every new session started with the same explanations.</p><p>Where things live.</p><p>Why something is implemented in that weird way.</p><p>Which module owns what.</p><p>Which file we absolutely should not touch.</p><p>What we already tried.</p><p>What broke last time.</p><p>Why that stupid-looking piece of code is actually important.</p><p>I’d spend an hour getting the agent up to speed.</p><p>Then the session would end.</p><p>Next day:</p><blockquote><em>“Okay, let’s continue.”</em></blockquote><p>And the agent would basically say:</p><blockquote><em>“Great! Let me inspect the repository.”</em></blockquote><p>Nooooo. <strong>We already did this! </strong>😂</p><p>But of course, the agent hadn’t really forgotten.</p><p>The information was simply never part of the project.</p><p>It was in the conversation.</p><p>And conversations are temporary.</p><p>The repository isn’t.</p><p>That distinction started bothering me more and more.</p><h3>If the agent forgets, why doesn’t the repository remember?</h3><p>This was probably the moment where ACC started.</p><p>I kept thinking about the same thing:</p><blockquote><strong>The repository is the one thing that survives everything.</strong></blockquote><p>I can change agents.</p><p>I can start a new conversation.</p><p>I can hit a context limit.</p><p>I can switch from Claude to Cursor to another tool.</p><p>The code is still there.</p><p>The Git history is still there.</p><p>The README is still there.</p><p>So why shouldn’t the knowledge we accumulate while working with agents be there too?</p><p>If I spend two hours explaining to an AI why the networking layer works a certain way…</p><p>why does that explanation disappear when the chat disappears?</p><p>Why isn’t it in the repository?</p><p>And that’s where I started looking much more seriously at Markdown.</p><h3>Why is everyone talking about Markdown?</h3><p>The interesting thing about all these articles isn’t really Markdown itself.</p><p>It’s <strong>structure</strong>.</p><p>The idea is that instead of giving an LLM a giant pile of information and hoping it figures things out, we give it information in a structure it already understands.</p><p>Bhavesh Yeole makes an interesting point in <em>Markdown is all you need!?</em>:</p><blockquote>LLMs are pattern machines.</blockquote><p>We give them patterns, and they continue those patterns.</p><p>And Markdown is basically everywhere in the material these models have consumed.</p><ul><li>GitHub.</li><li>Stack Overflow.</li><li>Documentation.</li><li>Tutorials.</li><li>README files.</li><li>Technical articles.</li><li>Code repositories.</li></ul><p>So when we give an agent something like:</p><pre>## Architecture</pre><pre>The API communicates with the service layer.</pre><pre>The service layer communicates with the database.</pre><pre>The UI must never access the database directly.</pre><p>we aren’t inventing some complicated new language.</p><p>We’re giving the model a structure it already knows.</p><p>And I think that’s one reason this whole thing is taking off.</p><h3>Markdown is also ridiculously convenient</h3><p>There’s another reason I like it.</p><p>It’s boring.</p><p>And I mean that as a compliment.</p><p>Markdown doesn’t need a runtime.</p><p>It doesn’t need a server.</p><p>It doesn’t need an SDK.</p><p>It doesn’t need a database.</p><p>You can open it in VS Code.</p><p>You can open it in Vim.</p><p>You can read it on GitHub.</p><p>You can diff it.</p><p>You can commit it.</p><p>You can send it to an AI.</p><p>And a human can read exactly the same thing.</p><p>That’s actually pretty rare.</p><p>Usually, when we optimize something for machines, it becomes annoying for humans.</p><p>Markdown is one of those weird cases where both sides get something useful.</p><h3>But then I started thinking about documentation</h3><p>This is where things became a little more complicated.</p><p>We’ve had documentation forever.</p><p>And documentation is great.</p><p>Until it isn’t.</p><p>We’ve all seen this:</p><pre>docs/architecture.md</pre><p>describing an architecture that hasn’t existed for six months.</p><p>The code changed.</p><p>The documentation didn’t.</p><p>So I didn’t want to create another giant architecture document.</p><p>I started thinking:</p><blockquote><strong><em>What if the context lived next to the code it describes?</em></strong></blockquote><p>If I’m working inside networking/, maybe the networking rules should be there.</p><p>If I’m working inside frontend/, maybe the frontend context should be there.</p><p>Something like:</p><pre>project/<br>├── AGENTS.md<br>├── frontend/<br>│   └── AGENTS.md<br>├── backend/<br>│   └── AGENTS.md<br>└── networking/<br>    └── AGENTS.md</pre><p>Now the repository starts to become a map.</p><p>And more importantly, the map follows the project.</p><p>Move the code?</p><p>Move its context.</p><p>Delete the subsystem?</p><p>Its context goes away too.</p><p>No giant documentation directory sitting somewhere becoming increasingly fictional.</p><p>That was the idea I wanted to explore.</p><h3>And then I found <a href="https://agents.md/?utm_source=chatgpt.com">AGENTS.md</a></h3><p>This was another important part of the puzzle.</p><p>I didn’t want to invent another format.</p><p>The ecosystem was already converging around things like:</p><p>AGENTS.md</p><p>CLAUDE.md</p><p>SKILL.md</p><p>copilot-instructions.md</p><p>So why create another one?</p><p>I don’t want:</p><pre>ACC.md<br>ACC_AGENTS.md<br>AGENT-CONTEXT.md</pre><p>just because I happened to build it 😂</p><p>If the ecosystem already has a standard, <strong>use the standard</strong>.</p><p>That’s why ACC treats AGENTS.md as a first-class part of the repository rather than trying to replace it.</p><p>And this became one of the most important principles of the whole project:</p><blockquote><strong><em>ACC should be optional.</em></strong></blockquote><p>An agent that knows nothing about ACC should still be able to work with an ACC repository.</p><p>It’s just Markdown.</p><p>It’s just files.</p><p>It’s still a normal Git repository.</p><p>If you remove the ACC CLI tomorrow, the project shouldn’t suddenly become useless.</p><p>That’s important to me.</p><p>I don’t want another lock-in.</p><h3>So… I built ACC</h3><p>At this point, I had enough questions that I couldn’t really stop myself.</p><p>So I started building.</p><p><strong>ACC — Agent Code Context.</strong></p><p>The basic idea is:</p><blockquote><strong><em>Make the repository self-describing for AI agents.</em></strong></blockquote><p>Not by creating another AI.</p><p>Not by creating another proprietary memory system.</p><p>Not by replacing MCP.</p><p>Not by replacing Skills.</p><p>Just by making the repository better at explaining itself.</p><p>And this is where the project started getting much more interesting than I expected.</p><h3>The repository is the product</h3><p>One of the things I kept coming back to while designing ACC was:</p><p><strong>The repository is the product.</strong></p><p>Not ACC.</p><p>Not the CLI.</p><p>Not the agent.</p><p>The repository.</p><p>The context belongs next to the code.</p><p>The rules belong next to the code.</p><p>The memory belongs in the repository.</p><p>For example, ACC can keep durable memory in .acc-memory.md.</p><p>And that sounds like a tiny detail.</p><p>But think about what it means.</p><p>I can switch agents.</p><p>I can close the conversation.</p><p>I can start a new session.</p><p>I can bring another developer into the project.</p><p>The accumulated context doesn’t disappear.</p><p>Because it was never the agent’s.</p><p><strong>It was the project’s.</strong></p><p>That was the property I was actually looking for.</p><h3>Then I ran into the architecture problem</h3><p>Okay.</p><p>If we’re going to make the repository self-describing, we need to understand its architecture.</p><p>Easy, right?</p><p>Let’s just create:</p><pre>graph.yaml</pre><p>and describe everything there.</p><p>Except… It’s not a good idea 👎🏽</p><p>Because now we have another thing that can become stale.</p><p>The code changes.</p><p>The graph doesn’t.</p><p>So ACC takes a different approach.</p><p><strong>Derive the graph instead of maintaining it.</strong></p><p>ACC can look at what the repository declares and what the source actually reveals.</p><p>And then there’s one more distinction I really wanted.</p><p>Not every fact is equally trustworthy.</p><h3>Not everything the AI says is a fact</h3><p>Imagine the repository says:</p><blockquote><em>“The networking layer owns connection state.”</em></blockquote><p>That’s a <strong>declared</strong> fact.</p><p>A developer explicitly said it.</p><p>Then ACC looks at the code and discovers:</p><blockquote><em>router.rs imports </em><em>connection.rs.</em></blockquote><p>That’s a <strong>discovered</strong> fact.</p><p>We can observe it.</p><p>Then maybe an agent says:</p><blockquote><em>“I think module X probably depends on connection state.”</em></blockquote><p>That’s an <strong>inferred</strong> fact.</p><p>Maybe it’s right.</p><p>Maybe it’s wrong.</p><p>And I don’t want the third one silently becoming part of the first one.</p><p>So ACC keeps the provenance.</p><p><strong>Declared.</strong></p><p><strong>Discovered.</strong></p><p><strong>Inferred.</strong></p><p>That distinction became surprisingly important.</p><p>Because AI is very good at making guesses sound like facts.</p><p>We’ve all experienced that one. 😂</p><h3>Context is a budget</h3><p>Another thing that kept coming up in the research was the idea that <strong>context is a budget</strong>.</p><p>And this one really clicked with me.</p><p>Because I’ve watched agents get overwhelmed by too much information.</p><p>Sometimes people think:</p><blockquote><em>“The model has a huge context window now, so just give it everything.”</em></blockquote><p>But more context isn’t necessarily better context.</p><p>If I’m asking an agent to fix a bug in one part of a repository, I don’t need to give it every unrelated file in the project.</p><p>I need the right information.</p><p>That’s what ACC’s progressive context is about.</p><p>Instead of:</p><blockquote><em>“Here’s the entire repository. Good luck.”</em></blockquote><p>the idea is:</p><blockquote><em>“You’re working here. Here’s what you need to know.”</em></blockquote><p>The hierarchy.</p><p>The relevant contracts.</p><p>The dependencies.</p><p>The constraints.</p><p>The context that actually matters.</p><p>That’s a much more useful starting point.</p><h3>Skills vs MCP</h3><p>And then there is the other conversation happening right now.</p><p><strong>Skills vs MCP.</strong></p><p>This one is interesting because I don’t really want to pick a side or I have too. I don’t think it matters.</p><p>There are people arguing that Markdown-based skills are replacing the need for MCP.</p><p>And there are people arguing that protocols are what we actually need when things become serious.</p><p>I think both sides have a point.</p><p>If I want to tell an agent:</p><blockquote><em>Run these commands.</em></blockquote><blockquote><em>Don’t touch this directory.</em></blockquote><blockquote><em>Follow this workflow.</em></blockquote><blockquote><em>Use this convention.</em></blockquote><p>Markdown is fantastic.</p><p>But if I need authentication, permissions, external services, structured tools, observability, or access to something outside the repository?</p><p>Then a protocol makes a lot of sense.</p><p>So my position with ACC is pretty simple:</p><blockquote><strong>I don’t think you have to choose.</strong></blockquote><p>Markdown can be the interface for context.</p><p>Protocols can be the bridge to capabilities.</p><p>And the repository can sit underneath both.</p><p>ACC doesn’t replace MCP.</p><p>It doesn’t replace Skills.</p><p>It tries to make the repository a better foundation for both.</p><h3>Okay, but does this actually work?</h3><p>This was the point where I didn’t want to just believe my own idea.</p><p>So I built another project.</p><p><strong>ABA — ACC Battle Arena.</strong></p><p>The idea is pretty simple.</p><p>Take the same task.</p><p>Take the same repository.</p><p>Use the same model.</p><p>Run the task with ACC context.</p><p>Then run it without ACC context.</p><p>And compare what happens.</p><p>Not a theoretical benchmark.</p><p>Actual sandboxes.</p><p>Actual agents.</p><p>Actual plan/act phases.</p><p>Actual verification.</p><p>I wanted to watch what the agents actually did.</p><p>Because sometimes the numbers don’t tell you the whole story.</p><h3>And this is where I started seeing something I knew, but It’s much clearer now</h3><p>The model matters.</p><p>Obviously.</p><p>A better model is usually going to perform better.</p><p>But after watching a bunch of these battles, and working with a lot of providers and models during the last year, something else became pretty obvious:</p><blockquote><strong>The context mattered a lot more than I expected. And actually can be as important as the model itself sometimes.</strong></blockquote><p>The same model.</p><p>The same repository.</p><p>The same task.</p><p>And yet the behavior could be noticeably different.</p><p>Without context, the agent would spend a lot of time trying to understand what it was looking at, where it should work, what matters for the changes, how it’s the project structured, etc.</p><p>It would explore.</p><p>Guess.</p><p>Search.</p><p>Sometimes invent an architecture.</p><p>Sometimes they’d decide that the correct solution was to rewrite something that didn’t need rewriting — or worse, just completely remove the code 😂</p><p>With context, it had a map.</p><p>It knew where to look.</p><p>It understood the boundaries.</p><p>It had some idea of the architecture before touching anything.</p><p>And my favorite part:</p><blockquote><strong>it was less likely to invent things.</strong></blockquote><p>That’s actually what I care about most.</p><p>I don’t need the AI to be more confident in doing mistakes.</p><p>I need it to be <strong>less confidently wrong</strong> — and more context-aware, so it has a better chance of getting it right.</p><h3>Then came the obvious question</h3><p>If this works…</p><p>why isn’t everyone already doing it?</p><p>Well…</p><p>They kind of are.</p><p>That’s probably the most interesting thing about this whole space.</p><p>Nobody sat down and collectively decided:</p><blockquote><em>“Okay everyone, we’re going to use Markdown for AI context now.”</em></blockquote><p>It just started happening.</p><p>AGENTS.md.</p><p>CLAUDE.md.</p><p>SKILL.md.</p><p>copilot-instructions.md.</p><p>Research workflows.</p><p>Scratchpads.</p><p>Planning documents.</p><p>Spec-driven development.</p><p>Different communities.</p><p>Different tools.</p><p>Different approaches.</p><p>Same direction.</p><p>And I think that’s worth paying attention to.</p><p>Maybe this isn’t just another AI trend.</p><p>Maybe we’re discovering a new layer of software development.</p><h3>The repository becomes part of the agent</h3><p>This is probably the bigger idea behind ACC.</p><p>For a long time, the source code was the source of truth.</p><p>Documentation explained it.</p><p>Tests verified it.</p><p>Configuration controlled it.</p><p>Now we have another participant:</p><p><strong>the AI agent.</strong></p><p>And the AI needs context.</p><p>It needs to know not only:</p><blockquote><em>“What code exists?”</em></blockquote><p>but:</p><blockquote><em>“Why does it exist?”</em></blockquote><blockquote><em>“What am I allowed to change?”</em></blockquote><blockquote><em>“What should I preserve?”</em></blockquote><blockquote><em>“How does this part fit into the rest?”</em></blockquote><p>That’s knowledge.</p><p>And I think that knowledge should live as close as possible to the thing it describes.</p><p>Not in my chat history.</p><p>Not inside one particular AI vendor.</p><p>Not inside a proprietary memory system.</p><p><strong>In the repository.</strong></p><h3>And ACC is not the point</h3><p>This is probably the most important thing I want to say.</p><blockquote>I don’t actually care if everyone uses ACC. I’d be fucking thrilled if everyone did 😂</blockquote><p>Seriously.</p><p>If tomorrow somebody builds something much better using a completely different approach, <strong>I’d be just as happy</strong>.</p><p>That’s really what I’m trying to figure out with ACC.</p><p>I’m not interested in building another tool that tells everyone, <em>“this is the right way to work with AI.”</em></p><p>I just kept running into the same problem: every time the agent changed, the conversation ended, or the context got reset, we lost all the understanding we’d built up.</p><p>And I kept thinking:</p><blockquote><strong>Why does that knowledge belong to the agent instead of the project?</strong></blockquote><p>That’s the part I’m interested in.</p><p>ACC is just what I ended up building because I wanted to see what would happen if we treated the repository as the place where that context lives.</p><p>And because it’s open source, other people can tell me where I’m wrong.</p><p>Which is probably going to happen. 😂 <strong>That’s how open source grows — people take an idea, challenge it, break it, improve it, and build something better on top of it.</strong></p><h3>The fun part of open source</h3><p>That’s why I’m putting this out there now.</p><p>Not because I think ACC is finished.</p><p>It isn’t.</p><p>There are things I’m still figuring out.</p><p>There are design decisions I’m not completely sure about.</p><p>There are probably things that looked like a great idea at 2 AM and won’t survive contact with actual developers.</p><p>That’s normal.</p><p>The whole point is to put it in front of people.</p><p>Try it on your repository.</p><p>Try it with your favorite coding agent.</p><p>Try it on a huge monorepo.</p><p>Try it on a tiny project.</p><p>Break it.</p><p>Tell me I’m wrong.</p><p>Open an issue.</p><p>Send a PR.</p><p>Whatever.</p><p>That’s how we figure these things out.</p><h3>Agentic-Driven Development</h3><p>And maybe this is where we’re heading: <strong>Agentic-Driven Development.</strong></p><p>Not humans using AI to write code.</p><p>But humans defining intent while agents explore, plan, build, verify, and iterate.</p><p>If that’s the direction software development is going, then agents need more than a model and a context window.</p><p>They need a <strong>persistent understanding of the project</strong>.</p><p>That’s why I think ACC makes sense.</p><p>The agent can change.</p><p>The model can change.</p><p>The conversation can disappear.</p><p><strong>The repository remains.</strong></p><p>ACC is an attempt to make that repository a better environment for agents to work in — giving them the context, boundaries, decisions, and accumulated knowledge they need to keep moving without starting from zero every time.</p><p>Maybe the future of agentic development isn’t about building one perfect agent.</p><p>Maybe it’s about giving many agents a project they can actually understand.</p><h3>So… Markdown is all we need?</h3><p>Maybe.</p><p>Maybe not.</p><p>The title is obviously a little provocative.</p><p>We still need code.</p><p>We still need APIs.</p><p>We still need databases.</p><p>We still need protocols.</p><p>We still need tools.</p><p>But I think Markdown has become something much more interesting than a convenient way to format README files.</p><p>It’s a common language that humans and machines can both work with.</p><p>And that matters.</p><p>Because the future of software development is increasingly going to involve more than just humans writing code.</p><p>We’re going to have humans explaining intent.</p><p>Agents interpreting that intent.</p><p>Agents changing code.</p><p>Other agents reviewing it.</p><p>Humans reviewing the result.</p><p>And all of them need some shared understanding of the project.</p><p>Maybe Markdown is part of that shared layer.</p><p>Maybe the repository itself becomes the memory.</p><p>Maybe the agent doesn’t need to remember everything.</p><p>Maybe the project just needs to remember the right things.</p><h3>That’s why I built ACC</h3><p>I didn’t start this project because I thought Markdown was going to change software development.</p><p>I started it because I was tired of explaining the same damn things to AI agents.</p><p>Then I started reading.</p><p>I found a lot of people thinking about the same problem from completely different directions. And the more I read, the more I thought:</p><blockquote><strong>Wait… we’re all pointing at something here.</strong></blockquote><p>So I decided to stop thinking about it and actually build something.</p><p><strong>ACC was my attempt to see what happens when the repository becomes part of the conversation.</strong></p><ul><li>The agent changes.</li><li>The model changes.</li><li>The conversation ends.</li></ul><p>But the project keeps going.</p><p>And the context can go with it.</p><p>That’s really what I wanted to build.</p><h3>If you want to play with it</h3><p>The main project is here:</p><p><strong>ACC — Agent Code Context</strong><br><a href="https://github.com/EnzoVezzaro/agents-code-context">https://github.com/EnzoVezzaro/agents-code-context</a></p><p>And if you want to see the benchmarking side:</p><p><strong>ABA — ACC Battle Arena</strong><br><a href="https://github.com/EnzoVezzaro/aba-arena">https://github.com/EnzoVezzaro/aba-arena</a></p><p>The complete specification is in the repositories. The docs explain the architecture, graph model, CLI, diagnostics, context system, and everything else.</p><p>This article is not really about explaining all of that.</p><p>It’s about <strong>why I ended up building it in the first place.</strong></p><p>So if you’re working with AI coding agents, give it a shot.</p><p>And if you think I’m doing something completely wrong…</p><p>please tell me. 😂</p><p>Star it.</p><p>Break it.</p><p>Open an issue.</p><p>Send a PR.</p><p>Or build something better.</p><p>And if you want to support my open-source work, you can sponsor me here:</p><p><a href="https://github.com/sponsors/EnzoVezzaro">https://github.com/sponsors/EnzoVezzaro</a></p><p>I’m genuinely curious where this goes.</p><p>Because maybe we’re going to discover that the answer is something completely different, or maybe not.</p><p>But right now, after spending all this time working with AI agents, I keep coming back to the same idea:</p><blockquote><strong>The agent doesn’t need to remember everything.</strong></blockquote><blockquote><strong>The repository needs to remember the right things.</strong></blockquote><p>And maybe that’s enough.</p><p>The map is already in the repo.</p><p>We just need to make it easier for the agent to read it.</p><p><em>Thanks to everyone in the open-source community who’s been experimenting with this stuff in public — the people working on </em><em>AGENTS.md, Skills, MCP, coding agents, spec-driven development, research workflows, and all the weird little experiments that keep pushing this space forward.</em></p><p><em>I got inspired by a lot of ideas from all of you. That’s kind of the point of open source.</em></p><p><strong>Gracias por los aportes y por seguir empujando, juntos, hacia el futuro. 🙌</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f9f7283b758" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe Coding Adventures: Day 10 — Dominican Congress MCP]]></title>
            <link>https://medium.com/@enzovezzaro/vibe-coding-adventures-day-10-dominican-congress-mcp-dae1074ab4ce?source=rss-a225e16db862------2</link>
            <guid isPermaLink="false">https://medium.com/p/dae1074ab4ce</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[mcp-client]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Enzo Junior Vezzaro]]></dc:creator>
            <pubDate>Wed, 09 Apr 2025 14:11:23 GMT</pubDate>
            <atom:updated>2025-04-09T14:49:50.882Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vibe Coding Adventures: Day 10 — Dominican Congress MCP</h3><p>It’s day 10 already! 10 days of Vibe Coding, 10 days where I learned a bunch about this AI systems, and how they can be integrated into our workflow.</p><p>Today we’ll take a look at MCP. A buzz word that it’s been taking the AI world by storm. But what is it?</p><h3>What’s an MCP (Modern Context Protocol)?</h3><p>As it’s name suggest, it’s a communication protocol. In words of the team which created it:</p><blockquote>It’s a new standard for connecting AI assistants to the systems where data lives, including content repositories, business tools, and development environments. Its aim is to help frontier models produce better, more relevant responses.</blockquote><p>Basically, it’s a place where your information, custom tools, and instructions lives. Think of it as a toolset for your AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gi34oIGnb06QQx2KJEX0lQ.png" /><figcaption>image from <a href="https://www.claudemcp.com/blog/mcp-vs-api">https://www.claudemcp.com/blog/mcp-vs-api</a></figcaption></figure><p>In this <a href="https://www.claudemcp.com/blog/mcp-vs-api">post</a> (I really recommend to read) is well explained, a “MCP is a standardized protocol for connecting AI agents to various external tools and data sources. Imagine it as a USB-C interface — but for AI applications.”</p><p>That’s an awesome way to put it! Just imagine your AI having a tool to extend it’s USB ports, in order to be able to use them for different outputs: headphones, charger, speakers, mouse, keyboard, etc. An MCP is basically a way to allow AI agents to use different tools, have the most updated data, and interact more efficiently with the client.</p><h3>But why do we need an MCP for that? What are the benefits?</h3><p>Using a MCP in theory has many benefits, let’s explore some of them:</p><p><strong>🧠 Context-Awareness</strong></p><ul><li>An MCP would allow systems to <strong>understand and adapt to real-time context</strong>, such as user behavior, location, device type, preferences, and environmental data.</li><li>Makes apps <strong>smarter</strong>, more <strong>responsive</strong>, and better at personalization.</li></ul><p><strong>🔁 Efficient State Management</strong></p><ul><li>By maintaining contextual state across sessions or interactions, MCP could reduce redundant data requests and <strong>enable seamless user experiences</strong> (e.g., continuing a task across devices).</li></ul><p><strong>🔐 Granular Access Control &amp; Security</strong></p><ul><li>Context-based protocols can include <strong>dynamic access control</strong> based on context (e.g., only allow login from trusted locations or times).</li><li>Helps <strong>enhance security without sacrificing usability</strong>.</li></ul><p><strong>🔄 Interoperability in Distributed Systems</strong></p><ul><li>A well-designed MCP would standardize how services <strong>share contextual data</strong>, improving coordination between microservices, edge devices, IoT systems, etc.</li></ul><p><strong>⚡ Improved Performance</strong></p><ul><li>Reduces unnecessary API calls and improves <strong>caching and prefetching strategies</strong> based on contextual predictions.</li></ul><p><strong>🛠️ Developer Productivity</strong></p><ul><li>Offers a <strong>clear structure</strong> for managing context, reducing the boilerplate or inconsistencies developers face when passing state between components, services, or layers.</li></ul><p><strong>🧩 Support for AI and ML</strong></p><ul><li>Context-aware protocols are a <strong>natural fit for AI-driven systems</strong>, feeding real-time data into models to adapt behavior dynamically.</li></ul><p>These are the promises of MCP, in truth we’re still so far from that reality.</p><p>To know what’s the truth I decided to build one from scratch, just to see the reality with my own eyes. For personal and limited experience, I’ve seen both the potential and the pitfalls of it.</p><p>While it’s a powerful tool, implementing it quickly becomes overwhelming. The added complexity often feels disproportionate to the actual value delivered, and debugging issues tied to shifting states is a nightmare.</p><p>It’s a great idea in theory, but in practice, it’s easy to over-engineer and hard to get right without introducing performance or privacy trade-offs.</p><p>These are some of the criticisms or challenges that I found myself (some of them, not all):</p><p>🔍 Complexity and Overhead</p><ul><li><strong>Managing context across systems</strong> can become extremely complex.</li><li>Developers might struggle with <strong>state bloat</strong>, managing outdated or irrelevant context, or determining what context is truly necessary.</li><li>It introduces a <strong>higher cognitive load</strong> and more moving parts in an already complex stack.</li></ul><p>🧩 Lack of Standardization</p><ul><li>Without a widely accepted spec or protocol, MCP-like solutions can suffer from <strong>inconsistency</strong> across implementations (outside of OpenAI and Claude).</li><li>Teams may build their own version of “context handling,” leading to <strong>fragmentation</strong> and <strong>compatibility issues</strong>.</li></ul><p>🔐 Privacy and Security Risks</p><ul><li>Context-aware systems often collect <strong>sensitive user data</strong> (location, behavior, identity, etc.).</li><li>This opens up <strong>huge privacy concerns</strong>, especially if the context is improperly stored, shared, or breached.</li><li>Users may not even be aware of the extent of data being tracked and used.</li></ul><p>⚖️ Ethical Concerns</p><ul><li>Context can be used to <strong>manipulate user behavior</strong> (think algorithmic targeting or dark patterns — eventhough they’re being used right now).</li><li>Raises concerns about <strong>surveillance</strong>, <strong>informed consent</strong>, and <strong>autonomy</strong> — especially when AI is involved.</li></ul><p>⏱️ Latency and Performance Trade-Offs</p><ul><li>Continuously evaluating and reacting to context can introduce <strong>latency</strong> or <strong>increase resource consumption</strong>, especially on edge devices or low-power systems.</li></ul><p>🔧 Difficult Debugging and Testing</p><ul><li>Systems that adapt based on context are often <strong>non-deterministic</strong> — making them <strong>hard to test</strong> and debug.</li><li>Bugs may only occur in specific contextual states, which are hard to reproduce (this is true with or without MCP Servers).</li></ul><p>💸 Implementation Cost vs. Value</p><ul><li>For many products, implementing a full context-aware protocol <strong>might be overkill</strong>.</li><li>Teams may end up <strong>over-engineering</strong> for features that don’t significantly improve the user experience.</li></ul><p>What’s more, most of what MCPs try to accomplish can already be done — often more simply and reliably — using well-designed REST APIs. In the end, it sometimes feels like solving problems that don’t really exist, with added cost and maintenance.</p><h3>So what’s the deal? Do we use it or not?</h3><p>Well, it all depends on your risk tolerance and your use cases. I always suggest to get familiar with these tools, so try it out.</p><p>I feel like it’s really immature as a standard; It‘s really a great idea, and I have no doubt it will be the standard of tomorrow. But for now, I think it’s really risky to invest time and effort on such a fast growing, fast moving piece of technology. I think MCP will take significantly longer to be adopted in software engineering than AI did.</p><h3>Now, let’s get back to our series. It’s time to start building!</h3><p>Since experience says more than words, let’s build one from scratch to see what we can accomplish with such tool.</p><p>Antropic has an <a href="https://modelcontextprotocol.io/introduction">amazing documentation</a> which explains in details how to create and implement a MCP. You can follow their guidelines, and even gave you the instruction to <a href="https://modelcontextprotocol.io/tutorials/building-mcp-with-llms">build it using Claude</a>. But for this exercise I decided to implemented myself, following the documentation to learn how this things work.</p><h3>What’s the idea?</h3><p>The idea is to build an MCP that provides the latest information from the Dominican Congress. We’ll be implementing an MCP interface that can fetch, crawl, and parse data directly from the Dominican government’s sources, making that information accessible to the AI in real time.</p><p>Here’s a quick summary of our MCP:</p><pre>This MCP server provides access to information about the Dominican Congress, including legislative agendas, legislator activity, and new bills.<br><br>## Tools<br><br>*   **fetch-legislative-agenda:** Fetches the legislative agenda for a given chamber.<br>    *   Parameters:<br>        *   `chamber` (string, required): The chamber to fetch the agenda for. Must be either `&quot;senado&quot;` or `&quot;diputados&quot;`.<br>*   **get-legislator-activity:** Gets the activity for a given legislator.<br>    *   Parameters:<br>        *   `name` (string, required): The name of the legislator.<br>*   **summarize-today:** Summarizes today&#39;s legislative activity.<br>    *   Parameters: None<br>*   **new bills:** Fetches new bills for a given chamber.<br>    *   Parameters:<br>        *   `chamber` (string, required): The chamber to fetch the new bills for. Must be either `&quot;senado&quot;` or `&quot;diputados&quot;`.<br>*   **parse-pdf:** Parses a PDF file from a given URL.<br>    *   Parameters:<br>        *   `pdfUrl` (string, required): The URL of the PDF file.<br>*   **datos-abiertos:** Queries the datos.gob.do API.<br>    *   Parameters:<br>        *   `q` (string, optional): The search query.<br>        *   `organization` (string, optional): The organization to filter by.<br>        *   `tags` (string, optional): The tags to filter by.<br>        *   `groups` (string, optional): The groups to filter by.<br>        *   `skip` (string, optional): The number of results to skip.<br>*   **parse-csv:** Parses a CSV file from a given URL.<br>    *   Parameters:<br>        *   `csvUrl` (string, required): The URL of the CSV file.<br>*   **parse-xlsx:** Parses an XLSX file from a given URL.<br>    *   Parameters:<br>        *   `xlsxUrl` (string, required): The URL of the XLSX file.<br><br>## Resource Templates<br><br>*   **bulletin://{date}**: Daily bulletin for a given date.</pre><p>As you can see it’s a small MCP server which fetch and servers the information from the Dominican Congress’ Website, we also gave to the MCP some tooling like: parse-xlsx, parse-csv, parse-pdf. Just in case the AI needs them.</p><p>Just for the sake of learning, let’s see the workflow of our MCP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FC7KVWQIFBXVbBbnaiaTg.png" /><figcaption>Workflow MCP Server</figcaption></figure><p>Very simple indeed. But that doesn’t mean it’s easy to build either. Let’s review and comment our code:</p><pre>// Dominican Congress Watcher - MCP Server<br>// Uses TypeScript and MCP SDK to provide live updates from SenadoRD and Cámara de Diputados<br><br>import { McpServer, ResourceTemplate } from &quot;@modelcontextprotocol/sdk/server/mcp.js&quot;;<br>import { StdioServerTransport } from &quot;@modelcontextprotocol/sdk/server/stdio.js&quot;;<br>import { z } from &quot;zod&quot;;<br>import puppeteer from &quot;puppeteer&quot;;<br>import axios from &quot;axios&quot;;<br>import pdf from &#39;pdf-parse/lib/pdf-parse.js&#39;;<br>import { parse as csvParse } from &#39;csv-parse&#39;;<br>import * as xlsx from &#39;xlsx&#39;;<br><br>// Create the MCP server<br>const server = new McpServer({<br>  name: &quot;Dominican Congress MCP&quot;,<br>  version: &quot;1.0.0&quot;<br>});<br><br>// Tool: Fetch Legislative Agenda<br>server.tool(&quot;fetch-legislative-agenda&quot;, {<br>  chamber: z.enum([&quot;senado&quot;, &quot;diputados&quot;]),<br>}, async ({ chamber }) =&gt; {<br>  const agenda = await crawlAgenda(chamber);<br>  return {<br>    content: [{ type: &quot;text&quot;, text: agenda }]<br>  };<br>});<br><br>// Tool: Get Legislator Activity<br>server.tool(&quot;get-legislator-activity&quot;, {<br>  name: z.string(),<br>}, async ({ name }) =&gt; {<br>  const summary = await getLegislatorHistory(name);<br>  return {<br>    content: [{ type: &quot;text&quot;, text: summary }]<br>  };<br>});<br><br>// Tool: Summarize Today&#39;s Legislative Activity<br>server.tool(&quot;summarize-today&quot;, {}, async () =&gt; {<br>  const summary = await summarizeTodayCongress();<br>  return {<br>    content: [{ type: &quot;text&quot;, text: summary }]<br>  };<br>});<br><br>// Tool: New Bills<br>server.tool(&quot;new bills&quot;, {<br>  chamber: z.enum([&quot;senado&quot;, &quot;diputados&quot;]),<br>}, async ({ chamber }) =&gt; {<br>  const updates = await checkNewBills(chamber);<br>  return {<br>    content: [{ type: &quot;text&quot;, text: updates }]<br>  };<br>});<br><br>// Tool: Parse PDF<br>server.tool(&quot;parse-pdf&quot;, {<br>  pdfUrl: z.string().url()<br>}, async ({ pdfUrl }) =&gt; {<br>  try {<br>    const response = await axios.get(pdfUrl, { responseType: &#39;arraybuffer&#39; });<br>    const data = await pdf(response.data);<br>    return {<br>      content: [{ type: &quot;text&quot;, text: data.text }]<br>    };<br>  } catch (error: any) {<br>    console.error(`Error processing PDF ${pdfUrl}: ${error.message}`);<br>    return {<br>      content: [{ type: &quot;text&quot;, text: `Error processing PDF: ${error.message}` }],<br>      isError: true<br>    };<br>  }<br>});<br><br>// Tool: Datos Abiertos<br>server.tool(&quot;datos-abiertos&quot;, {<br>  q: z.string().optional(),<br>  organization: z.string().optional(),<br>  tags: z.string().optional(),<br>  groups: z.string().optional(),<br>  skip: z.string().optional(),<br>}, async ({ q, organization, tags, groups, skip }) =&gt; {<br>  const url = `https://datos.gob.do/api/datasets?q=${q || &#39;&#39;}&amp;organization=${organization || &#39;&#39;}&amp;tags=${tags || &#39;&#39;}&amp;groups=${groups || &#39;&#39;}&amp;skip=${skip || &#39;&#39;}`;<br>  try {<br>    const response = await axios.get(url);<br>    const data = response.data;<br>    return {<br>      content: [{ type: &quot;text&quot;, text: JSON.stringify(data, null, 2) }]<br>    };<br>  } catch (error: any) {<br>    console.error(`Error obteniendo datos abiertos: ${error.message}`);<br>    return {<br>      content: [{ type: &quot;text&quot;, text: `Error obteniendo datos abiertos: ${error.message}` }],<br>      isError: true<br>    };<br>  }<br>});<br><br>// Tool: Parse CSV<br>server.tool(&quot;parse-csv&quot;, {<br>  csvUrl: z.string().url()<br>}, async ({ csvUrl }) =&gt; {<br>  try {<br>    const response = await axios.get(csvUrl, { responseType: &#39;stream&#39; });<br>    const records: any[] = [];<br>    const parser = response.data.pipe(csvParse({<br>      delimiter: &#39;,&#39;,<br>      columns: true,<br>      skip_empty_lines: true<br>    }));<br>    for await (const record of parser) {<br>      records.push(record);<br>    }<br>    return {<br>      content: [{ type: &quot;text&quot;, text: JSON.stringify(records, null, 2) }]<br>    };<br>  } catch (error: any) {<br>    console.error(`Error procesando CSV ${csvUrl}: ${error.message}`);<br>    return {<br>      content: [{ type: &quot;text&quot;, text: `Error procesando CSV: ${error.message}` }],<br>      isError: true<br>    };<br>  }<br>});<br><br>// Tool: Parse XLSX<br>server.tool(&quot;parse-xlsx&quot;, {<br>  xlsxUrl: z.string().url()<br>}, async ({ xlsxUrl }) =&gt; {<br>  try {<br>    const response = await axios.get(xlsxUrl, { responseType: &#39;arraybuffer&#39; });<br>    const workbook = xlsx.read(response.data, { type: &#39;buffer&#39; });<br>    const sheetName = workbook.SheetNames[0];<br>    const worksheet = workbook.Sheets[sheetName];<br>    const jsonData = xlsx.utils.sheet_to_json(worksheet);<br>    return {<br>      content: [{ type: &quot;text&quot;, text: JSON.stringify(jsonData, null, 2) }]<br>    };<br>  } catch (error: any) {<br>    console.error(`Error procesando XLSX ${xlsxUrl}: ${error.message}`);<br>    return {<br>      content: [{ type: &quot;text&quot;, text: `Error procesando XLSX: ${error.message}` }],<br>      isError: true<br>    };<br>  }<br>});<br><br>// Resource: Daily Bulletin<br>server.resource(<br>  &quot;daily-bulletin&quot;,<br>  new ResourceTemplate(&quot;bulletin://{date}&quot;, { list: undefined }),<br>  async (uri, { date }) =&gt; {<br>    const bulletin = await getCongressBulletin(date as string);<br>    return {<br>      contents: [{<br>        uri: uri.href,<br>        text: bulletin,<br>      }],<br>    };<br>  }<br>);<br><br>// --- Implementation Helpers ---<br><br>async function crawlAgenda(chamber: string): Promise&lt;string&gt; {<br>  const baseUrl = chamber === &quot;senate&quot;<br>    ? &quot;https://www.senadord.gob.do/orden-del-dia/&quot;<br>    : &quot;https://camaradediputados.gob.do/ordenes-del-dia-del-pleno/&quot;;<br><br>  const browser = await puppeteer.launch({ headless: true });<br>  const page = await browser.newPage();<br>  await page.goto(baseUrl, { waitUntil: &#39;networkidle0&#39; }); // Wait for network activity to cease<br><br>  // Get main page text<br>  await page.evaluate(() =&gt; document.body.innerHTML);<br><br>  // Find PDF links<br>  const pdfLinks = await page.$$eval(&#39;a.wpfd_downloadlink&#39;, (links, pageUrl) =&gt;<br>    links.map(link =&gt; ({<br>      href: new URL(link.getAttribute(&#39;href&#39;) || &#39;&#39;, pageUrl).href, // Resolve relative URLs<br>      name: link.textContent?.trim() || link.getAttribute(&#39;href&#39;)?.split(&#39;/&#39;).pop() || &#39;unknown.pdf&#39; // Get name from text or filename<br>    })), baseUrl); // Pass baseUrl to resolve relative URLs correctly<br><br>  let mainText = await page.evaluate(() =&gt; document.body.innerText);<br><br>  await browser.close();<br><br>  const combinedText = `Resume la agenda legislativa del siguiente texto extraído del sitio web del congreso (${chamber}).  The following PDFs were found, please parse them using the parse-pdf tool:\n${pdfLinks.map(link =&gt; link.href).join(&#39;\n&#39;)}\n\n${mainText}`;<br>  return combinedText;<br>}<br><br><br>async function getLegislatorHistory(name: string): Promise&lt;string&gt; {<br>  const url = `https://www.camaradediputados.gob.do/\nhttps://www.senadord.gob.do/`;<br>  const browser = await puppeteer.launch({ headless: true });<br>  const page = await browser.newPage();<br>  await page.goto(url);<br>  const text = await page.evaluate(() =&gt; document.body.innerText);<br>  await browser.close();<br><br>  return `Busca toda la información sobre la actividad reciente del legislador o legisladora llamado/a ${name} y resumenla de forma clara y cronológica:\n\n${text}`;<br>}<br><br>async function summarizeTodayCongress(): Promise&lt;string&gt; {<br>  const senate = await crawlAgenda(&quot;senate&quot;);<br>  const deputies = await crawlAgenda(&quot;deputies&quot;);<br><br>  const fullText = `Agenda Senado:\n${senate}\n\nAgenda Diputados:\n${deputies}`;<br>  return `Resume el trabajo legislativo del día a partir del siguiente texto combinado del Senado y Cámara de Diputados:\n\n${fullText}`;<br>}<br><br>async function checkNewBills(chamber: string): Promise&lt;string&gt; {<br>  const baseUrl = chamber === &quot;senate&quot;<br>    ? &quot;http://www.senado.gov.do/wfilemaster/lista_expedientes.aspx?coleccion=53&quot;<br>    : &quot;https://camaradediputados.gob.do/&quot;;<br><br>  try {<br>    const browser = await puppeteer.launch({ headless: true });<br>    const page = await browser.newPage();<br><br>    await page.setExtraHTTPHeaders({<br>      &#39;accept&#39;: &#39;text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8&#39;,<br>      &#39;accept-encoding&#39;: &#39;gzip, deflate&#39;,<br>      &#39;accept-language&#39;: &#39;en-GB,en;q=0.8&#39;,<br>      &#39;cache-control&#39;: &#39;no-cache&#39;,<br>      &#39;connection&#39;: &#39;keep-alive&#39;,<br>      &#39;host&#39;: &#39;www.senado.gov.do&#39;,<br>      &#39;pragma&#39;: &#39;no-cache&#39;,<br>      &#39;sec-gpc&#39;: &#39;1&#39;,<br>      &#39;upgrade-insecure-requests&#39;: &#39;1&#39;,<br>      &#39;User-Agent&#39;: &#39;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36&#39;<br>    });<br><br>    await page.goto(baseUrl);<br>    const text = await page.evaluate(() =&gt; document.body.innerText);<br>    await browser.close();<br><br>    return `Busca y resume cualquier propuesta de ley nueva publicada recientemente en el siguiente texto:\n\n${text}`;<br>  } catch (error: any) {<br>    console.error(`Error obteniendo nuevas leyes: ${error.message}`);<br>    return `Error obteniendo nuevas leyes: ${error.message}`;<br>  }<br>}<br><br>async function getCongressBulletin(date: string): Promise&lt;string&gt; {<br>  const url = `https://www.senadord.gob.do/orden-del-dia/`; // Placeholder<br>  const browser = await puppeteer.launch({ headless: true });<br>  const page = await browser.newPage();<br>  await page.goto(url);<br>  const text = await page.evaluate(() =&gt; document.body.innerText);<br>  await browser.close();<br><br>  return `Extrae y resume el boletín legislativo del día ${date} del siguiente contenido web:\n\n${text}`;<br>}<br><br>const PORT = process.env.PORT || 8089;<br>const transport = new StdioServerTransport();<br>server.connect(transport).then(() =&gt; {<br>  console.log(`Dominican Congress MCP server running on port ${PORT}`);<br>});<br><br>export default server;</pre><p>As you can see we start out by initializing our server:</p><pre>const server = new McpServer({<br>  name: &quot;Dominican Congress MCP&quot;,<br>  version: &quot;1.0.0&quot;<br>});</pre><p>To then give our server the tools and resources it needs:</p><pre>server.resource(<br>  &quot;daily-bulletin&quot;,<br>  new ResourceTemplate(&quot;bulletin://{date}&quot;, { list: undefined }),<br>  async (uri, { date }) =&gt; {<br>    const bulletin = await getCongressBulletin(date as string);<br>    return {<br>      contents: [{<br>        uri: uri.href,<br>        text: bulletin,<br>      }],<br>    };<br>  }<br>);<br><br>// We probably can move this into the resources, but for this example let&#39;s keep it as tool<br>server.tool(&quot;fetch-legislative-agenda&quot;, {<br>  chamber: z.enum([&quot;senado&quot;, &quot;diputados&quot;]),<br>}, async ({ chamber }) =&gt; {<br>  const agenda = await crawlAgenda(chamber);<br>  return {<br>    content: [{ type: &quot;text&quot;, text: agenda }]<br>  };<br>});</pre><p>The code is very simple; you tell the AI which tools or resources are available, so it can decided what to use and when (unless you specify).</p><p>And last, you need to expose the server. In this case we’re using Stdio for simplicity, but we can also expose it with Server-Sent Events (SSE) (see <a href="https://modelcontextprotocol.io/docs/concepts/transports">documentation</a>).</p><pre>const PORT = process.env.PORT || 8089;<br>const transport = new StdioServerTransport();<br>server.connect(transport).then(() =&gt; {<br>  console.log(`Dominican Congress MCP server running on port ${PORT}`);<br>});</pre><p>Once we have all in place, we can then build the server. In our case a simple ´npm run build´ is enough.</p><pre>&gt; dominican-legal-mcp@1.0.0 build<br><br>Author: Enzo Vezzaro<br>GitHub: https://github.com/EnzoVezzaro/dominicans-mcp<br>MCP Configuration (add this to your settings):<br>{<br>  &quot;dominican-congress&quot;: {<br>    &quot;command&quot;: &quot;node&quot;,<br>    &quot;args&quot;: [&quot;/Users/mac/Desktop/Github/mcp-dominican-layer/build/index.js&quot;],<br>    &quot;env&quot;: {}<br>  }<br>}</pre><p>For practicality, I’m printing the server’s configurations on the console for the next step.</p><h3>What do we do now with our server?</h3><p>Now that we have our server built and available in local, we can add it to our prefered MCP client.</p><p>Antropic has a very good selection of <a href="https://modelcontextprotocol.io/clients">MCP clients</a> you can choose. In my case, I’ll be using Cline for this.</p><p>The steps to enable MCP on your client are the following:</p><p>1️⃣ Open your server’s configuration in your client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*7dxhUlEm1lIgJBZo59xYnw.png" /><figcaption>Cline MCP Tab</figcaption></figure><p>2️⃣ Click on “Configure MCP Servers”. This will open a json file with all your configured servers. It’ll be empty if you haven’t done it before.</p><pre>{<br>  &quot;mcpServers&quot;: {}<br>}</pre><p>3️⃣ Add your server’s configurations.</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;dominican-congress&quot;: {<br>      &quot;command&quot;: &quot;node&quot;,<br>      &quot;args&quot;: [&quot;/Users/mac/Desktop/Github/mcp-dominican-layer/build/index.js&quot;],<br>      &quot;env&quot;: {}<br>    }<br>  }<br>}</pre><p>4️⃣ After saving the file, you’ll see your MCP server on the panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*HxXXYMM-LhRUuJ4JrXAHhg.png" /></figure><p>Now it’s time to finally use it.</p><h3>Let’s start asking! 🤖</h3><p>Now that we have our MCP server configured in Cline, we can start interacting with our AI.</p><p>User Initial Prompt: “give me the agenda of the senate”</p><p>AI: “The user wants the agenda of the senate. I have access to the dominican-congress MCP server, which has a fetch-legislative-agenda tool that takes a chamber parameter. The user is asking for the senate agenda, so I should use the fetch-legislative-agenda tool with the chamber parameter set to &quot;senado&quot;.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*nH2tTTvkxmGsPo8ktJZA4Q.png" /></figure><p>User: “Approved”</p><p>AI: The fetch-legislative-agenda tool returned a list of PDFs. I need to parse these PDFs to get the agenda. The dominican-congress MCP server has a parse-pdf tool that takes a pdfUrl parameter. I should iterate through the list of PDFs and use the parse-pdf tool for each one. Since there are many PDFs, I will start with the first one and then use the attempt_completion tool to show the result. If the user wants more, I can continue parsing the other PDFs.</p><p>The first PDF URL is <a href="https://www.senadord.gob.do/Descargas/1379/orden-del-dia/51283/agenda-ordinaria-00041-plo-01-04-2025-se">https://www.senadord.gob.do/Descargas/1379/orden-del-dia/51283/agenda-ordinaria-00041-plo-01-04-2025-se</a><a href="https://camaradediputados.gob.do/download/142/ordenes-del-dia-del-pleno/24926/sesion-ordinaria-no-00000-miercoles-09-de-abril-de-2025-10-00-am.pdf.">.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*00W7GHFFhiT9UjDj6gwU7w.png" /></figure><p>User: “Approved”</p><p>AI: “I have successfully parsed the first PDF and extracted the agenda for the session on Wednesday, April 9, 2025. I can now present this agenda to the user.</p><p>The session includes:</p><ul><li>Verification of quorum and presentation of excuses.</li><li>Presentation of the agenda, reading and approval of pending session minutes.</li><li>Reading of correspondences and presentation of reports submitted to Congress.</li><li>“Turnos Previos” (Previous Turns).</li><li>Observations from the Executive Branch on laws approved by the National Congress.</li><li>Review of bills returned with modifications by the Senate.</li><li>Prioritized bills.</li><li>Initiatives whose knowledge has been declared urgent.</li><li>Initiatives pending from the previous day’s agenda.</li><li>Initiatives to be taken into consideration, following the chronological order of their deposit.</li></ul><p>The agenda also includes a list of initiatives to be considered, including:</p><ul><li>A project of resolution requesting the President to instruct the Ministry of Education to divide the educational district 08–04 of the regional education 08 of the province Santiago.</li><li>A project of law establishing penalties for violence against public health servants.</li><li>A project of law declaring Santo Domingo Oeste as an ecotourism and industrial zone.</li><li>A project of law regulating the Lifeguard Service in Public and Private Resorts.</li><li>Several projects of law designating roads and highways.</li><li>A project of law creating a specialized department for the search of missing persons.</li><li>A project of law modifying the Law on Fiscal Rectification.</li><li>A project of law creating a justice of the peace court in Guayacanes.</li><li>A project of law declaring October 15 as National Rural Woman’s Day.</li><li>A project of resolution forming a parliamentary friendship group with Ukraine.</li><li>A project of law declaring Santiago de los Caballeros as a “city of festivals”.</li><li>A project of law declaring Sabana de la Mar as capital of the Los Haitises National Park.</li><li>A project of law declaring architectural monuments several churches.</li><li>A project of law modifying the Organic Law of the National Police.</li></ul><p>Finally, the session will also cover:</p><ul><li>Internal resolutions.</li><li>A project of law modifying the law declaring El Seibo as an ecotouristic province.</li><li>A project of law declaring Samaná as an ecotouristic province.</li><li>A project of law designating a road with the name José Francisco López Chávez.</li><li>A reading of the list of bills that expire at the end of the legislature.</li><li>A reading of matters sent to committee whose term expires.</li><li>Information turns.”</li></ul><p>As you can see the MCP server is working as expected. It’s been used by our AI (in my case Gemini 2.5 Pro, but it can be used on any client with MCP capabilities).</p><p>This is just a small example of what can be accomplish with these servers. In the recent months we had an avalanche of services using MCP servers, some of the most important are listed <a href="https://modelcontextprotocol.io/examples">here</a>.</p><p>To wrap up, as this post is becoming quite lengthy, I want to emphasize that MCPs are an invaluable tool for AIs. They not only enhance the AI’s understanding of the resources and tools at its disposal but also improve the way LLMs interact with users.</p><p>This has been a fantastic opportunity to explore this emerging paradigm shift. These new types of servers will definitely play a big role in the future — even though the path toward standardization is still long and uncertain.</p><p>And that’s all for todays’ <strong>Vibe Coding Adventures — Day 10</strong>!</p><p><strong>Catch you in the next one! 🚀</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dae1074ab4ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe Coding Adventures: Day 9 — GamePeer JS]]></title>
            <link>https://medium.com/@enzovezzaro/vibe-coding-adventures-day-9-gamepeer-js-ced49de6bc65?source=rss-a225e16db862------2</link>
            <guid isPermaLink="false">https://medium.com/p/ced49de6bc65</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[p2p]]></category>
            <category><![CDATA[js-game]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Enzo Junior Vezzaro]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 17:52:40 GMT</pubDate>
            <atom:updated>2025-04-05T17:52:40.307Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vibe Coding Adventures: Day 9 — GamePeer JS</h3><p>Hi everyone! 👋🏽 Today, day 9 of our <a href="https://medium.com/@enzovezzaro/vibe-coding-adventures-100-days-of-experiments-15a90861674c">Vibe Coding Adventure</a>, I wanted to talk about a project that came up during the development of the <a href="https://medium.com/@enzovezzaro/vibe-coding-adventures-day-8-dominopoli-baaecee5f71f">Dominopoly Game</a>.</p><p>As already mention on the last blog, this monopoli-style dominican game inspired me to develop another project, call <strong>GamePeer JS</strong>.</p><p><strong>What is GamePeer JS?</strong></p><p>GamePeer is a way to easily integrate basic game mechanics into your JS games. I wanted to make my development journey into JS games easier and more enjoyable. That’s why I ended up creating a JS library which utilizes Peer.js to facilite p2p game interactions and development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0bmLAiaooSHubKAnU1jTw.png" /><figcaption>GamePeer JS Website</figcaption></figure><h3>Why is this project on our Vibe Coding journey?</h3><p>Well, it’s because part of the process was done using this AI systems. From the initial prompt to the code development, AI helped me all the way to accomplish this JS library. Sometimes made the experience easier, sometimes harder, but as you already know, it’s part of the process.</p><p>Let’s start by reviewing the first stage, as always, the initial prompt of the project:</p><pre>### **Prompt:**  <br><br>Build a **peer-to-peer multiplayer game engine and library** called **GamePeer JS**, designed for **browser-based 3D games** with real-time networking using **PeerJS**. This is a **frontend-only engine** (no backend servers).<br><br>---<br><br>### **Core Features:**<br><br>1. **Peer-to-Peer Multiplayer Engine:**<br>   - Use **PeerJS** to connect players via **WebRTC**, creating a fully decentralized network.<br>   - Implement **lobby creation, player matchmaking (via room code or direct peer ID)**, and **host-client architecture** where one player acts as the authoritative source.<br>   - Handle **real-time position updates, game events, and input synchronization** between peers.<br><br>2. **Modular Game Framework:**<br>   - Include **modular game logic hooks**, such as `useGameLoop`, `usePlayerControls`, and `useMultiplayerState`.<br>   - Provide tools for **collision detection** and basic **physics integration (Cannon-es)**.<br>   - Support **co-op**.<br><br>3. **Matchmaking &amp; Room Handling:**<br>   - Players can create or join rooms via **peer ID or room code**.<br>   - Optionally use a **signaling list** to track available peers (can be stored temporarily in-memory or indexedDB).<br>   - Display current player count and list of connected peers in UI.<br><br>4. **No Backend, Privacy-Focused:**<br>   - Game state is shared **only between connected peers**.<br>   - No user data, scores, or history is stored on a central server.<br>   - Player stats or settings can be stored in **LocalStorage**.<br><br>5. **Developer-Friendly SDK/API:** (future)<br>   - Expose a simple API (e.g., `connectToPeer(peerId)`, `broadcastUpdate(payload)`, `onPeerMessage(callback)`) for developers to build on.<br>   - Provide example components and hooks to simplify multiplayer game development.<br><br>---<br><br>### 🛠️ Development Stack<br><br>- **Module Type:** ES Modules (`&quot;type&quot;: &quot;module&quot;`)<br>- **Build System:** [Rollup](https://rollupjs.org/)  <br>  - Plugins:<br>    - `@rollup/plugin-node-resolve`<br>    - `@rollup/plugin-commonjs`<br>    - `@rollup/plugin-terser` (for minification)<br>- **Peer-to-Peer Communication:** [PeerJS](https://peerjs.com/) (WebRTC abstraction)<br>- **Documentation:** [JSDoc](https://jsdoc.app/) with `clean-jsdoc-theme`<br>- **Scripts:**<br>  - `build`: Bundles the library<br>  - `dev`: Watches files for changes during development<br>  - `docs`: Generates documentation<br>  - `prepublishOnly`: Builds the library before publishing<br><br>---<br><br>**Final UI/UX Guidelines:**<br><br>- Keep the interface **minimal, game-focused, and fully browser-compatible**.<br>- Allow developers to **plug in their own UIs, scenes, and game logic** with ease.<br>- No signups, no backend—**just instant multiplayer gameplay powered by P2P**.</pre><p>As you can see from the prompt, I needed to build a lightweight, easy to use, plug&amp;play “game engine” for web-based games. Nothing fancy, or complicated, just include it in your project and start using it.</p><p>No more complicated configuration, no more complicated backends and devops setups. Just pure P2P gameplay.</p><h3>It’s time for the AI to play its part! 🤖</h3><p>Given the above prompt to the AI, it generated a pretty basic and standard codebase, with very little functionalities. Which is fine, I just needed to scaffold a basic project for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eShontZpjVaWTUgExYHcYQ.png" /><figcaption>Github commit</figcaption></figure><pre>// GamePeerSDK.js - Browser-to-browser P2P game SDK using PeerJS<br><br>import MatchmakingService from &#39;./MatchmakingService.js&#39;;<br>import VoiceChatManager from &#39;./VoiceChatManager.js&#39;;<br><br>class GamePeerSDK {<br>  constructor(options = {}) {<br>    this.options = {<br>      debug: false,<br>      tickRate: 20, // Updates per second<br>      peerOptions: {}, // PeerJS specific options<br>      useMatchmaking: false,<br>      matchmakingOptions: {},<br>      useVoiceChat: false,<br>      voiceChatOptions: {},<br>      ...options<br>    };<br>    <br>    this.peer = null;<br>    this.connections = new Map(); // Store active connections<br>    this.gameState = new GameState();<br>    this.isHost = false;<br>    this.clientId = null;<br>    this.lastUpdateTime = 0;<br>    this.tickInterval = null;<br>    <br>    // Game state<br>    this.players = {};<br>    this.gameObjects = {};<br>    this.localPlayerId = null;<br>    <br>    // Matchmaking and voice chat managers<br>    this.matchmaking = null;<br>    this.voiceChat = null;<br>    <br>    this.eventHandlers = {<br>      &#39;connection&#39;: [],<br>      &#39;disconnection&#39;: [],<br>      &#39;stateUpdate&#39;: [],<br>      &#39;error&#39;: [],<br>      &#39;roomsUpdated&#39;: [],<br>      &#39;voiceChatConnected&#39;: [],<br>      &#39;voiceChatDisconnected&#39;: []<br>    };<br>    <br>    this._setupLogger();<br>    <br>    // Initialize optional services<br>    if (this.options.useMatchmaking) {<br>      this._initMatchmaking();<br>    }<br>    <br>    if (this.options.useVoiceChat) {<br>      this._initVoiceChat();<br>    }<br>  }<br>  <br>  // Initialize as a host (server)<br>  async hostGame(roomId = null, roomMetadata = {}) {<br>    this.isHost = true;<br>    const id = roomId || this._generateRoomId();<br>    <br>    try {<br>      return await new Promise((resolve, reject) =&gt; {<br>        this.peer = new Peer(id, this.options.peerOptions);<br>        <br>        this.peer.on(&#39;open&#39;, async (peerId) =&gt; {<br>          this.clientId = peerId;<br>          this.localPlayerId = `player_${peerId}`;<br>          this.log(`Initialized as host with ID: ${peerId}`);<br>          <br>          // Register with matchmaking if enabled<br>          if (this.matchmaking) {<br>            try {<br>              await this.matchmaking.init(peerId);<br>              await this.matchmaking.registerRoom(peerId, roomMetadata);<br>            } catch (err) {<br>              this.log(&#39;Warning: Failed to register with matchmaking service&#39;, err);<br>            }<br>          }<br>          <br>          // Initialize voice chat if enabled<br>          if (this.voiceChat) {<br>            try {<br>              await this.voiceChat.init(this.peer);<br>            } catch (err) {<br>              this.log(&#39;Warning: Failed to initialize voice chat&#39;, err);<br>            }<br>          }<br>          <br>          this._createLocalPlayer();<br>          this._startGameLoop();<br>          resolve(peerId);<br>        });<br>        <br>        this.peer.on(&#39;connection&#39;, (conn) =&gt; {<br>          this._handleNewConnection(conn);<br>        });<br>        <br>        this.peer.on(&#39;error&#39;, (err) =&gt; {<br>          this._triggerEvent(&#39;error&#39;, err);<br>          reject(err);<br>        });<br>      });<br>    } catch (err) {<br>      this._triggerEvent(&#39;error&#39;, err);<br>      throw err;<br>    }<br>  }<br>  <br>  // Join an existing game<br>  async joinGame(hostId) {<br>    try {<br>      return await new Promise((resolve, reject) =&gt; {<br>        this.peer = new Peer(this.options.peerOptions);<br>        <br>        this.peer.on(&#39;open&#39;, async (id) =&gt; {<br>          this.clientId = id;<br>          this.localPlayerId = `player_${id}`;<br>          this.log(`Initialized as client with ID: ${id}`);<br>          <br>          // Initialize voice chat if enabled<br>          if (this.voiceChat) {<br>            try {<br>              await this.voiceChat.init(this.peer);<br>            } catch (err) {<br>              this.log(&#39;Warning: Failed to initialize voice chat&#39;, err);<br>            }<br>          }<br>          <br>          // Connect to the host<br>          const conn = this.peer.connect(hostId, {<br>            reliable: true<br>          });<br>          <br>          conn.on(&#39;open&#39;, () =&gt; {<br>            this.log(`Connected to host: ${hostId}`);<br>            this.connections.set(hostId, conn);<br>            <br>            this._setupDataHandling(conn);<br>            this._triggerEvent(&#39;connection&#39;, { peerId: hostId });<br>            <br>            // Connect to voice chat if enabled<br>            if (this.voiceChat) {<br>              this.voiceChat.callPeer(hostId).catch(err =&gt; {<br>                this.log(&#39;Warning: Failed to connect voice chat&#39;, err);<br>              });<br>            }<br>            <br>            this._createLocalPlayer();<br>            this._requestFullState();<br>            resolve(hostId);<br>          });<br>          <br>          conn.on(&#39;error&#39;, (err) =&gt; {<br>            this._triggerEvent(&#39;error&#39;, err);<br>            reject(err);<br>          });<br>        });<br>        <br>        this.peer.on(&#39;error&#39;, (err) =&gt; {<br>          this._triggerEvent(&#39;error&#39;, err);<br>          reject(err);<br>        });<br>      });<br>    } catch (err) {<br>      this._triggerEvent(&#39;error&#39;, err);<br>      throw err;<br>    }<br>  }<br>  <br>  // Game object management<br>  createGameObject(type, props = {}) {<br>    const objectId = `obj_${Date.now()}_${Math.random().toString(36).substr(2, 5)}`;<br>    const gameObject = {<br>      type,<br>      ownerId: this.localPlayerId,<br>      ...props<br>    };<br>    <br>    this.gameObjects[objectId] = gameObject;<br>    this.syncGameObject(objectId, gameObject);<br>    return objectId;<br>  }<br>  <br>  movePlayer(x, y) {<br>    if (!this.localPlayerId) return;<br>    <br>    const player = this.players[this.localPlayerId];<br>    if (player) {<br>      player.x = x;<br>      player.y = y;<br>      this.syncGameObject(this.localPlayerId, { x, y });<br>    }<br>  }<br>  <br>  // Clean up resources<br>  destroy() {<br>    if (this.tickInterval) clearInterval(this.tickInterval);<br>    if (this.peer) this.peer.destroy();<br>    if (this.voiceChat) this.voiceChat.destroy();<br>  }<br>  <br>  // Private methods<br>  _createLocalPlayer() {<br>    const playerData = {<br>      name: `Player ${this.clientId.substr(0, 5)}`,<br>      x: Math.floor(Math.random() * 500),<br>      y: Math.floor(Math.random() * 500),<br>      color: this._getRandomColor()<br>    };<br>    <br>    this.players[this.localPlayerId] = playerData;<br>    this.syncGameObject(this.localPlayerId, playerData);<br>  }<br>  <br>  _getRandomColor() {<br>    const colors = [&#39;#FF5733&#39;, &#39;#33FF57&#39;, &#39;#3357FF&#39;, &#39;#F3FF33&#39;, &#39;#FF33F3&#39;];<br>    return colors[Math.floor(Math.random() * colors.length)];<br>  }<br>  <br>  // ... (rest of the GameNetworkSDK implementation)<br>}<br><br>// Helper class for game state management<br>class GameState {<br>  constructor() {<br>    this.state = {};<br>  }<br>  <br>  set(key, value) {<br>    this.state[key] = value;<br>  }<br>  <br>  get(key) {<br>    return this.state[key];<br>  }<br>  <br>  getFullState() {<br>    return this.state;<br>  }<br>  <br>  updateState(updates) {<br>    Object.assign(this.state, updates);<br>  }<br>}<br><br>export default GamePeerSDK;</pre><p>The AI did a good job creating a basic template for our project; with basic configurations needed for our work. Above you can see one of the main files created by the AI.</p><h3>It’s time for the Human 👨🏽‍💻</h3><p>As you can see, our project is far from complete. It lacks almost all the functionalities, and the ones created needed some changes.</p><p>I started from the beginning, as always:</p><p>1️⃣ Clean up the codebase: remove any logic you don’t need, reduce duplications, separate as much as posible into small pieces and files, make sure it’s well organized and structure the way you want.</p><p>2️⃣ Check and update any library you want to use: make sure your project it’s updated to avoid build issues along the way.</p><p>3️⃣ Write down your final user experience: make a file with the end goal for the AI, so it can always have a look if it gets confused.</p><pre><br>GamePeer JS Developer Experience<br><br>I want to be this way:<br><br>Initialize <br>const game = new GamePeerJS({<br>  debug: true,<br>  useKeyboardController: true, <br>  useMouseController: true, // create this one, if true it need to track the mouse and listen to it, like keyboard services<br>  localPlayerId: `player-${Math.random().toString(36).substr(2, 8)}` // if not passed, it get created for you<br>  ...<br>});<br><br>// host game<br>const roomId = await game.hostGame(); // return room id<br><br>// join game<br>const result = await game.joinGame(roomId); // return &quot;success&quot; or &quot;failed&quot;<br><br>// listen to custom events<br>game.on(&lt;CUSTOM_EVENT_NAME /&gt;, (data) =&gt; {<br>  ...<br>})<br><br>// global listener &#39;stateUpdate&#39; - this listens and broadcast all changes. These are always available and brodcasting<br>CUSTOM_SYSTEM_DEFAULTS = &#39;stateUpdate&#39;<br>game.on(&lt;CUSTOM_SYSTEM_DEFAULTS /&gt;, (data) =&gt; {<br>  ...<br>})<br><br>// create object Game<br>game.createGameObject(&lt;CUSTOM_ID /&gt;, {<br>  ...<br>})<br><br>// global broadcastEvent - this broadcast the data for all users<br>game.broadcastEvent(&#39;bullet&#39;, {<br>  ...<br>})<br><br>// -------------------<br>// -------------------<br><br>Must be configued as useKeyboardController: true in Initialize<br>If this is not set, don&#39;t broadcast or track keyboard<br><br>// controller keyboardController<br>const keyboard = game.keyboardController({<br>  keybindings: [[EVENT_NAME, KEY_NAME (example &quot;ArrowLeft&quot;)]]<br>})<br><br>// listens to key events<br>keyboard.on(&lt;EVENT_NAME /&gt;, ({action, event}) =&gt; {<br>  ...<br>});<br><br>// default bindings available - these are listen and broadcast by default.<br>EVENT_DEFAULT_NAME = &#39;up&#39;, &#39;down&#39;, &#39;left&#39;, &#39;right&#39;, &#39;space&#39;, &#39;enter&#39;<br>keyboard.on(&lt;EVENT_DEFAULT_NAME /&gt;, ({action, event}) =&gt; {<br>  ...<br>});<br><br>// listens to any error in the controller<br>mouse.on(&#39;error&#39;, ({message, error}) =&gt; {<br>  console.error(&#39;Matchmaking error:&#39;, message, error);<br>});<br><br>// -------------------<br>// -------------------<br><br>Must be configued as useMouseController: true in Initialize<br>If this is not set, don&#39;t broadcast or track mouse<br><br>// controller keyboardController<br>const mouse = game.mouseController({<br>  keybindings: [[EVENT_NAME, KEY_NAME (example &quot;right click&quot;)]]<br>})<br><br>// listens to key events<br>mouse.on(&lt;EVENT_NAME /&gt;, ({action, event}) =&gt; {<br>  ...<br>});<br><br>// default bindings available - these are listen and broadcast by default.<br>EVENT_DEFAULT_NAME = &#39;mousemove&#39;, &#39;mousedown&#39;, &#39;mouseup&#39;, &#39;click&#39;, ...<br>mouse.on(&lt;EVENT_DEFAULT_NAME /&gt;, ({action, event}) =&gt; {<br>  ...<br>});<br><br>// listens to any error in the controller<br>mouse.on(&#39;error&#39;, ({message, error}) =&gt; {<br>  console.error(&#39;Matchmaking error:&#39;, message, error);<br>});<br><br><br>// -------------------<br>// -------------------<br><br>// Matchmaking<br>const matchmaking = game.matchmaking({<br>  ...<br>})<br><br>// Initialize with unique client ID<br>await matchmaking.init(clientId);<br><br>// Register Room<br>await matchmaking.registerRoom(roomId, {<br>  ...<br>});<br><br>// Update Room<br>await matchmaking.updateRoom({<br>  ...<br>});<br><br>// get all rooms<br>const rooms = await matchmaking.refreshRooms();<br><br>// filter rooms<br>const filteredRooms = matchmaking.findRooms({<br>  ...<br>});<br><br>// Join Room<br>const roomInfo = await matchmaking.joinRoom(roomId, &#39;password-if-required&#39;);<br>// Returns { id, host, password }<br><br>// listen to changes to the room<br>matchmaking.on(&#39;roomsUpdated&#39;, ({rooms}) =&gt; {<br>  console.log(&#39;Updated rooms list:&#39;, rooms);<br>});<br><br>// listens to any error in the controller<br>matchmaking.on(&#39;error&#39;, ({message, error}) =&gt; {<br>  console.error(&#39;Matchmaking error:&#39;, message, error);<br>});<br><br>// clean up room<br>matchmaking.destroy();<br><br><br>//// FOLLOW THIS PATTERN FOR the rest</pre><p>This way you can improve it’s acuracy and avoid too many allucinations.</p><p>4️⃣ Clean up your Github Repository: make sure your Github Repo (or the version control you use) it’s ready for commits.</p><h3>Let’s start building! 👷🏽‍️</h3><p>Now that we have everything in place, we can start building the product and putting all the pieces together.</p><p>I started from the initialization to then code the controllers, and later focus on the player’s interactivity and game’s object interactions. It took me a while, about 6 hours, but the end result was pretty sweet. I really enjoyed this part.</p><p>The end product is a modular based project with all the functionalities isolated for maintainability and readability purposes.</p><p>The object tracking was particularly tricky, as keeping updates between peers is not as easy as it sounds. Having objects being track and sync between two or more participants is not an easy task to pull off, but GamePeer JS tries to make as simple as posible.</p><p><strong>Key features developed:</strong></p><ul><li>Host/client game architecture</li><li>Game state synchronization</li><li>Player and game object management</li><li>Event system for game events</li><li>Support for matchmaking, voice chat, and input controllers</li><li>Tick-based game loop</li></ul><p><strong>Core Architecture:</strong></p><ul><li>src/: Core code</li><li>modules/: Main components</li><li>services/: Additional services</li><li>examples/: Demo implementations</li><li>docs/: Documentation (generated via JSDoc)</li><li>config/: Build and documentation config</li></ul><p><strong>Main Components:</strong></p><ul><li>src/modules/GamePeerJS.js: Core JS class</li><li>Manages peer connections (PeerConnectionManager)</li><li>Handles game state synchronization (GameState)</li><li>Provides player management (PlayerInitializer)</li><li>Supports services like matchmaking, voice chat, input controllers</li><li>Event system for game events</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4HTNil_0CQa5Subs8Hktg.png" /><figcaption>Project Structure</figcaption></figure><p>The end result shows a comprehensive peer-to-peer gaming JS library that enables developers to create multiplayer browser games with minimal server infrastructure.</p><p>GamePeer JS provides core functionalities for establishing direct browser-to-browser connections, synchronizing game state, managing players and game objects, and includes built-in services for matchmaking, voice chat, and input handling.</p><p>It’s all about simplicity and developer experience! Of course, this is a solo developer’s project, released in <a href="https://github.com/EnzoVezzaro/gamepeer-js">open source</a>; for sure it will have some buggy behaviors, but overall it did accomplished the job, and it has been useful for those cases where servers might not be need it, or are too expensive.</p><p>I also added some examples to watch:</p><ul><li>examples/interactive/ — interactivity example</li><li>examples/keyboard/ — keyboard controller examples</li><li>examples/matchmaking/ — matchmaking example</li><li>examples/pingpong/ — play the pingpong gme with a peer</li><li>examples/snake/ — play the snake game with others</li></ul><p>GamePeer JS is a solution for building simple WebRTC-based multiplayer games that can scale from simple 2-player games to more complex multiplayer experiences.</p><p>After about 1/2 days, I finished the basic mechanics, tested them against the examples (I didn’t build any test for this, sorry if something get ofended), and release to NPM. Yes, npm. As well as configuring GH Actions, creating the website, and more.</p><p>If you want to use it, you can download this package from NPM:</p><pre>&gt; npm i gamepeer-js</pre><p>After which you can use it on your project like so:</p><pre>import { GamePeerJS } from &#39;gamepeer-js&#39;;<br><br>const game = new GamePeerJS({<br>  debug: false, // Enable debug logging (default: false)<br>  useKeyboardController: false, // Enable keyboard input (default: false)<br>  useMouseController: false, // Enable mouse input (default: false)<br>  useMatchmaking: false, // Enable matchmaking (default: false)<br>  useVoiceChat: false, // Enable voice chat (default: false)<br>  tickRate: 20, // Game state updates per second (default: 20)<br>  localPlayerId: `player-${Math.random().toString(36).substr(2, 8)}` // Auto-generated if not provided<br>});</pre><blockquote>It’s that simple!</blockquote><p>For more information about this project go to 👇🏽</p><p>Website: <a href="https://gamepeerjs.netlify.app/">https://gamepeerjs.netlify.app/</a></p><p>Docs: <a href="https://gamepeerjs-docs.netlify.app/">https://gamepeerjs-docs.netlify.app/</a></p><p>NPM: <a href="https://www.npmjs.com/package/gamepeer-js">https://www.npmjs.com/package/gamepeer-js</a></p><p><strong>Try it out! 👾</strong></p><p>As already mentioned, GamePeer JS is Currently in development. You will find some bug for sure ☕️ PRs are welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ced49de6bc65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe Coding Adventures: Day 8— Dominopoly]]></title>
            <link>https://medium.com/@enzovezzaro/vibe-coding-adventures-day-8-dominopoli-baaecee5f71f?source=rss-a225e16db862------2</link>
            <guid isPermaLink="false">https://medium.com/p/baaecee5f71f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[3d-game-development]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[monopoly]]></category>
            <dc:creator><![CDATA[Enzo Junior Vezzaro]]></dc:creator>
            <pubDate>Tue, 01 Apr 2025 15:41:04 GMT</pubDate>
            <atom:updated>2025-04-05T17:39:48.380Z</atom:updated>
            <content:encoded><![CDATA[<p>Well well well, I know this is kind of a cliché at this point. But let’s build a game 👾</p><p>What type of game? I monopoly game 😅 why monopoly, I still don’t know.</p><p>Let’s begin from the basis. What am I try to accomplish with this project? In few words — realtime interactivity, game mechanics, and complex algorithms.</p><p>Since I don’t want to use servers either, let’s make it p2p too.</p><h3>Why monopoly?</h3><p>I’m still asking myself this 😂 while working on it, I realized how many rules this game has making it so much complicated that I though.</p><p>Still; it’s been a great excesive and actually have helped me a lot to enjoy coding again.</p><p>So, let’s explore the rules before getting into the code.</p><pre>### Basic rules of **Monopoly**:<br><br>### **Objective**:  <br>The goal is to bankrupt your opponents by buying, renting, and selling properties.<br><br>### **Setup**:<br>1. **Board**: Place the board on a flat surface.<br>2. **Pieces**: Each player selects a token (e.g., car, dog, hat).<br>3. **Money**: Each player starts with $1500, consisting of:<br>   - 2 x $500 bills<br>   - 4 x $100 bills<br>   - 1 x $50 bill<br>   - 1 x $20 bill<br>   - 2 x $10 bills<br>   - 1 x $5 bill<br>   - 5 x $1 bills<br>4. **Dice**: Players take turns rolling two dice.<br><br>### **Gameplay**:<br>1. **Turn Sequence**: Players take turns rolling the dice and moving their token clockwise around the board.<br>2. **Landing on Properties**:  <br>   - **Buy Properties**: If you land on an unowned property, you can buy it at the listed price.<br>   - **Pay Rent**: If you land on an opponent&#39;s property, pay them rent according to the property&#39;s deed card.<br>3. **Chance and Community Chest**:  <br>   - Draw a card from the respective deck when landing on these spaces and follow the instructions.<br>4. **Jail**:  <br>   - You go to jail if you roll doubles three times in a row or land on the &quot;Go to Jail&quot; space.<br>   - You can get out by rolling doubles on your next turn or paying a $50 fine.<br><br>### **Building**:<br>1. **Houses and Hotels**:  <br>   - You can build houses or hotels on properties you own (monopolies). Build evenly (no more than 4 houses per property before you build a hotel).<br>   - Rent increases with houses and hotels.<br><br>### **Bankruptcy**:<br>- If you owe more money than you can pay, you must declare bankruptcy and lose all assets.<br>- If you owe another player, you give them your properties. If you owe the bank, your properties are returned to the bank.<br><br>### **Winning**:<br>- The last player remaining who is not bankrupt wins the game.<br><br>These are the basic rules, but there are many house rules people often play with, such as trading properties and adding extra bonuses for certain actions. Enjoy the game!</pre><p>As you can see this game has a lot of rules which mean that we’ll required a lot of functional logic to make this work.</p><p>To add we need to add a custom dominican flavor to it, and also make sure it’s all p2p without requiring any server to run. Lastly, but not least, let’s make 3d also, why not 😅.</p><p>Now that we have a basis understanding of the game, let’s start building it!</p><h3>It’s time for the AI 🤖</h3><p>As you already know, this series it’s all about AI. How these new tools are improving developers capabilities and productivity. Is the hype true or we’re facing another hype mirage? As always, the true probably is in the middle.</p><p>The first step, as you know, it’s the prompt. For this I used a mix of <a href="https://openai.com/index/chatgpt/">ChatGPT o4</a> and <a href="https://www.anthropic.com/news/claude-3-7-sonnet">Claude 3.7 Sonnet</a>. You probably don’t need to see the back and fourth with the AIs, but this required me about 20 min of prompting, and probably with more time, I could’ve improve even more this end prompt. But let’s go with it, this is the end result:</p><pre>Monopoly Game Documentation (Dominican Theme)<br><br>1. Introduction<br><br>This project is a Dominican-themed multiplayer Monopoly game, where up to 10 players can play together in a 3D environment. The game allows for peer-to-peer (P2P) communication using Peer.js, and supports both human players and AI bots (when there are fewer players than expected). The game includes a waiting room for the game creator and players to join, and the creator has control over when the game starts.<br><br>2. Key Features<br><br>Dominican Themed Components: All game elements, such as the board, characters, properties, and cards, are themed around Dominican culture.<br><br>Up to 10 Players: Maximum of 10 human players per game session. The creator specifies how many players can join.<br><br>Peer.js Integration: For real-time, peer-to-peer communication between all players, handling player moves and updates live.<br><br>Bot Integration: If the number of human players is less than the desired count, bots are automatically added to fill the spots.<br><br>Waiting Room: The game creator waits in a room until the players join. The creator can start the game at any time.<br><br>3D Environment: The game is built using a 3D engine (e.g., Three.js or Babylon.js) for an immersive experience.<br><br>Customizable Game Settings: The creator can specify the number of players for each game session.<br><br>3. Game Flow<br><br>3.1. Game Creation<br><br>Game Creator specifies the number of players and creates a new game channel.<br><br>Game Link: The creator is provided with a unique URL to share with other players. This link connects to the game.<br><br>The creator is placed in the waiting room, where they can wait for other players to join.<br><br>3.2. Joining the Game<br><br>Players click the shared link to join the game.<br><br>After joining, they are placed in the waiting room and see a message: &quot;Waiting to start game by the owner&quot;.<br><br>Players can see how many players have joined and how many are still needed to start.<br><br>3.3. Starting the Game<br><br>The game creator has a &quot;Start Game&quot; button.<br><br>Once the creator presses &quot;Start Game&quot;, the server checks how many human players have joined.<br><br>If there are fewer players than the specified number, bots will automatically join to fill the remaining spots.<br><br>3.4. Playing the Game<br><br>Once the game starts, all players (human and bots) can take turns.<br><br>Peer.js handles the communication of each player&#39;s move, updating the game state in real-time.<br><br>The game continues as a typical Monopoly game but with Dominican-themed components.<br><br>4. Technical Setup<br><br>4.1. Peer.js Communication<br><br>Peer-to-Peer Connections: Peer.js is used to establish connections between players.<br><br>Game Room: Each game session is represented by a unique room ID. Players connect to this room using their Peer.js ID.<br><br>Real-Time Updates: Game states (e.g., player positions, property purchases, etc.) are sent to all players in real-time.<br><br>4.2. Waiting Room Management<br><br>The game creator is the host and controls when the game starts. The creator’s browser maintains a list of connected players.<br><br>Players in the waiting room are shown the current status of the game, such as how many players have joined and how many are still needed.<br><br>4.3. Bots<br><br>Bot Creation: If the number of human players is less than the specified number, bots will be created to fill the remaining spots.<br><br>Bot Logic: Bots will automatically perform typical Monopoly moves, such as rolling dice, purchasing properties, and paying rent.<br><br>Bot Representation: Bots will have a unique name (e.g., &quot;Bot 1&quot;, &quot;Bot 2&quot;) and appear as human players in the game interface.<br><br>5. 3D Engine Integration (e.g., Three.js)<br><br>Board and Characters: The board is rendered in a 3D space using Three.js (or another 3D engine). Each player is represented by a 3D character/avatar with Dominican cultural themes (e.g., traditional outfits, iconic landmarks).<br><br>Camera and Controls: Players can view the game from different angles, and the camera is automatically adjusted based on the player’s movements.<br><br>Game Actions: Player actions, such as rolling dice and moving tokens, are also represented in 3D.<br><br>6. Game Logic<br><br>6.1. Player Turns<br><br>Players take turns to roll the dice and move their token across the board.<br><br>Each player’s move is broadcasted to all peers using Peer.js. The game state (player position, properties owned, etc.) is synchronized in real-time.<br><br>6.2. Bot Logic<br><br>Bots play using a simple algorithm that simulates Monopoly strategies, such as purchasing properties when appropriate, managing their cash flow, and participating in auctions.<br><br>Bots take their turns automatically, without user input.<br><br>6.3. Real-Time Synchronization<br><br>Every time a player makes a move, it is immediately shared with the other players using Peer.js.<br><br>Players will see each other’s moves, and the game board will be updated live, ensuring an interactive experience.<br><br>7. Front-End (UI)<br><br>7.1. Game Creation Screen<br><br>Input for specifying the number of players (1 to 10).<br><br>Button to create a new game and generate a shareable link.<br><br>7.2. Waiting Room Screen<br><br>Display of the current players connected and the total number of players required.<br><br>Button to start the game (only visible to the game creator).<br><br>7.3. Game Board<br><br>3D Monopoly board with Dominican-themed elements.<br><br>Player tokens are moved in real-time based on the dice roll.<br><br>Cards, properties, and cash are all updated visually in the 3D environment.<br><br>Player Interaction: Players can click on properties, perform trades, and make transactions.</pre><p>Now that we have our prompt, let’s see if the AI is capable of taking on this task.</p><p>Let’s start with our friend <a href="https://lovable.dev/">Lovable.dev</a> (at this point they should be sponsoring this series 😂).</p><p>Given this prompt to the AI, I can say that the end result was dicent, but lacking of most of what I asking for 😅.</p><p>What did the AI built?</p><p>✅ 3d Basic Board game with Three.js and plain CSS</p><p>✅ Basic logic for connection</p><p>✅ Waiting Room</p><p>✅ Room creation</p><p>✅ Basic Peer.js integration</p><p>What did miss or did wrong?</p><p>☑️ 3d player</p><p>☑️ Complex P2P comunication</p><p>☑️ Complex game mechanics</p><p>☑️ Missing a lot of rules</p><p>☑️ Pretty basic dominican theme</p><p>☑️ Produce a lot bad choices:</p><p>— unnecesary lighting on the 3d board</p><p>— huge huge codebase in single JS</p><p>— wrong implementation of Peer.js</p><p>At this point I was done with the AI. Even though it didn’t do a great job, it was a good enough baseline to start fixing stuff and improving on what was done.</p><h3>Here is where the human comes in! 😊</h3><p>Time for the human to take over and start the coding journey. Of course, with other AIs companions on my side using <a href="https://cline.bot/">Cline</a> on VScode.</p><p>First of all I started by downloading the project/repo in local. This is fundamental if you want to work with AI. Keeping track of your changes will save you ton of time and frustration.</p><p>Once the project is setup and running we can start making our changes.</p><p><strong>Time for cleanup!</strong></p><p>What’s the first step? of cource, cleaning up as much as you can. This will make your life easier, and the project much easier to manage. Remove as much as posible, of cource leaving intact what’s working properly. This step requires a lot of attention, because you’re not familiar with the code you’ll be reviewing, which means that you’ll have to figure out a lot of logic that wasn’t written by you. You’ll need enough experience to see the code and understand if can be changed, moved, refactor, or remove.</p><p>This is not a really easy task, and will require some time to accomplish properly.</p><p>For this project I focused on the most obvios ones, we can keep doing this for much longer, so don’t think you’ll find a diamond polished game.</p><h3>Coding time!</h3><p>Now that we have our initial project setup, and cleaned up (as much as it can be), it’s time to get into the code 🙌🏽.</p><p>🔰 What do we do first, how do we proceed?</p><p>I started from the beginning, the peer connections and waiting room.</p><p>After reviewing the code, I made some changes for different reason: code consistency, removing code duplications, adapting logic to the game’s rules, and improving the overall experience.</p><p>The end result is a nice game initialization page, where users can enter their names and create a game that they can share.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwyLxVO_0TJNYNa08QgQIw.png" /><figcaption>Room Creation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RD3tIr63rE4qtfX-c3UQbg.png" /><figcaption>Waiting Room</figcaption></figure><p>Once you create the game, you’ll get an invite link you can share to start a game with other users. Otherwise you can just “Start Game” with bots.</p><h3>Board and 3D objects 🕹️</h3><p>This is where stuff started to fall apart 😅 The AI didn’t do a good job at all here. It created the basic layout, but it was really basic. I ended up working for about 1 hour just on this component to make it “kind of ok”.</p><p>Let’s just explore the end result of this part, after all the changes and refactoring made on the game:</p><pre>import React, { useRef, useEffect, useState, useCallback, Suspense } from &#39;react&#39;; // Added Suspense<br>import { Canvas, useLoader, useFrame } from &#39;@react-three/fiber&#39;; // Added useLoader and useFrame<br>import { OrbitControls, Text, useTexture, useFBX } from &#39;@react-three/drei&#39;;<br>import * as THREE from &#39;three&#39;;<br>import { OBJLoader } from &#39;three/examples/jsm/loaders/OBJLoader.js&#39;; // Added OBJLoader<br>import { Button } from &#39;@/components/ui/button&#39;;<br>import { Card, CardContent } from &#39;@/components/ui/card&#39;;<br>import { Badge } from &#39;@/components/ui/badge&#39;;<br>import { Dices, CircleDollarSign, Home, Bot } from &#39;lucide-react&#39;;<br>import { GameState, Player, Property } from &#39;@/types/game&#39;;<br>import PlayerInfo from &#39;./PlayerInfo&#39;;<br>import PlayerToken from &#39;./PlayerToken&#39;; // Import the new component<br>import PeerService from &#39;@/services/PeerService&#39;;<br>import PropertyActionCard from &#39;./PropertyActionCard&#39;;<br>import { DEFAULT_REWARD_GO, getPropertyColor } from &#39;@/lib/colors&#39;;<br>import { CardEffectAction, handleCardEffect } from &#39;@/lib/card-effects&#39;;<br><br>interface GameBoardProps {<br>  gameState: GameState;<br>  onRollDice: (dice: [number, number]) =&gt; void;<br>  onEndTurn: () =&gt; void;<br>  onBuyProperty: (propertyId: string) =&gt; void;<br>  onMovePlayer: (playerId: string, newPosition: number) =&gt; void;<br>  onUpdateMoney: (playerId: string, amount: number) =&gt; void;<br>  onUpdateJailStatus: (playerId: string, jailed: boolean) =&gt; void;<br>  onJailCard: (playerId: string) =&gt; void; // Rename prop<br>}<br><br>// Create a texture loader once outside of component to avoid recreating on every render<br>const textureLoader = new THREE.TextureLoader();<br>const fallbackTexture = textureLoader.load(<br>  &#39;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==&#39;<br>);<br><br>// Create a cached texture loader for board texture<br>let boardTextureCache: THREE.Texture | null = null;<br><br>const RotatingIndicator = () =&gt; {<br>  const ref = useRef&lt;THREE.Group&gt;(null);<br>  const playerIndicator = useFBX(&#39;/assets/3d/Players/Player_indicator.fbx&#39;);<br>  <br>  useFrame((state, delta) =&gt; {<br>    if (ref.current) {<br>      ref.current.rotation.y += delta * 2; // Rotate at 2 radians per second<br>    }<br>  });<br><br>  return (<br>    &lt;group ref={ref}&gt;<br>      &lt;primitive<br>        object={playerIndicator.clone()}<br>        scale={0.005}<br>      /&gt;<br>    &lt;/group&gt;<br>  );<br>};<br><br>const Board = ({ <br>  properties, <br>  players, <br>  currentPlayer,<br>  onSpaceClick <br>}: { <br>  properties: Property[], <br>  players: Player[],<br>  currentPlayer: number,<br>  onSpaceClick: (property: Property | null, position: number) =&gt; void<br>}) =&gt; {<br>  const boardRef = useRef&lt;THREE.Group&gt;(null);<br>  const [boardTexture, setBoardTexture] = useState&lt;THREE.Texture&gt;(fallbackTexture);<br>  <br>  // Load texture only once with useEffect<br>  useEffect(() =&gt; {<br>    if (!boardTextureCache) {<br>      textureLoader.load(<br>        &#39;/board-texture.jpg&#39;,<br>        (texture) =&gt; {<br>          boardTextureCache = texture;<br>          setBoardTexture(texture);<br>        },<br>        undefined,<br>        () =&gt; {<br>          console.warn(&#39;Failed to load board texture, using fallback&#39;);<br>          setBoardTexture(fallbackTexture);<br>        }<br>      );<br>    } else {<br>      setBoardTexture(boardTextureCache);<br>    }<br>  }, []);<br>  <br>  const boardSize = 22;  // Keep same overall board size<br>  const spaceSize = 1.8; // Make properties thinner<br><br>  const houseModel = useFBX(&#39;/assets/3d/Buildings/Building_1.fbx&#39;);<br>  const houseModel4 = useFBX(&#39;/assets/3d/Buildings/Building_5.fbx&#39;);<br>  const hotelModel = useFBX(&#39;/assets/3d/Buildings/Building_3.fbx&#39;);<br>  <br>  const goTileModel = useFBX(&#39;/assets/3d/Props/Traffic_Light_2.fbx&#39;);<br>  // const jailModel = useFBX(&#39;/assets/3d/Buildings/Building_6.fbx&#39;);<br>  const goJailModel = useFBX(&#39;/assets/3d/Buildings/Jail/1.fbx&#39;);<br>  const parkModel = useFBX(&#39;/assets/3d/Props/Tram_Stop_1.fbx&#39;);<br>  <br>  // Create board spaces<br>  const boardSpaces = [];<br>  for (let i = 0; i &lt; 40; i++) {<br>    let x = 0, z = 0;<br>    const cornerOffset = boardSize / 2 - spaceSize / 2;<br>    <br>    if (i &lt; 10) { <br>      // First side (GO to JAIL) - correct as is<br>      if (i === 0) { x = cornerOffset; z = cornerOffset; } // GO<br>      else if (i &lt; 10) { x = cornerOffset - i * spaceSize - 1.1; z = cornerOffset - 0.85; } // Properties 1-9<br>    }<br>    else if (i &lt; 20) { <br>      // Second side (JAIL to PARKING)<br>      if (i === 10) { x = -cornerOffset; z = cornerOffset; } // JAIL<br>      else if (i &lt; 20) { x = -cornerOffset + spaceSize - 1; z = cornerOffset - (i - 10) * spaceSize - 1.1; } // Properties 11-19<br>    }<br>    else if (i &lt; 30) { <br>      // Third side (PARKING to GO TO JAIL)<br>      if (i === 20) { x = -cornerOffset; z = -cornerOffset; } // PARKING<br>      else if (i &lt; 30) { x = -cornerOffset + (i - 20) * spaceSize + 1.1; z = -cornerOffset + 0.85; } // Properties 21-29<br>    }<br>    else { <br>      // Fourth side (GO TO JAIL to GO)<br>      if (i === 30) { x = cornerOffset; z = -cornerOffset; } // GO TO JAIL<br>      else if (i &lt; 40) { x = cornerOffset - 0.85; z = -cornerOffset + (i - 30) * spaceSize + 1.1; } // Properties 31-39<br>    }<br>    <br>    const property = properties.find(p =&gt; p.position === i);<br>    const color = getPropertyColor(property);<br>    <br>    const isCorner = i % 10 === 0; // Positions 0,10,20,30 are corners<br>    <br>    boardSpaces.push(<br>      &lt;group <br>        key={`space-${i}`} <br>        position={[x, 0, z]} // Raise corners slightly<br>        onClick={() =&gt; onSpaceClick(property, i)}<br>        rotation={[0, <br>          i &lt; 10 ? 0 : <br>          i &lt; 20 ? -Math.PI/2 : <br>          i &lt; 30 ? Math.PI : <br>          Math.PI/2, <br>        0]}<br>      &gt;<br>        {isCorner ? (<br>          i === 0 ? (<br>            // Special case for GO tile (position 0)<br>            &lt;Suspense fallback={null}&gt; {/* Add Suspense for model loading */}<br>              &lt;primitive <br>                object={goTileModel.clone()} <br>                position={[-1.9, 0, 0.9]}<br>                scale={0.2}<br>                rotation={[0, Math.PI/2, 0]}<br>              /&gt;<br>            &lt;/Suspense&gt;<br>          ) : i === 20 ? (<br>            // Parking space (position 20)<br>            &lt;Suspense fallback={null}&gt;<br>              &lt;primitive <br>                object={parkModel.clone()}<br>                position={[0.2, 0, 0.3]}<br>                scale={0.15}<br>                rotation={[0, 180, 0]}<br>              /&gt;<br>            &lt;/Suspense&gt;<br>          ) : i === 30 ? (<br>            // Go to Jail space (position 30)<br>            &lt;Suspense fallback={null}&gt;<br>              &lt;primitive <br>                object={goJailModel.clone()}<br>                position={[0, 0.62, 0]}<br>                scale={0.01}<br>                rotation={[0, -Math.PI/2, 0]}<br>              /&gt;<br>            &lt;/Suspense&gt;<br>          ) : (<br>            // Other corner spaces - wider and taller<br>            &lt;mesh position={[-0.55, 0, -0.55]} receiveShadow&gt;<br>              &lt;boxGeometry args={[spaceSize * 1.55, 0, spaceSize * 1.55]} /&gt;<br>              &lt;meshStandardMaterial color={color || &#39;gray&#39;} /&gt;<br>            &lt;/mesh&gt;<br>          )<br>        ) : (<br>          // Regular property space<br>          &lt;mesh position={[0, 0, -0.7]} receiveShadow&gt;<br>            &lt;boxGeometry args={[spaceSize, 0.1, 0.9]} /&gt;<br>            &lt;meshStandardMaterial color={color} /&gt;<br>          &lt;/mesh&gt;<br>        )}<br>        &lt;Text<br>          position={[0, 0.1, 0]}<br>          rotation={[-Math.PI / 2, 0, 0]}<br>          fontSize={0.2}<br>          color=&quot;black&quot;<br>          anchorX=&quot;center&quot;<br>          anchorY=&quot;middle&quot;<br>        &gt;<br>          {property ? property.name.substring(0, 10) : `Space ${i}`}<br>        &lt;/Text&gt;<br>        {property?.houses &gt; 0 &amp;&amp; (<br>          &lt;&gt;<br>            {Array.from({length: Math.min(property.houses, 4)}).map((_, idx) =&gt; {<br>              const spacing = 0.8; // Increased from 0.5 to 0.8 for more space between buildings<br>              const xOffset = (idx - (Math.min(property.houses, 4) - 1) / 2) * spacing;<br>              const zOffset = idx % 2 === 0 ? 0 : 0.4; // Increased from 0.3 to 0.4 for more depth variation<br>              const model = idx % 2 === 0 ? houseModel.clone() : houseModel4.clone();<br>              <br>              // Apply consistent scaling based on house count<br>              const baseScale = 0.03; // Further reduced from 0.15 to make buildings smaller<br>              let scaleVariation = 0;<br>              if (property.houses === 2) {<br>                scaleVariation = idx % 2 === 0 ? 0.02 : 0.01; // Smaller variation<br>              } else if (property.houses &gt; 2) {<br>                scaleVariation = idx * 0.003; // Smaller variation<br>              }<br>              const finalScale = baseScale + scaleVariation;<br>              model.scale.set(finalScale, finalScale, finalScale);<br>              <br>              return (<br>                &lt;primitive<br>                  key={`house-${i}-${idx}`}<br>                  object={model}<br>                  position={[xOffset, 0, zOffset]}<br>                  rotation={[0, Math.PI/2, 0]}<br>                /&gt;<br>              );<br>            })}<br>            {property.houses &gt;= 5 &amp;&amp; (<br>              &lt;primitive<br>                object={hotelModel.clone()}<br>                position={[0, 0, 0]}<br>                rotation={[0, Math.PI/2, 0]}<br>                scale={[0.001, 0.001, 0.001]}<br>              /&gt;<br>            )}<br>          &lt;/&gt;<br>        )}<br>      &lt;/group&gt;<br>    );<br>  }<br><br>  // Add center board logo - removed font property to avoid loading error<br>  const centerContent = (<br>    &lt;group position={[0, 0.1, 0]}&gt;<br>      &lt;Text<br>        position={[0, 0, 0]}<br>        rotation={[-Math.PI / 2, 0, 0]}<br>        fontSize={1.5}<br>        color=&quot;#FF0000&quot;<br>        anchorX=&quot;center&quot;<br>        anchorY=&quot;middle&quot;<br>      &gt;<br>        DOMINOPOLY<br>      &lt;/Text&gt;<br>    &lt;/group&gt;<br>  );<br><br>  // Create player tokens - use memoization to prevent recreation on every render<br>  const playerTokens = React.useMemo(() =&gt; {<br>    return players.map((player, index) =&gt; {<br>      const position = player.position;<br>      let x = 0, z = 0;<br>      const cornerOffset = boardSize / 2 - spaceSize / 2;<br>      if (position &lt; 10) { <br>        if (position === 0) { x = cornerOffset; z = cornerOffset; } <br>        else { x = cornerOffset - position * spaceSize - 1.1; z = cornerOffset - 0.85; }<br>      }<br>      else if (position &lt; 20) { <br>        if (position === 10) { x = -cornerOffset; z = cornerOffset; }<br>        else { x = -cornerOffset + spaceSize - 1; z = cornerOffset - (position - 10) * spaceSize - 1.1; }<br>      }<br>      else if (position &lt; 30) { <br>        if (position === 20) { x = -cornerOffset; z = -cornerOffset; }<br>        else { x = -cornerOffset + (position - 20) * spaceSize + 1.1; z = -cornerOffset + 0.85; }<br>      }<br>      else { <br>        if (position === 30) { x = cornerOffset; z = -cornerOffset; }<br>        else { x = cornerOffset - 0.85; z = -cornerOffset + (position - 30) * spaceSize + 1.1; }<br>      }<br>      <br>      // Adjust vertical position slightly for the model base<br>      const yPos = 0.1; <br><br>      // Calculate offset for players on the same space to avoid collision<br>      const playersOnSameSpace = players.filter(p =&gt; p.position === position);<br>      const numPlayersOnSpace = playersOnSameSpace.length;<br>      const playerIndexOnSpace = playersOnSameSpace.findIndex(p =&gt; p.id === player.id);<br><br>      let offsetX = 0;<br>      let offsetZ = 0;<br>      if (numPlayersOnSpace &gt; 1) {<br>          const offsetRadius = 0.4; // Radius of the circle around the space center<br>          const angleStep = (2 * Math.PI) / numPlayersOnSpace; // Angle between players<br>          const angle = playerIndexOnSpace * angleStep;<br>          <br>          offsetX = Math.cos(angle) * offsetRadius;<br>          offsetZ = Math.sin(angle) * offsetRadius;<br>      }<br>      <br>      x += offsetX;<br>      z += offsetZ;<br><br>      // Ensure player and character exist before trying to access model<br>      if (!player || !player.character) {<br>        console.warn(`Player or character data missing for index ${index}`);<br>        return null; // Skip rendering if data is incomplete<br>      }<br><br>      // Calculate base rotation to face inward (opposite of board side rotation)<br>      let baseRotation = 0;<br>      if (position &lt; 10) baseRotation = Math.PI;<br>      else if (position &lt; 20) baseRotation = Math.PI/2;<br>      else if (position &lt; 30) baseRotation = 0;<br>      else baseRotation = -Math.PI/2;<br>      <br>      // Add 45 degrees for corner positions<br>      const isCorner = position % 10 === 0;<br>      const cornerRotation = isCorner ? Math.PI/4 : 0;<br>      <br>      return (<br>        &lt;group key={`player-${player.id}`} position={[x, yPos, z]} rotation={[0, baseRotation + cornerRotation, 0]}&gt;<br>          &lt;PlayerToken <br>            modelPath={`/assets/3d/Players/${player.character.model}`}<br>            color={player.color}<br>            isCurrent={currentPlayer === index}<br>          /&gt;<br>          {currentPlayer === index &amp;&amp; (<br>            &lt;group position={[0, 1.5, 0]}&gt;<br>              &lt;RotatingIndicator /&gt;<br>            &lt;/group&gt;<br>          )}<br>        &lt;/group&gt;<br>      );<br>    });<br>  }, [players, currentPlayer, boardSize, spaceSize]); // Dependencies remain the same<br>  <br>  return (<br>    &lt;group ref={boardRef}&gt;<br>      {/* Board base - use stable reference to texture */}<br>      &lt;mesh position={[0, -0.1, 0]} receiveShadow&gt;<br>        &lt;boxGeometry args={[boardSize, 0.1, boardSize]} /&gt;<br>        &lt;meshStandardMaterial color=&quot;#E6DDC6&quot; map={boardTexture} /&gt;<br>      &lt;/mesh&gt;<br>      <br>      {/* Board inner area with lighter color */}<br>      &lt;mesh position={[0, -0.05, 0]} receiveShadow&gt;<br>        &lt;boxGeometry args={[boardSize - spaceSize * 3.5, 0.1, boardSize - spaceSize * 3.5]} /&gt;<br>        &lt;meshStandardMaterial color=&quot;#E6DDC6&quot; /&gt;<br>      &lt;/mesh&gt;<br><br>      {centerContent}<br>      {boardSpaces}<br>      {playerTokens}<br>    &lt;/group&gt;<br>  );<br>};<br><br>const GameBoard: React.FC&lt;GameBoardProps&gt; = ({<br>  gameState,<br>  onRollDice,<br>  onEndTurn,<br>  onBuyProperty,<br>  onMovePlayer,<br>  onUpdateMoney,<br>  onUpdateJailStatus,<br>  onJailCard // Rename destructured prop here<br>}) =&gt; {<br>  const [diceValues, setDiceValues] = useState&lt;[number, number]&gt;([1, 1]);<br>  const [diceRolling, setDiceRolling] = useState(false);<br>  const [propertyForAction, setPropertyForAction] = useState&lt;Property | null&gt;(null);<br>  const [viewedProperty, setViewedProperty] = useState&lt;Property | null&gt;(null);<br><br>  const currentPlayerIndex = gameState.currentPlayer;<br>  const currentPlayer = gameState.players[currentPlayerIndex];<br>  const isBot = currentPlayer?.type === &#39;bot&#39;;<br>  const isMyTurn = currentPlayer &amp;&amp; !isBot &amp;&amp; currentPlayer.id === PeerService.getCurrentPeerId();<br>  <br>  useEffect(() =&gt; {<br>    // Only check for new actions if we don&#39;t already have one pending<br>    if (currentPlayer &amp;&amp; !propertyForAction) {<br>      const propertyAtPosition = gameState.properties.find(<br>        p =&gt; p.position === currentPlayer.position<br>      );<br>      <br>      // Skip if we&#39;re not on a property or it&#39;s not our turn<br>      if (!propertyAtPosition || !gameState.hasDiceRolled || isBot || <br>          currentPlayer.id !== PeerService.getCurrentPeerId()) {<br>        return;<br>      }<br><br>      const isSpecialCard = propertyAtPosition.type === &#39;surprise&#39; || propertyAtPosition.type === &#39;box&#39;;<br>      const isCorner = propertyAtPosition.position === 10 || propertyAtPosition.position === 20 || propertyAtPosition.position === 30 || propertyAtPosition.position === 40 || propertyAtPosition.position === 0;<br>      const isBuyable = !isCorner &amp;&amp; !isSpecialCard &amp;&amp; !propertyAtPosition.owner &amp;&amp; (propertyAtPosition.price !== undefined);<br>      <br>      if (isSpecialCard) {<br>        try {<br>          const stackType = propertyAtPosition.type === &#39;surprise&#39; ? &#39;surprise&#39; : &#39;box&#39;;<br>          const cardStack = gameState.cardStacks?.[stackType] ?? [];<br>          <br>          if (cardStack.length === 0) {<br>            console.warn(&#39;Empty card stack:&#39;, stackType);<br>            setPropertyForAction({<br>              ...propertyAtPosition,<br>              drawnCard: {<br>                id: &#39;default&#39;,<br>                type: stackType,<br>                title: &#39;No Cards Available&#39;,<br>                description: &#39;This card stack is empty&#39;,<br>                effect: {<br>                  type: &#39;money&#39;,<br>                  value: 0,<br>                  description: &#39;No effect&#39;<br>                }<br>              }<br>            });<br>            return;<br>          }<br>        } catch (error) {<br>          console.error(&#39;Error drawing card:&#39;, error);<br>          setPropertyForAction(null);<br>        }<br>      } else {<br>        setPropertyForAction(isBuyable ? propertyAtPosition : null);<br>      }<br>    }<br>  }, [currentPlayer, gameState.properties, gameState.hasDiceRolled, isBot]);<br><br>  const handleRollDice = () =&gt; {<br>    setDiceRolling(true);<br>    let rollCount = 0;<br>    let latestDiceValues: [number, number] = [0, 0];<br>    const rollInterval = setInterval(() =&gt; {<br>      latestDiceValues = [Math.floor(Math.random() * 6) + 1, Math.floor(Math.random() * 6) + 1];<br>      setDiceValues(latestDiceValues);<br>      if (++rollCount === 4) {<br>        clearInterval(rollInterval);<br>        setDiceRolling(false);<br>        onRollDice(latestDiceValues);<br>      }<br>    }, 100);<br>  };<br><br>  const handleSpaceClick = useCallback((property: Property | null, position: number) =&gt; {<br>    if (property) {<br>      setViewedProperty(property);<br>    }<br>  }, []);<br><br>  return (<br>    &lt;div className=&quot;flex flex-col h-screen&quot;&gt;<br>      &lt;div className=&quot;flex-1 relative&quot;&gt;<br>        &lt;Canvas camera={{ position: [0, 30, 0], rotation: [0, Math.PI, 0], fov: 50, near: 0.1, far: 2000 }}&gt;<br>          &lt;ambientLight intensity={1.5} /&gt;<br>          &lt;Board <br>            properties={gameState.properties as Property[]}<br>            players={gameState.players}<br>            currentPlayer={currentPlayerIndex}<br>            onSpaceClick={handleSpaceClick}<br>          /&gt;<br>          &lt;OrbitControls enablePan enableZoom enableRotate minPolarAngle={0} maxPolarAngle={Math.PI / 2.5} /&gt;<br>        &lt;/Canvas&gt;<br><br>        {/* Player Info Panel */}<br>        &lt;div className=&quot;absolute top-4 right-4 space-y-2 max-h-[80vh] overflow-y-auto&quot;&gt;<br>          {gameState.players.map((player, index) =&gt; (<br>            &lt;PlayerInfo <br>              key={player.id} <br>              player={player} <br>              isCurrentTurn={index === currentPlayerIndex}<br>              properties={gameState.properties}<br>            /&gt;<br>          ))}<br>        &lt;/div&gt;<br><br>        {/* Dice Controls */}<br>        &lt;div className=&quot;absolute bottom-4 left-4 flex gap-4&quot;&gt;<br>          &lt;Card className=&quot;w-fit shadow-lg&quot;&gt;<br>            &lt;CardContent className=&quot;p-4&quot;&gt;<br>              &lt;div className=&quot;flex items-center gap-4&quot;&gt;<br>                &lt;div className=&quot;grid grid-cols-2 gap-2&quot;&gt;<br>                  {diceValues.map((value, index) =&gt; (<br>                    &lt;div key={index} className={`w-12 h-12 bg-white rounded-lg border border-game-primary shadow flex items-center justify-center text-2xl font-bold ${diceRolling ? &#39;animate-dice-roll&#39; : &#39;&#39;}`}&gt;<br>                      {value}<br>                    &lt;/div&gt;<br>                  ))}<br>                &lt;/div&gt;<br>                &lt;div className=&quot;space-y-2&quot;&gt;<br>                  &lt;Button<br>                    onClick={handleRollDice}<br>                    disabled={!isMyTurn || diceRolling || gameState.hasDiceRolled || isBot}<br>                    className=&quot;bg-game-primary hover:bg-game-primary/90 flex items-center gap-2&quot;<br>                  &gt;<br>                    &lt;Dices size={16} /&gt; Roll Dice<br>                  &lt;/Button&gt;<br>                  &lt;Button<br>                    onClick={onEndTurn}<br>                    disabled={!isMyTurn || !gameState.hasDiceRolled || isBot}<br>                    variant=&quot;outline&quot;<br>                    className=&quot;w-full border-game-primary/30&quot;<br>                  &gt;<br>                    End Turn<br>                  &lt;/Button&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/CardContent&gt;<br>          &lt;/Card&gt;<br>        &lt;/div&gt;<br><br>        {/* Property Action Card (for buying/special cards) */}<br>        {propertyForAction &amp;&amp; currentPlayer &amp;&amp; isMyTurn &amp;&amp; (<br>          &lt;PropertyActionCard <br>            property={propertyForAction}<br>            playerMoney={currentPlayer.money}<br>            onBuy={() =&gt; {<br>              onBuyProperty(propertyForAction.id);<br>              setPropertyForAction(null);<br>            }}<br>            onPass={() =&gt; setPropertyForAction(null)}<br>            onAcceptCard={() =&gt; {<br>              if (!propertyForAction?.drawnCard) {<br>                console.error(&#39;No drawn card found&#39;);<br>                return;<br>              }<br>              <br>              try {<br>                handleCardEffect(<br>                  propertyForAction.drawnCard,<br>                  currentPlayer,<br>                  (effect: CardEffectAction) =&gt; {<br>                    if (!effect) {<br>                      console.error(&#39;No effect provided&#39;);<br>                      return;<br>                    }<br>                    <br>                    switch(effect.type) {<br>                      case &#39;move&#39;:<br>                        if (effect.position === undefined) {<br>                          console.error(&#39;Missing position for move effect&#39;);<br>                          return;<br>                        }<br>                        onMovePlayer(effect.playerId, effect.position);<br>                        break;<br>                      case &#39;money&#39;:<br>                        if (effect.amount === undefined) {<br>                          console.error(&#39;Missing amount for money effect&#39;);<br>                          return;<br>                        }<br>                        onUpdateMoney(effect.playerId, effect.amount);<br>                        break;<br>                      case &#39;jail&#39;:<br>                        if (effect.jailed === undefined) {<br>                          console.error(&#39;Missing jailed status for jail effect&#39;);<br>                          return;<br>                        }<br>                        onUpdateJailStatus(effect.playerId, effect.jailed);<br>                        break;<br>                      case &#39;get_out_of_jail&#39;:<br>                        onJailCard(effect.playerId); // Rename function call<br>                        break;<br>                      default:<br>                        console.error(&#39;Unknown effect type:&#39;, effect);<br>                        return;<br>                    }<br>                    setPropertyForAction(null);<br>                  }<br>                );<br>              } catch (error) {<br>                console.error(&#39;Error processing card effect:&#39;, error);<br>              }<br>            }}<br>            open={!!propertyForAction}<br>            showActions={true}<br>          /&gt;<br>        )}<br><br>        {/* Property View Card (for viewing) */}<br>        {viewedProperty &amp;&amp; (<br>          &lt;PropertyActionCard<br>            property={viewedProperty}<br>            playerMoney={currentPlayer?.money || 0}<br>            onBuy={() =&gt; {}}<br>            onPass={() =&gt; setViewedProperty(null)}<br>            open={!!viewedProperty}<br>            showActions={false}<br>            isCardView={true}<br>          /&gt;<br>        )}<br><br>        {/* Current Player Info */}<br>        &lt;div className=&quot;absolute top-4 left-4 space-y-2&quot;&gt;<br>          &lt;Badge className=&quot;px-3 py-1 text-md bg-game-primary text-white&quot;&gt;<br>            &lt;div className=&quot;flex items-center gap-2&quot;&gt;<br>              &lt;div className=&quot;w-3 h-3 rounded-full&quot; style={{ backgroundColor: currentPlayer?.color }} /&gt;<br>              {isBot &amp;&amp; &lt;Bot size={14} /&gt;}<br>              {currentPlayer?.name}&#39;s Turn<br>            &lt;/div&gt;<br>          &lt;/Badge&gt;<br>          &lt;div className=&quot;flex items-center gap-1 bg-white/80 px-3 py-1 rounded-full text-sm&quot;&gt;<br>            &lt;CircleDollarSign size={14} className=&quot;text-game-primary&quot; /&gt;<br>            &lt;span&gt;${currentPlayer?.money}&lt;/span&gt;<br>          &lt;/div&gt;<br>          {isBot &amp;&amp; gameState.hasDiceRolled &amp;&amp; (<br>            &lt;div className=&quot;bg-black/70 text-white px-3 py-1 rounded-full text-sm animate-pulse&quot;&gt;<br>              Bot is thinking...<br>            &lt;/div&gt;<br>          )}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default GameBoard;</pre><p>As what you can see from this huge piece of code, we have a GameBoard component that handles a lot of stuff: game mechanics, player’s position, game state, etc. Even though we have a lot of logic on this single component, that surely can be splitted into multiple small ones, we have a lot of other components that manage other part of the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*yraqFD5hXPuFTSpDkj-DdQ.png" /><figcaption>File Structure</figcaption></figure><p>This is just to give you an idea of the complexity of this project. This being a game with a lot rules and logic to handle, it requires a lot of different parts to make it work as intended.</p><p>After refactoring and improving the generated code to make sure we have all our logic and behaviors in place, using mostly JS knowledge, Stackoverflow and google, and of course when useful Cline, the end result is actually not that bad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aY5mpOtAHU82B-vaw8Zp3g.png" /><figcaption>Game Board</figcaption></figure><p>I ended up with a nice canva with all the pieces necessary to build the game, we finally have our baseline ready. Which allowed me to focus a bit on the 3d objects elements of the game.</p><h3>Game Objects 🎮</h3><p>Another part the AI failed was handeling the 3d objects of the game. First of all, the main problem resided on how players moved around the board. They didn’t change direction correctly, sometimes they just miss the corners, and the steps were all mess up.</p><p>I spent the rest of the day, about 3 hours, working on fixing and improving this acpect of the game. I worked on the correct implementation for the player’s position tracking and direction. With a few tweeks here and there, I was able to fix the movements of the players.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*NiWUWV_pl4Adl4wFC1zHmg.png" /></figure><h3>Buy / Dismiss / Rent Mechanics 🏦</h3><p>Another piece of logic that I had to change quite a bit for the game was the Buy / Dismiss / Pay Rent Mechanics of the game. It was bad coded and broken, I had to step in and solve a bunch of logic wrongly implemented (it wasn’t bad code, it was just wrongly implemented).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*yeRplj3MVu7RwehhpbEUJQ.png" /><figcaption>Buy property</figcaption></figure><h3>Dice Mechanics 🎲</h3><p>Here too the AI didn’t accomplished what it was tasked to do, but I was able to fix it without too much effort. The dice was updating late, wasn’t connected to the correct player, and didn’t manage well the turned based mechanics. At the end I was able to fix it and improve it a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*M3Ee7IVMEcPKawtc_sDHBw.png" /><figcaption>Dice</figcaption></figure><h3>To be continue!</h3><p>At this point I was pretty exhausted, but also happy for all the effort and results accomplished. In very little time I was able to have this game up and running, with 3d game mechanics and scores system. A lot of code was done, a lot fixes where made, a lot of effort was given.</p><p>That’s why I decided to stop here for the moment, and allow myself a bit of breading room before coming back to this project. I’ll continue this for sure. This project also gave me an idea for a “JS Game Engine” aiming the developer community. Stay tune for that!</p><h3>This is not the end of this project, it just the beginning!</h3><p>I’ll keep improving the game and blogging about it, if you wanna give it a try just go to <a href="https://dominopoli.netlify.app/">https://dominopoli.netlify.app/</a> 🌎 suggestions are welcome.</p><p><strong>Also, at some point I’ll open source it, stay tuned for that too!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baaecee5f71f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe Coding Adventures: Day 7 — ChatPeer]]></title>
            <link>https://medium.com/@enzovezzaro/vibe-coding-adventures-day-7-chatpeer-30486e0ebfd4?source=rss-a225e16db862------2</link>
            <guid isPermaLink="false">https://medium.com/p/30486e0ebfd4</guid>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[p2p]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[chat]]></category>
            <dc:creator><![CDATA[Enzo Junior Vezzaro]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 13:40:25 GMT</pubDate>
            <atom:updated>2025-03-28T13:40:25.504Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vibe Coding Adventures: Day 7 — ChatPeer</h3><p>Hello everyone, It’s me again with another cool project, another adventure, another Vibe Coding experiment 🏄🏽‍♂️</p><p><strong>What do we build today?</strong></p><p>Today I’ll be building another P2P app! It’s time to bring to live a private and secure communication platform with P2P capabilities and a touch of AI companionship ⚡️</p><h3>What’s ChatPeer all about?</h3><p>ChatPeer is a P2P, local fist, secure and open source platform for Web communication. I utilized the power of PeerJS to build a platform where users can communicate privately, browser to browser, share images, stream videos, audio, and screen, and users can also bring their favorate AI into their chat to make it more interactive and utilize the power of AI to improve our conversations.</p><p><strong>Let’s get into the weeds, shall we?</strong></p><p>As always the first step is getting the main prompt right, as much is posible. Let’s go to our favorite tool for this, ChatGPT; for about 30 minutes, I went back and forward with the AI to create and improve the main prompt, to then be able to use it on the next tool. This is the final result for this step:</p><pre>Prompt:  <br><br>Build a privacy-focused, AI-enhanced peer-to-peer communication app called ChatPeer. This is a web-only application (no mobile support) that operates entirely in the browser, with no backend servers.  <br><br>Core Features:  <br>1. Peer-to-Peer Communication:  <br>   - Use PeerJS for direct text messaging, audio calls, video calls, and screen sharing between users.  <br>   - Each user generates a unique peer ID upon opening the app.  <br><br>2. Local-Only Data Storage:  <br>   - Store user preferences, chat history, and settings in LocalStorage to maintain full privacy (no external databases or cloud storage).  <br>   - Reloading the app does not reset conversations, as long as LocalStorage is available.  <br><br>3. AI-Powered Assistance:  <br>   - Integrate AI models from OpenAI, Grok, Claude, and Groq via API calls.  <br>   - Provide context-aware suggestions, smart replies, and real-time conversation insights.  <br><br>4. Seamless User Experience:  <br>   - No authentication/login required-users connect via peer IDs.  <br>   - Modern, responsive UI optimized for desktop browsers only.  <br>   - Allow users to copy/share their peer ID for easy connections.  <br><br>5. Security &amp; Privacy:  <br>   - All communications happen directly between peers, avoiding centralized servers.  <br>   - Since no backend is used, messages are not stored anywhere outside of LocalStorage.  <br><br>Development Requirements:  <br>- Frontend: Build using React + TypeScript (or another modern framework).  <br>- Peer-to-Peer Logic: Implement with PeerJS.  <br>- AI API Integration: Use API calls to OpenAI, Grok, Claude, and Groq for AI-powered chat features.  <br>- State Management: Preferably use React hooks and LocalStorage instead of external state libraries.  <br><br>User Flow:  <br>1. User opens the web app and is assigned a unique peer ID.  <br>2. They can share this ID to connect with another user.  <br>3. Once connected, users can chat, make audio/video calls, and share screens via PeerJS.  <br>4. AI-powered features provide real-time suggestions and insights in conversations.  <br><br>Ensure the UI is sleek, minimalistic, and intuitive to make ChatPeer feel modern and user-friendly. No account creation, no servers-just instant, secure, AI-powered communication.</pre><p>It’s all about privacy, it’s about real p2p communication.</p><h3>It’s AI time! 🤖</h3><p>Now that we have our prompt, let’s start building!</p><p>First of all since this was a pretty interesting and much complicated project than before, I decided to test this prompt on the biggest platforms for AI code generation right now:</p><p>✅ <a href="https://v0.dev/">v0.dev</a></p><p>✅ <a href="https://lovable.dev/">Lovable.dev</a></p><p>✅ <a href="https://bolt.new/">Bolt.new</a></p><p>After about 2 hours of prompting with these tool I encounter many issues with all of 3 platforms. First of all, I found that AI is not really that good when it comes to less known solutions like p2p. Most of the tries I did ended up with a not functional app that required a lot of fixing to be able to use it. Not only that, the AI pretty much didn’t know how to structure this app in a way that is actually manageable by a programmer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDlfy0r9E3GYe2KXTF6uYw.png" /><figcaption>Bolt.new — pretty dissapointing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_cYzk2DXRZ-RGvdJJ9R7w.png" /><figcaption>v0.dev — naild it on the functionalities, but the design was terrible</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GIGw5S8gt9wYSk6Xi9wG-Q.png" /><figcaption>Lovable.dev — as always Lovable wins, with functionality and minimal design</figcaption></figure><p>As you can see from the results, we had different results based on the service used. The worse of all was Bolt.new, it managed to build “something”, but it was really really uggly, and it didn’t work at all. At the second place we have v0.dev, which managed to make a better job with the functionalities. It has pretty much all I asked for, but the UI was really terrible. The last was Lovable.dev, I always end up choosing this platform for the projects of our Vibe Coding adventures as they always provide a functional app with a dicent UI that we can work with. It’s not the best in the world, but at least I don’t have to start from scratch completely.</p><p>Now that we have our base project, we can get involved.</p><h3>It’s time for the Human! 👨🏽‍💻</h3><p>Now that the AI has done its part, it’s time to start coding! Let’s make this project usable, beatiful, and helpful.</p><p>At this point I had all the functionalities needed in place, but the UX was all over the place. I spent the next 6–8 hours changing the code, improving the UX / UI, fixing AI coding errors, and of course cleanup a bit the code. This was done half AI with <a href="https://cline.bot/">Cline</a>, half me coding my way through.</p><p>I don’t wanna to bother you with a bunch of code, you can take a look at the repo, but let’s just see together this little piece of logic:</p><pre>import { useState, useEffect, useCallback, useRef } from &#39;react&#39;;<br>import Peer, { DataConnection } from &#39;peerjs&#39;;<br>import { toast } from &#39;sonner&#39;;<br>import { ConnectionStatus, Message, User, Channel, Server } from &#39;@/types/types&#39;;<br><br>type UsePeerConnectionProps = {<br>  userId: string;<br>  username: string;<br>};<br><br>type PeerMessage =<br>  | { type: &#39;message&#39;; payload: Message &amp; { channelId?: string } }<br>  | { type: &#39;user-info&#39;; payload: User }<br>  | { type: &#39;typing&#39;; payload: { userId: string; isTyping: boolean } }<br>  | { type: &#39;read&#39;; payload: { messageId: string } }<br>  | { type: &#39;channel&#39;; payload: Channel[] }<br>  | { type: &#39;server&#39;; payload: Server[] }<br>  | { type: &#39;media-offer&#39;; payload: { sdp: string; type: &#39;offer&#39; } }<br>  | { type: &#39;media-answer&#39;; payload: { sdp: string; type: &#39;answer&#39; } }<br>  | { type: &#39;media-end&#39;; payload: { userId: string } };<br><br>type PersonalChats = { [peerId: string]: Message[] };<br><br>const usePeerConnection = ({ userId, username }: UsePeerConnectionProps) =&gt; {<br>  const [status, setStatus] = useState&lt;ConnectionStatus&gt;(&#39;disconnected&#39;);<br>  const [users, setUsers] = useState&lt;User[]&gt;([]);<br>  const [messages, setMessages] = useState&lt;Message[]&gt;([]);<br>  const [personalChats, setPersonalChats] = useState&lt;PersonalChats&gt;({});<br>  const [channels, setChannels] = useState&lt;Channel[]&gt;([]);<br>  const [servers, setServers] = useState&lt;Server[]&gt;([]);<br>  const [currentChannelId, setCurrentChannelId] = useState&lt;string | null&gt;(null);<br>  const [currentServerId, setCurrentServerId] = useState&lt;string | null&gt;(null);<br>  const [connectedPeers, setConnectedPeers] = useState&lt;string[]&gt;([]);<br>  const [isAudioEnabled, setIsAudioEnabled] = useState&lt;boolean&gt;(false);<br>  const [isVideoEnabled, setIsVideoEnabled] = useState&lt;boolean&gt;(false);<br>  const [isScreenSharing, setIsScreenSharing] = useState&lt;boolean&gt;(false);<br>  const [userStreams, setUserStreams] = useState&lt;{[userId: string]: MediaStream}&gt;({});<br>  const [isTyping, setIsTyping] = useState&lt;boolean&gt;(false);<br>  const [typingTimeout, setTypingTimeout] = useState&lt;NodeJS.Timeout | null&gt;(null);<br><br>  const peerRef = useRef&lt;Peer | null&gt;(null);<br>  const connectionsRef = useRef&lt;Record&lt;string, DataConnection&gt;&gt;({});<br>  const localStreamRef = useRef&lt;MediaStream | null&gt;(null);<br>  const screenStreamRef = useRef&lt;MediaStream | null&gt;(null);<br><br>  // Initialize with stored data<br>  useEffect(() =&gt; {<br>    const storedData = localStorage.getItem(&#39;chatData&#39;);<br>    if (storedData) {<br>      try {<br>        const { users, messages, channels } = JSON.parse(storedData);<br>        <br>        // Set initial state with stored data<br>        setUsers(users || []);<br>        setMessages(messages || []);<br>        <br>        // If we have channels, use them<br>        if (channels?.length) {<br>          setChannels(channels);<br>          setCurrentChannelId(channels[0]?.id || null);<br>        } else {<br>          // Otherwise create default channel<br>          const defaultChannels: Channel[] = [<br>            {<br>              id: &#39;general&#39;,<br>              name: &#39;general&#39;,<br>              description: &#39;General discussion&#39;,<br>              isPrivate: true,<br>              type: &#39;text&#39;,<br>              members: [],<br>              messages: []<br>            },<br>          ];<br>          setChannels(defaultChannels);<br>          setCurrentChannelId(&#39;general&#39;);<br>        }<br>      } catch (error) {<br>        console.error(&#39;Error parsing stored chat data:&#39;, error);<br>      }<br>    } else {<br>      // No stored data, create default channel<br>      const defaultChannels: Channel[] = [<br>        {<br>          id: &#39;general&#39;,<br>          name: &#39;general&#39;,<br>          description: &#39;General discussion&#39;,<br>          isPrivate: true,<br>          type: &#39;text&#39;,<br>          members: [],<br>          messages: []<br>        },<br>      ];<br>      setChannels(defaultChannels);<br>      setCurrentChannelId(&#39;general&#39;);<br>    }<br>  }, []);<br><br>  // Initialize peer connection after state is initialized<br>  useEffect(() =&gt; {<br>    if (!userId || !channels.length) return;<br><br>    const initPeer = async () =&gt; {<br>      setStatus(&#39;connecting&#39;);<br>      <br>      try {<br>        const peer = new Peer(userId, {<br>          debug: 2,<br>        });<br><br>        peer.on(&#39;open&#39;, (id) =&gt; {<br>          console.log(&#39;My peer ID is: &#39; + id);<br>          setStatus(&#39;connected&#39;);<br>          <br>          // Add self to users list<br>          setUsers((prev) =&gt; [<br>            ...prev.filter(u =&gt; u.id !== userId),<br>            { id: userId, name: username, status: &#39;online&#39; }<br>          ]);<br>          <br>          toast.success(&#39;Connected to server&#39;);<br>        });<br><br>        peer.on(&#39;connection&#39;, (conn) =&gt; {<br>          setupConnection(conn);<br>        });<br><br>        peer.on(&#39;call&#39;, (call) =&gt; {<br>          // Answer incoming calls with local stream if available<br>          if (localStreamRef.current) {<br>            call.answer(localStreamRef.current);<br>          } else {<br>            // Try to get media if not available<br>            navigator.mediaDevices.getUserMedia({ video: true, audio: true })<br>              .then(stream =&gt; {<br>                localStreamRef.current = stream;<br>                call.answer(stream);<br>              })<br>              .catch(() =&gt; call.answer());<br>          }<br>          <br>          call.on(&#39;stream&#39;, (remoteStream) =&gt; {<br>            console.log(&#39;Received remote stream from&#39;, call.peer);<br>            setUserStreams(prev =&gt; ({<br>              ...prev,<br>              [call.peer]: remoteStream<br>            }));<br>          });<br><br>          call.on(&#39;close&#39;, () =&gt; {<br>            console.log(&#39;Call ended with&#39;, call.peer);<br>            setUserStreams(prev =&gt; {<br>              const newStreams = {...prev};<br>              delete newStreams[call.peer];<br>              return newStreams;<br>            });<br>          });<br>        });<br><br>        peer.on(&#39;error&#39;, (err) =&gt; {<br>          console.error(&#39;Peer connection error:&#39;, err);<br>          toast.error(`Connection error: ${err.message}`);<br>          setStatus(&#39;disconnected&#39;);<br>        });<br><br>        peer.on(&#39;disconnected&#39;, () =&gt; {<br>          console.log(&#39;Peer disconnected&#39;);<br>          setStatus(&#39;disconnected&#39;);<br>          toast.error(&#39;Disconnected from server&#39;);<br>        });<br><br>        peerRef.current = peer;<br>      } catch (error) {<br>        console.error(&#39;Failed to create peer:&#39;, error);<br>        setStatus(&#39;disconnected&#39;);<br>        toast.error(&#39;Failed to connect&#39;);<br>      }<br>    };<br><br>    initPeer();<br><br>    return () =&gt; {<br>      if (peerRef.current) {<br>        peerRef.current.destroy();<br>      }<br>      <br>      if (localStreamRef.current) {<br>        localStreamRef.current.getTracks().forEach(track =&gt; track.stop());<br>      }<br>      <br>      if (screenStreamRef.current) {<br>        screenStreamRef.current.getTracks().forEach(track =&gt; track.stop());<br>      }<br>    };<br>  }, [userId, username]);<br><br>  // Set up connection handlers<br>  const setupConnection = useCallback((conn: DataConnection) =&gt; {<br>    const peerId = conn.peer;<br>    <br>    conn.on(&#39;open&#39;, () =&gt; {<br>      console.log(&#39;Connection established with&#39;, peerId);<br>      <br>      // Store the connection<br>      connectionsRef.current[peerId] = conn;<br>      setConnectedPeers((prev) =&gt; [...new Set([...prev, peerId])]);<br>      <br>      // Send user info<br>      sendToPeer(peerId, {<br>        type: &#39;user-info&#39;,<br>        payload: {<br>          id: userId,<br>          name: username,<br>          status: &#39;online&#39;<br>        }<br>      });<br>      <br>      // Send channel list<br>      if (channels.length &gt; 0) {<br>        sendToPeer(peerId, {<br>          type: &#39;channel&#39;,<br>          payload: channels<br>        });<br>      }<br>      <br>      // Send server list<br>      if (servers.length &gt; 0) {<br>        sendToPeer(peerId, {<br>          type: &#39;server&#39;,<br>          payload: servers<br>        });<br>      }<br>    });<br><br>    conn.on(&#39;data&#39;, (data: PeerMessage) =&gt; {<br>      console.log(&#39;Received data:&#39;, data);<br>      <br>      switch (data.type) {<br>        case &#39;message&#39;: {<br>          const messageData = data.payload as Message &amp; { channelId?: string };<br>          setMessages((prev) =&gt; [...prev, messageData]);<br>          // Update channel messages<br>          setChannels(prev =&gt; prev.map(channel =&gt; {<br>            if (channel.id === messageData.channelId) {<br>              return {<br>                ...channel,<br>                messages: [...channel.messages, messageData]<br>              };<br>            }<br>            return channel;<br>          }));<br>          break;<br>        }<br>        case &#39;user-info&#39;: {<br>          const userData = data.payload as User;<br>          setUsers((prev) =&gt; [<br>            ...prev.filter(u =&gt; u.id !== userData.id),<br>            userData<br>          ]);<br>          break;<br>        }<br>          <br>        case &#39;typing&#39;: {<br>          const typingData = data.payload as { userId: string; isTyping: boolean };<br>          setUsers(prev =&gt; prev.map(user =&gt; {<br>            if (user.id === typingData.userId) {<br>              return { ...user, isTyping: typingData.isTyping };<br>            }<br>            return user;<br>          }));<br>          break;<br>        }<br>          <br>        case &#39;channel&#39;: {<br>          const channelData = data.payload as Channel[];<br>          setChannels(prev =&gt; {<br>            // Merge with existing channels<br>            const existingIds = new Set(prev.map(c =&gt; c.id));<br>            const newChannels = channelData.filter(c =&gt; !existingIds.has(c.id));<br>            return [...prev, ...newChannels];<br>          });<br>          console.log(&#39;here: channel receive: &#39;, channels, channelData);<br>          <br>          break;<br>        }<br>          <br>        case &#39;server&#39;: {<br>          const serverData = data.payload as Server[];<br>          setServers(prev =&gt; {<br>            // Merge with existing servers<br>            const existingIds = new Set(prev.map(s =&gt; s.id));<br>            const newServers = serverData.filter(s =&gt; !existingIds.has(s.id));<br>            return [...prev, ...newServers];<br>          });<br>          break;<br>        }<br>          <br>        case &#39;media-offer&#39;: {<br>          // Handle media offer (for future implementation)<br>          break;<br>        }<br>          <br>        case &#39;media-answer&#39;: {<br>          // Handle media answer (for future implementation)<br>          break;<br>        }<br>          <br>        case &#39;media-end&#39;: {<br>          // Handle media end (for future implementation)<br>          break;<br>        }<br>      }<br>    });<br><br>    conn.on(&#39;close&#39;, () =&gt; {<br>      console.log(&#39;Connection closed with&#39;, peerId);<br>      <br>      // Remove the connection<br>      delete connectionsRef.current[peerId];<br>      setConnectedPeers((prev) =&gt; prev.filter(id =&gt; id !== peerId));<br>      <br>      // Update user status<br>      setUsers((prev) =&gt; <br>        prev.map(user =&gt; <br>          user.id === peerId <br>            ? { ...user, status: &#39;offline&#39; } <br>            : user<br>        )<br>      );<br>    });<br><br>    conn.on(&#39;error&#39;, (err) =&gt; {<br>      console.error(&#39;Connection error:&#39;, err);<br>      toast.error(`Connection error with peer: ${err}`);<br>    });<br>  }, [userId, username, channels, currentChannelId, servers]);<br><br>  // Connect to a peer<br>  const connectToPeer = useCallback(async (peerId: string, channelId: string | null) =&gt; {<br>    if (!peerRef.current || peerId === userId) return;<br><br>    // Don&#39;t reconnect if already connected<br>    if (connectionsRef.current[peerId]) return;<br><br>    try {<br>      const conn = peerRef.current.connect(peerId);<br>      setupConnection(conn);<br>      toast.success(`Connecting to ${peerId}...`);<br><br>      // Ensure we have media before initiating call<br>      if (!localStreamRef.current &amp;&amp; isVideoEnabled) {<br>        try {<br>          const stream = await navigator.mediaDevices.getUserMedia({ <br>            video: true, <br>            audio: isAudioEnabled <br>          });<br>          localStreamRef.current = stream;<br>        } catch (error) {<br>          console.error(&#39;Failed to get media:&#39;, error);<br>        }<br>      }<br><br>      // Initiate call if we have a local stream<br>      if (localStreamRef.current) {<br>        const call = peerRef.current.call(peerId, localStreamRef.current);<br>        call.on(&#39;stream&#39;, (remoteStream) =&gt; {<br>          console.log(&#39;Received remote stream from&#39;, peerId);<br>          setUserStreams(prev =&gt; ({<br>            ...prev,<br>            [peerId]: remoteStream<br>          }));<br>        });<br>        <br>        call.on(&#39;close&#39;, () =&gt; {<br>          console.log(&#39;Call ended with&#39;, peerId);<br>          setUserStreams(prev =&gt; {<br>            const newStreams = {...prev};<br>            delete newStreams[peerId];<br>            return newStreams;<br>          });<br>        });<br>      }<br>    } catch (error) {<br>      console.error(&#39;Failed to connect to peer:&#39;, error);<br>      toast.error(`Failed to connect to ${peerId}`);<br>    }<br>  }, [userId, setupConnection, isVideoEnabled, isAudioEnabled]);<br><br>  // Send data to a specific peer<br>  const sendToPeer = useCallback((peerId: string, data: PeerMessage) =&gt; {<br>    const conn = connectionsRef.current[peerId];<br>    if (conn &amp;&amp; conn.open) {<br>      conn.send(data);<br>      return true;<br>    }<br>    return false;<br>  }, []);<br><br>  // Send data to all connected peers<br>  const broadcast = useCallback((data: PeerMessage, isPrivate: boolean = false) =&gt; {<br>    if (isPrivate) return;<br>    Object.values(connectionsRef.current).forEach(conn =&gt; {<br>      if (conn.open) {<br>        conn.send(data);<br>      }<br>    });<br>  }, []);<br><br>  // Update channel<br>  const updateChannelPrivacy = (privacy: boolean) =&gt; {<br>    setChannels(prev =&gt; {<br>      return prev.map(channel =&gt; {<br>        if (channel.id === currentChannelId) {<br>          return {<br>            ...channel,<br>            isPrivate: privacy<br>          };<br>        }<br>        return channel;<br>      });<br>    });<br>  };<br><br>  // Send a message<br>  const sendMessage = useCallback((content: string, type: &#39;text&#39; | &#39;image&#39; | &#39;audio&#39; | &#39;video&#39; = &#39;text&#39;, botId?: string) =&gt; {<br>    if ((!content.trim() &amp;&amp; type === &#39;text&#39;) || status !== &#39;connected&#39;) return;<br><br>    const message: Message = {<br>      id: `${botId || userId}-${Date.now()}`,<br>      content,<br>      senderId: botId || userId,<br>      timestamp: Date.now(),<br>      read: false,<br>      type<br>    };<br><br>    const currentChannel = channels.find((channel) =&gt; channel.id === currentChannelId);<br>    console.log(&#39;check message: &#39;, message);<br><br>    // Shared chat<br>    setMessages((prev) =&gt; [...prev, message]);<br><br>    setChannels(prev =&gt; {<br>      return prev.map(channel =&gt; {<br>        console.log(&#39;aqui 1: &#39;, channel.id, currentChannelId);<br>        if (channel.id === currentChannelId) {<br>          console.log(&#39;aqui 2&#39;);<br>          return {<br>            ...channel,<br>            messages: [...channel.messages, message]<br>          };<br>        }<br>        return channel;<br>      });<br>    });<br><br>    if (currentChannel &amp;&amp; !currentChannel.isPrivate) {<br>      broadcast({<br>        type: &#39;message&#39;,<br>        payload: {<br>          ...message,<br>          channelId: currentChannelId<br>        }<br>      });<br>    } else {<br>      // Send to all connected peers if the channel is private<br>      connectedPeers.forEach(peerId =&gt; {<br>        sendToPeer(peerId, {<br>          type: &#39;message&#39;,<br>          payload: {<br>            ...message,<br>            channelId: currentChannelId<br>          }<br>        });<br>      });<br>    }<br><br>    return message;<br>  }, [userId, status, broadcast, sendToPeer, currentChannelId, connectedPeers, channels]);<br><br>  // Update typing status<br>  const updateTypingStatus = useCallback((isUserTyping: boolean) =&gt; {<br>    if (isTyping === isUserTyping) return;<br>    <br>    setIsTyping(isUserTyping);<br>    <br>    // Send typing status to peers<br>    broadcast({<br>      type: &#39;typing&#39;,<br>      payload: { userId, isTyping: isUserTyping }<br>    });<br>    <br>    // Clear previous timeout<br>    if (typingTimeout) {<br>      clearTimeout(typingTimeout);<br>    }<br>    <br>    // Set timeout to clear typing status<br>    if (isUserTyping) {<br>      const timeout = setTimeout(() =&gt; {<br>        setIsTyping(false);<br>        broadcast({<br>          type: &#39;typing&#39;,<br>          payload: { userId, isTyping: false }<br>        });<br>      }, 3000);<br>      <br>      setTypingTimeout(timeout);<br>    }<br>  }, [isTyping, typingTimeout, broadcast, userId]);<br><br>  // Toggle audio<br>  const toggleAudio = useCallback(async () =&gt; {<br>    try {<br>      if (!localStreamRef.current) {<br>        const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: isVideoEnabled });<br>        localStreamRef.current = stream;<br>        <br>        // Call all connected peers<br>        callAllPeers();<br>        <br>        setIsAudioEnabled(true);<br>        toast.success(&#39;Microphone enabled&#39;);<br>      } else {<br>        const audioTracks = localStreamRef.current.getAudioTracks();<br>        <br>        if (audioTracks.length &gt; 0) {<br>          const isCurrentlyEnabled = audioTracks[0].enabled;<br>          audioTracks.forEach(track =&gt; {<br>            track.enabled = !isCurrentlyEnabled;<br>          });<br>          <br>          setIsAudioEnabled(!isCurrentlyEnabled);<br>          toast.success(isCurrentlyEnabled ? &#39;Microphone disabled&#39; : &#39;Microphone enabled&#39;);<br>        } else {<br>          // No audio tracks, need to get new stream<br>          const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: isVideoEnabled });<br>          <br>          // Replace current stream<br>          if (localStreamRef.current) {<br>            localStreamRef.current.getTracks().forEach(track =&gt; track.stop());<br>          }<br>          <br>          localStreamRef.current = stream;<br>          callAllPeers();<br>          <br>          setIsAudioEnabled(true);<br>          toast.success(&#39;Microphone enabled&#39;);<br>        }<br>      }<br>    } catch (error) {<br>      console.error(&#39;Error toggling audio:&#39;, error);<br>      toast.error(&#39;Failed to toggle microphone&#39;);<br>    }<br>  }, [isVideoEnabled]);<br><br>  // Toggle video<br>// Move callAllPeers above toggleVideo<br>const callAllPeers = useCallback(() =&gt; {<br>  if (!peerRef.current || !localStreamRef.current) return;<br>  <br>  connectedPeers.forEach(peerId =&gt; {<br>    try {<br>      const call = peerRef.current!.call(peerId, localStreamRef.current!);<br>      <br>      call.on(&#39;stream&#39;, (remoteStream) =&gt; {<br>        console.log(&#39;Received remote stream from&#39;, peerId);<br>        setUserStreams(prev =&gt; ({<br>          ...prev,<br>          [peerId]: remoteStream<br>        }));<br>      });<br>    } catch (error) {<br>      console.error(&#39;Error calling peer:&#39;, error);<br>    }<br>  });<br>}, [connectedPeers, peerRef, localStreamRef, setUserStreams]);<br><br>const toggleVideo = useCallback(async () =&gt; {<br>  try {<br>    if (!localStreamRef.current) {<br>      const stream = await navigator.mediaDevices.getUserMedia({ audio: isAudioEnabled, video: true });<br>      localStreamRef.current = stream;<br>      <br>      // Call all connected peers<br>      callAllPeers();<br>      <br>      setIsVideoEnabled(true);<br>      toast.success(&#39;Camera enabled&#39;);<br>    } else {<br>      const videoTracks = localStreamRef.current.getVideoTracks();<br>      <br>      if (videoTracks.length &gt; 0) {<br>        const isCurrentlyEnabled = videoTracks[0].enabled;<br>        videoTracks.forEach(track =&gt; {<br>          track.enabled = !isCurrentlyEnabled;<br>        });<br>        <br>        setIsVideoEnabled(!isCurrentlyEnabled);<br>        // Stop the video stream when disabling the camera<br>        if (isCurrentlyEnabled &amp;&amp; localStreamRef.current) {<br>          localStreamRef.current.getVideoTracks().forEach(track =&gt; track.stop());<br>          localStreamRef.current = null; // Set localStreamRef.current to null<br>        }<br>        toast.success(isCurrentlyEnabled ? &#39;Camera disabled&#39; : &#39;Camera enabled&#39;);<br>      } else {<br>        // No video tracks, need to get new stream<br>        const stream = await navigator.mediaDevices.getUserMedia({ audio: isAudioEnabled, video: true });<br>        <br>        // Replace current stream<br>        if (localStreamRef.current) {<br>          localStreamRef.current.getTracks().forEach(track =&gt; track.stop());<br>        }<br>        <br>        localStreamRef.current = stream;<br>        callAllPeers();<br>        <br>        setIsVideoEnabled(true);<br>        toast.success(&#39;Camera enabled&#39;);<br>      }<br>    }<br>  } catch (error) {<br>    console.error(&#39;Error toggling video:&#39;, error);<br>    toast.error(&#39;Failed to toggle camera&#39;);<br>    }<br>    }, [isAudioEnabled, callAllPeers]);<br><br>    // Share screen<br>    const shareScreen = useCallback(async () =&gt; {<br>        try {<br>            if (isScreenSharing &amp;&amp; screenStreamRef.current) {<br>                // Stop screen sharing<br>                screenStreamRef.current.getTracks().forEach(track =&gt; track.stop());<br>                screenStreamRef.current = null;<br>                setIsScreenSharing(false);<br>                toast.success(&#39;Screen sharing stopped&#39;);<br><br>                // Restore previous stream if available<br>                if (localStreamRef.current) {<br>                    callAllPeers();<br>                }<br>            };<br><br>            const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });<br><br>            // Add event listener for when user stops sharing<br>            stream.getVideoTracks()[0].onended = () =&gt; {<br>                setIsScreenSharing(false);<br>                screenStreamRef.current = null;<br>                toast.success(&#39;Screen sharing stopped&#39;);<br><br>                // Restore previous stream if available<br>                if (localStreamRef.current) {<br>                    callAllPeers();<br>                }<br>            };<br><br>            screenStreamRef.current = stream;<br>            setIsScreenSharing(true);<br>            toast.success(&#39;Screen sharing started&#39;);<br><br>            // Call all peers with screen share<br>            callAllPeersWithScreen();<br><br>        } catch (error) {<br>            console.error(&#39;Error sharing screen:&#39;, error);<br>            toast.error(&#39;Failed to share screen&#39;);<br>        }<br>    }, [isScreenSharing]);<br><br>    // Call all peers with screen share<br>    const callAllPeersWithScreen = useCallback(() =&gt; {<br>        if (!peerRef.current || !screenStreamRef.current) return;<br><br>        connectedPeers.forEach(peerId =&gt; {<br>            try {<br>                const call = peerRef.current!.call(peerId, screenStreamRef.current!);<br><br>                call.on(&#39;stream&#39;, (remoteStream) =&gt; {<br>                    console.log(&#39;Received remote stream from&#39;, peerId);<br>                    setUserStreams(prev =&gt; ({<br>                        ...prev,<br>                        [peerId]: remoteStream<br>                    }));<br>                });<br>            } catch (error) {<br>                console.error(&#39;Error calling peer with screen:&#39;, error);<br>            }<br>        });<br>    }, [connectedPeers]);<br><br>    // Upload and share image<br>    const uploadImage = useCallback(async (file: File) =&gt; {<br>        try {<br>            if (!file) return;<br><br>            // Convert file to data URL<br>            const reader = new FileReader();<br><br>            reader.onload = (event) =&gt; {<br>                if (event.target &amp;&amp; event.target.result) {<br>                    const imageDataUrl = event.target.result as string;<br><br>                    // Send image message<br>                    sendMessage(imageDataUrl, &#39;image&#39;);<br>                }<br>            };<br><br>            reader.readAsDataURL(file);<br>        } catch (error) {<br>            console.error(&#39;Error uploading image:&#39;, error);<br>            toast.error(&#39;Failed to upload image&#39;);<br>        }<br>    }, [sendMessage]);<br><br>    // Create a new channel<br>    const createChannel = useCallback((name: string, type: &#39;text&#39; | &#39;voice&#39; | &#39;announcement&#39; = &#39;text&#39;) =&gt; {<br>        if (!name.trim()) return;<br><br>        const channel: Channel = {<br>            id: `channel-${Date.now()}`,<br>            name: name.trim(),<br>            description: `${name} channel`,<br>            isPrivate: true,<br>            type,<br>            members: [],<br>            messages: []<br>        };<br><br>        setChannels(prev =&gt; [...prev, channel]);<br>        setCurrentChannelId(channel.id);<br><br>        // Broadcast new channel<br>        broadcast({<br>            type: &#39;channel&#39;,<br>            payload: [channel]<br>        }, channel.isPrivate);<br><br>        toast.success(`Created ${type} channel: ${name}`);<br><br>        return channel;<br>    }, [broadcast]);<br><br>    // Create a new server (which is a channel)<br>    const createServer = useCallback((name: string) =&gt; {<br>        if (!name.trim()) return;<br><br>        // Create a channel instead<br>        return createChannel(name, &#39;text&#39;);<br>    }, [createChannel]);<br><br>    // Select channel<br>    const selectChannel = useCallback((channelId: string) =&gt; {<br>        setCurrentChannelId(channelId);<br>    }, []);<br><br>    // Select server (just a wrapper to keep API compatibility)<br>    const selectServer = useCallback((serverId: string) =&gt; {<br>        // Treat servers as channels<br>        selectChannel(serverId);<br>    }, [selectChannel]);<br><br>    // Disconnect from all peers and server<br>    const disconnect = useCallback(() =&gt; {<br>        if (peerRef.current) {<br>            Object.values(connectionsRef.current).forEach(conn =&gt; {<br>                conn.close();<br>            });<br><br>            peerRef.current.disconnect();<br>            setStatus(&#39;disconnected&#39;);<br>            connectionsRef.current = {};<br>            setConnectedPeers([]);<br><br>            // Stop media streams<br>            if (localStreamRef.current) {<br>                localStreamRef.current.getTracks().forEach(track =&gt; track.stop());<br>                localStreamRef.current = null;<br>            }<br><br>            if (screenStreamRef.current) {<br>                screenStreamRef.current.getTracks().forEach(track =&gt; track.stop());<br>                screenStreamRef.current = null;<br>            }<br><br>            setIsAudioEnabled(false);<br>            setIsVideoEnabled(false);<br>            setIsScreenSharing(false);<br>        }<br>    }, []);<br><br>    return {<br>        status,<br>        users,<br>        messages,<br>        channels,<br>        servers,<br>        currentChannelId,<br>        currentServerId,<br>        connectedPeers,<br>        userStreams,<br>        isAudioEnabled,<br>        isVideoEnabled,<br>        isScreenSharing,<br>        localStream: localStreamRef.current,<br>        connectToPeer,<br>        sendMessage,<br>        updateTypingStatus,<br>        toggleAudio,<br>        toggleVideo,<br>        shareScreen,<br>        uploadImage,<br>        createChannel,<br>        createServer,<br>        selectChannel,<br>        selectServer,<br>        updateChannelPrivacy,<br>        disconnect<br>    };<br>};<br><br>export default usePeerConnection;</pre><p>Basically this is the usePeerConnection I use to manage all the comunication. As you can see it’s pretty verbose, I’m sure we can optimaze it much better, but this is just to show you the amount of logic the AI has to “produce” (of course I apply some changes, but most of the code it’s from AI). I apply the changes that I need it, but still; for the AI it’s hard to keep in memory all this code. I found myself having to explain to the AI how the app should work over and over. This new systems, which are incredible, have still many difficulties with large code bases, and large pieces of logic. They can write a lot of code, but that doesn’t mean that the code is always right or respondes to our business requirements. Of course we can use different strategies to mitigate this problem; requirements can be injected into the AI using different methods (prompt injection or custom training), but I found that it’s very difficult to give full context to the AI since their context window is always much smaller than what it’s needed on most projects.</p><p><em>Anyways, let’s get back to the App</em>. Once we have our main design in place with the minimal logic we need, it’s time to start getting our hards dirty.</p><p>I always suggest getting familiar with the codebase, clean up as much as posible, remove duplicates (you’ll probably get bore on your personal projects, but on a profesional setting this needs to be done), improve code quality and bug fixing. This is something that you need to incorporate in your building practices. The AIs are not infalible, all the contrary, and you need to have a grasp of what the AI produced, it’s limitations and how you can change it.</p><blockquote>I FOUND THAT THIS NEW SYSTEMS ARE NOT A TOOL FOR SOMEBODY WITH NO CODING EXPERIENCE. You’ll have a VERY hard time otherwise.</blockquote><h3>Getting to our project, What’s ChatPeer?</h3><p>Well, after this long explanation let’s now talk about what ChatPeer actually is.</p><p>As explain before this is a <strong>P2P, local fist, secure and open source platform for Web communication; </strong>a place where people can go, chat with another person or an integrated AI and have some fun on a P2P environment. All totally private, secure, and free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmJWAJFAlJI7hA8-nMsYqw.png" /><figcaption>ChatPeer Landing page</figcaption></figure><h3>What can you do with ChatPeer?</h3><p>ChatPeer has many of the classical functionalities of a Chat App, but I have also included many more:</p><p>1️⃣<strong> Peer-to-Peer Communication (via PeerJS)</strong></p><ul><li>Text Messaging: Users can send and receive messages in real time.</li><li>Audio Calls: Direct peer-to-peer voice calls.</li><li>Video Calls: High-quality peer-to-peer video communication.</li><li>Screen Sharing: Users can share their screens with connected peers.</li></ul><p>2️⃣ <strong>Connection Management:</strong></p><ul><li>Each user gets a unique peer ID upon opening the app.</li><li>Users can share their peer ID to establish a connection.</li><li>No authentication required — connections are established via direct peer-to-peer links.</li></ul><p>3️⃣<strong> AI-Powered Features (via OpenAI, Grok, Claude, and Groq APIs)</strong></p><ul><li>Context-Aware Chat Assistance: AI helps summarize, translate, or analyze conversations, all in your chat.</li><li>Real-Time Insights: AI offers sentiment analysis, topic extraction, or conversation enhancements.</li></ul><p>4️⃣<strong> Privacy-Focused &amp; Local-Only Storage</strong></p><ul><li>LocalStorage-Based Data Handling: Chat history, preferences, and peer connections are stored only in LocalStorage.</li><li>No backend servers or databases — full local privacy.</li><li>Data persists even after page refresh (unless manually cleared or disabled — it’s disabled by default).</li></ul><p>5️⃣ <strong>End-to-End Peer Security:</strong></p><ul><li>Messages and calls go directly between users — no intermediaries.</li><li>No user tracking, data collection, or cloud storage.</li></ul><p>6️⃣ <strong>User Experience &amp; UI</strong></p><ul><li>Desktop-Only Support (No mobile compatibility for the moment).</li><li>Minimalist, Modern UI with a clean chat interface.</li><li>Copy &amp; Share Peer ID functionality for easy connections.</li></ul><p>7️⃣️ <strong>Simple Controls:</strong></p><ul><li>Start/end a call, toggle video/audio, and enable/disable AI features, and more.</li></ul><p><strong>Let’s take a loot at the App now!</strong></p><p>The first step is going to the <a href="https://chat-peer.netlify.app/">landing page</a>. Open the chat on “Lunch App” and start your journey.</p><ol><li>Enter your Username, can be whatever, in my case is my name “Enzo”.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBdSwGMhrvBwCmLwGnRS-Q.png" /><figcaption>Chat Interface — User Connection</figcaption></figure><p>2. Once you’re in the Chat, you’ll see the Chat Interface where you can create a new channel, chat with the bot, or invite somebody to join the conversation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wC_i1jC8_DfXGDl2L94eKA.png" /><figcaption>Main Chat Interface</figcaption></figure><p>3. Let’s start creating a new channel called “Shared Channel”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*Iu4_hT5B71WSFUQYrgMDeg.png" /><figcaption>Create new Text Channel</figcaption></figure><p>4. Let’s invite another Peer to this channel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*TghCBKhrAvXlo6HNu-d4Yw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*L-2hf8FXY3gv9piy97DJgA.png" /></figure><p>Click the invite button at the top right of the screen and enter the peer id of the user you want to invite. Once done you’ll see a confirmation at the bottom, and you’ll be able to exchange messages with the user you invited.</p><p><strong>What else can you do?</strong></p><p>4. Once you have invite another person you can make: Video Call, Audio Call, Share Screen, and bring an AI bot into your conversations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_1dMvR9kbyMARdiugnNxnA.png" /><figcaption>Video Call from Invited User</figcaption></figure><p>5. As said before, you can ask an AI bot by simple write @bot on the chat bar and your prompt (remember, for the moment, it’s only text based models; if you need multimodal capabilities, contact me, let’s dicusss it).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXlUetdp4M7Zvqmw9lYJ4w.png" /><figcaption>Bot answer when you write @bot following by your prompt</figcaption></figure><p>⚠️ Remember to configure the bot from the setting (on the bottom left of the screen).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*94AiTYKnNwSzpUjD_4G-mg.png" /><figcaption>Settings LLM configurations</figcaption></figure><p>6. You also have the Storage settings that you can use to Import, Export or Clear the storage (AKA chats, channels, etc) on your session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LG5sudmBQ3GoNq-eO5gwoA.png" /><figcaption>From here you can clear your storage, download your chats, import old chats.</figcaption></figure><p><strong><em>Local Storage is disabled by default. If you want to keep your conversations, you need to toggle this functionality first.</em></strong></p><p>And that’s basically it. It’s a pretty simple application for p2p communication with a pitch of AI magic ✨ Hope you enjoy it.</p><p>If you found it useful, give me a clap 👏🏽 I really appreciate it.</p><p>Also if you want to contribute or just take a look at the code, you can do so on the <a href="https://github.com/EnzoVezzaro/chat-peer">Github page</a> (if you give me a star I’d also appreciate it so much) 💻.</p><p>For the live application for to this <a href="https://chat-peer.netlify.app/">website</a>. 🌎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30486e0ebfd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe Coding Adventures: Day 6— P2P Handshake v1 / v]]></title>
            <link>https://medium.com/@enzovezzaro/vibe-coding-adventures-day-6-p2p-handshake-v1-v-91aed304368b?source=rss-a225e16db862------2</link>
            <guid isPermaLink="false">https://medium.com/p/91aed304368b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[p2p]]></category>
            <category><![CDATA[decentralization]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Enzo Junior Vezzaro]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 17:55:57 GMT</pubDate>
            <atom:updated>2025-04-09T15:02:31.240Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vibe Coding Adventures: Day 6— P2P HandShare v1 / v2</h3><p>We keep vibing, we keep building! 🚀</p><p>Today, we’re diving <strong>back into P2P communication</strong>, but this time, we’re making it even cooler — <strong>a P2P file transfer system</strong> for anyone who values <strong>privacy-first</strong> file sharing. Because let’s be real — <strong>our security matters.</strong> 🔒</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmUJ8YupvXNlDR9BptJB_g.png" /><figcaption>P2P HandShare UI</figcaption></figure><h3>Do We Really Need Servers for Everything?</h3><p>We live in a world where almost <strong>everything</strong> depends on servers. And sure, for <strong>heavy-duty operations</strong>, we absolutely need them. But do we really need a server running <strong>24/7</strong> just to transfer files? 🤔</p><blockquote>I don’t think so.</blockquote><p>For <strong>simple</strong> file sharing — when you just want to send a document to a friend without any extra fuss — <strong>a P2P solution is more than enough.</strong> No middlemen, no storage on some random server, just a <strong>direct connection</strong> from you to them.</p><p>Of course, if we’re talking about <strong>huge</strong> files, <strong>cloud storage</strong>, or something that requires <strong>permanent access</strong>, a server makes sense. But if all you need is to <strong>send a file and be done with it</strong>, why not go the <strong>serverless</strong> route?</p><h3>Why Peer-to-Peer (P2P) Matters (And Why You Should Care)</h3><p>Think about the last time you sent a message, made a video call, or shared a file online. Chances are, that data <strong>passed through a central server</strong> — some big data center owned by a corporation that stores, tracks, and maybe even sells your information.</p><p>But what if we didn’t need those middlemen? What if we could just <strong>connect directly</strong> — no servers, no unnecessary delays, just pure <strong>peer-to-peer magic</strong>?</p><p>That’s exactly why <strong>P2P matters</strong>.</p><p><strong>1️⃣ No Middlemen = More Freedom</strong></p><p>With P2P, you don’t need to ask permission from some big company to send a file or start a call. Your data goes <strong>directly from you to the other person</strong> — no creepy third-party looking over your shoulder.</p><p>🛠 <strong>Example:</strong> BitTorrent. The internet tried to kill it, but it’s still one of the most efficient ways to share large files <strong>without</strong> relying on a central hub.</p><p><strong>2️⃣ Faster &amp; More Efficient</strong></p><p>Ever noticed how a video call lags when there are too many people on the platform? That’s because <strong>servers get overwhelmed</strong>. In a P2P system, your data doesn’t take a scenic route through some overloaded cloud server — it zips straight to its destination.</p><p>🛠 <strong>Example:</strong> WebRTC (like what we’re using in this project!). It makes video calls smoother by letting your browser talk directly to the other person’s browser — <strong>no middleman, no bottleneck</strong>.</p><p><strong>3️⃣ Better Privacy</strong></p><p>Most apps <strong>store</strong> your messages, your calls, your everything. That means someone <strong>owns</strong> your data. With P2P, your messages aren’t chilling on some company’s server waiting to be “analyzed” — they go straight to the recipient and disappear.</p><p>🛠 <strong>Example:</strong> Signal (for some calls) and Tox (a fully decentralized chat system). Nobody’s snooping on your convos.</p><p><strong>4️⃣ No Single Point of Failure</strong></p><p>Ever had WhatsApp go down, and suddenly you feel disconnected from the world? That happens because it’s <strong>centralized</strong> — if their servers die, so does your ability to communicate.</p><p>P2P networks <strong>don’t have that problem</strong>. If one peer goes offline, the rest <strong>keep going</strong>.</p><p>🛠 <strong>Example:</strong> Mesh networks. In a disaster, a properly set up P2P mesh can keep people connected even <strong>without internet</strong>.</p><p><strong>6️⃣ Cheap (Or Even Free!)</strong></p><p>Servers cost money. Big companies spend <strong>millions</strong> keeping them running (and pass that cost onto you). P2P networks <strong>share the load</strong> between users, meaning <strong>lower costs and better scalability</strong>.</p><p>🛠 <strong>Example:</strong> Bitcoin. No bank servers, no middlemen, just a bunch of computers verifying transactions on their own.</p><h3>Why This Matters for Our Project</h3><p>Our WebRTC app is all about <strong>pure P2P goodness</strong> — no central servers, no unnecessary processing, just <strong>direct connections</strong> between users. That means:</p><p>✅ <strong>No server costs</strong><br> ✅ <strong>More privacy</strong><br> ✅ <strong>Less lag</strong><br> ✅ <strong>More resilience</strong></p><p>The only problem? We still need to <strong>exchange WebRTC offers &amp; answers</strong> to make the connection. And since we’re not using a central server, we need a creative way to do it.</p><p>And that’s exactly what we’re working on. 🚀</p><h3>P2P HandShare V1 — Let’s Get AI in the Game!</h3><p>It’s time for AI to step up and do its part. Let’s go! 🚀</p><p>As always, everything starts with <strong>the right prompt</strong>. I spent around <strong>30–60 minutes</strong> going back and forth with the AI, refining and tweaking until I got <strong>the perfect prompt</strong>.</p><p>Here’s the final result of that process. Let’s dive in! 🔥</p><pre># HandShare Development Comprehensive Prompt<br><br>## Objective<br>Build a peer-to-peer document sharing application with no backend requirements, focusing on user experience and direct file transfer.<br><br>## Technical Requirements<br>- Use React 18 with Vite<br>- Implement TypeScript<br>- Use Tailwind CSS for styling<br>- Utilize WebRTC for direct file transfer<br><br>## Detailed Development Instructions<br><br>### Project Setup<br>1. Initialize a new Vite React project with TypeScript<br>2. Configure Tailwind CSS and install necessary dependencies<br>3. Set up ESLint and Prettier for code quality<br>4. Create a clean, modular project structure<br><br>### File Upload Component<br>- Create a drag-and-drop file upload interface<br>- Implement file validation:<br>  * Check file types<br>  * Validate file size (recommend 2GB max)<br>  * Provide clear user feedback on file selection<br>- Generate a unique, temporary sharing link upon file selection<br>- Allow easy link copying<br><br>### Connection Mechanism<br>- Implement WebRTC peer connection using WebRTC<br>- Design a connection flow:<br>  1. Sender uploads file<br>  2. Generate unique share link<br>  3. Receiver enters link<br>  4. Establish peer connection<br>  5. Both parties confirm transfer<br><br>### Transfer Protocol<br>- Implement file chunking for large files<br>- Create a secure transfer mechanism<br>- Show real-time transfer progress<br>- Handle potential connection interruptions<br>- Implement transfer cancellation<br><br>### User Interface Considerations<br>- Create a minimalist, intuitive design<br>- Implement responsive layout<br>- Design clear status indicators<br>- Create user-friendly error handling<br>- Ensure accessibility<br><br>### Performance and Security<br>- Minimize data storage<br>- No user authentication required<br>- Implement link expiration<br>- Ensure end-to-end transfer security<br>- Optimize for quick, seamless transfers<br><br>## Stretch Goals<br>- Add optional file encryption<br>- Implement advanced file type support<br>- Create mobile-responsive design<br>- Add transfer speed optimization<br><br>## Development Milestones<br>1. Basic file upload functionality<br>2. Link generation and sharing<br>3. WebRTC connection establishment<br>4. File transfer mechanism<br>5. Error handling and edge cases<br>6. Performance optimization<br>7. UI/UX refinement</pre><p>At this point, it was time to bring in my <strong>favorite AI coding assistants</strong>. This time, I tested the <strong>three most popular</strong> ones <strong>simultaneously</strong>:</p><p>🟢 <a href="https://v0.dev/"><strong>v0.dev</strong></a><br> 🟢 <a href="https://bolt.new/"><strong>Bolt.new</strong></a><br> 🟢 <a href="https://lovable.dev/"><strong>Lovable.dev</strong></a></p><p>After reviewing the results, I ran into several issues: <strong>connectivity problems, missing functionalities</strong>, and in some cases, I even <strong>hit the prompt limit</strong> on these platforms.</p><p>From my experience, the <strong>only tool that consistently delivers a decent job</strong> is <strong>Lovable.dev</strong>. I’m usually <strong>pretty satisfied</strong> with the UI and logic it generates. It’s not the best for fully functional applications, but if you need a <strong>solid modern UI with a moderate amount of logic</strong>, it gets the job done.</p><p>At this stage, the first version was <strong>technically done</strong> — the <strong>components were built, libraries installed</strong>… but, of course, <strong>nothing was actually working</strong>.</p><p>So, you know what that means — <strong>time for the human to step in.</strong> 🔧💻</p><h3>The WebRTC Challenge</h3><p>With the first version done, it was time to <strong>dig deep into the logic</strong>, especially when it came to <strong>WebRTC</strong>. And, well… let’s just say things weren’t exactly working as expected.</p><h4>The WebRTC Roadblock</h4><p>WebRTC is <strong>amazing for peer-to-peer connections</strong>, but it’s also notorious for its quirks. The biggest issue? <strong>Establishing the initial connection</strong> between two peers. Usually, this requires a <strong>signaling server</strong>, which acts as an intermediary to help both ends find each other before they establish a direct connection.</p><p>But here’s the thing: <strong>we didn’t want to involve any servers at all</strong> — not even for signaling (own the servers). This meant we had to find another way to <strong>exchange connection details</strong> between peers <strong>without relying on a centralized server</strong>.</p><h4>Enter the Offer/Answer Method</h4><p>Instead of a traditional signaling server, we opted for a <strong>manual exchange of WebRTC “offer” and “answer” signals</strong>. The process looks something like this:</p><ol><li>The <strong>sender generates an offer</strong> (a chunk of data containing connection details).</li><li>They <strong>share this link</strong> with the recipient, who receives the offer.</li><li>The recipient then <strong>generates an answer</strong> and sends it back to the sender.</li><li>Once both peers have exchanged their signaling data, WebRTC can establish a <strong>direct</strong> P2P connection — no servers required!</li></ol><p><strong>One peer generates a signal, the other pastes it in, and the connection begins. If you want to see this in action, you can go to </strong><a href="https://p2p-handshake.netlify.app/">https://p2p-handshake.netlify.app/</a> and try yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eKAJ6wbO13hfChF5PkXaIg.png" /><figcaption>P2P Handshare V1 WebRTC</figcaption></figure><h4>Unfortunately… this kinda sucks!</h4><p>Technically, this worked <strong>just fine</strong>, but <strong>manually copying and pasting connection data?</strong> Yeah, not exactly the slick user experience I was going for. I mean, who wants to feel like they’re defusing a bomb every time they send a file?</p><p>At first, I thought I was stuck. I briefly considered WebSockets, but that would mean <strong>introducing a server</strong>, which I really didn’t want. The whole point was to keep this <strong>truly peer-to-peer.</strong></p><p><strong>Then it hit me: Peer.js!</strong></p><p>Remember that <a href="https://medium.com/@enzovezzaro/vibe-coding-adventures-day-2-ai-twitter-clone-da5ab1933d8b"><strong>AI-powered Twitter clone</strong></a> we hacked together the other day? Well, we used <strong>Peer.js</strong> for that, and it was an absolute lifesaver. Turns out, <strong>it’s also perfect for solving our WebRTC headache.</strong></p><h4>So, what’s the deal with Peer.js?</h4><p>Peer.js is like WebRTC’s cool older sibling — it handles all the annoying signaling stuff <strong>without making you set up a dedicated server</strong>. Instead of copy-pasting weird codes, it just <strong>handles peer discovery for you</strong>.</p><p>By bringing Peer.js into the mix, we could:<br> ✅ <strong>Ditch the manual copy-paste ritual</strong><br> ✅ <strong>Keep everything fully P2P</strong> (no pesky servers!)<br> ✅ <strong>Actually make this thing fun to use</strong></p><p>And just like that, the project <strong>leveled up</strong>. Next step? Integrating Peer.js and finally getting that smooth, no-hassle experience we were aiming for.</p><h3>That where it was born P2P HandShare V2!</h3><p>And that’s how P2P HandShare V2 came to life! What started as a simple idea has now evolved into something much better, and it’s time to kick things up a gear ⚙️.</p><p>We reimagined how the connection process works by replacing the traditional WebRTC functionalities with peer.js. This means no more headaches with complicated setups.</p><blockquote>Fast, easy, and secure: that’s our promise.</blockquote><p>Now, the sender can simply share a link, and bam — through that link, the receiver automatically connects. No more exchanging long lists of information back and forth between peers. Everything just flows smoothly and effortlessly.</p><h3>And this is the End Result!</h3><p>Now that we have all in place and solved all the tecnical challenges, it’s time for a quick overview.</p><p>1️⃣ Just go to <a href="https://p2p-handshare-peerjs.netlify.app/">https://p2p-handshare-peerjs.netlify.app/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmUJ8YupvXNlDR9BptJB_g.png" /><figcaption>Preview Website</figcaption></figure><p>2️⃣ Upload a file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9jyqOasUqjimx3v0peMKw.png" /></figure><p>3️⃣ Share the generated link to the other person</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fymt_pHXVgsg3QEs39FiwQ.png" /></figure><p>4️⃣ Once the other person is connected, you (the sender) will see the connection open, and you’ll be able to start the transfer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCtgwHiMjsaXj5_cKxeH8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kuOjgqBn6laTh_hU32C1TQ.png" /></figure><p>5️⃣ Once the transfer is done, the receiver (the person connected on the other end) will be able to accept or decline the file transfered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9SQ5Z6gtmOgClewSMroFvQ.png" /></figure><p>6️⃣ If the user accept, the file will be downloaded on his machine. Otherwise, it will be declined.</p><ul><li>💻 Receiver:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABrYpb1Pmd8xdw4CYlaN9A.png" /><figcaption>Receiver: decline</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VhVoJZlmi0CCwuZ3vx0Trw.png" /><figcaption>Receiver: approved</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTXovWKA85cOa7s9c9PRBw.png" /><figcaption>Receiver: file download</figcaption></figure><ul><li>💻 Sender:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VhVoJZlmi0CCwuZ3vx0Trw.png" /><figcaption>Sender: accepted</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4FZzlZigsopxWnwYLofoQ.png" /><figcaption>Sender: decline</figcaption></figure><p>And that’s how you can share files directly between browsers — no need for a centralized server or expensive infrastructure — <strong>Simple, efficient, and free!</strong></p><p>Well, this is the end of this project. It’s been an awesome ride building this, and I’ve had a blast bringing it all together. Want to check out the code? Head over to GitHub! Or if you’re feeling adventurous and want to give it a spin, just hop over to <a href="https://p2p-handshare-peerjs.netlify.app/">https://p2p-handshare-peerjs.netlify.app/</a> and try it for yourself.</p><p>Github: <a href="https://github.com/EnzoVezzaro/peer-to-peer-handshake-docs">https://github.com/EnzoVezzaro/peer-to-peer-handshake-docs</a></p><p>Website: <a href="https://p2p-handshare-peerjs.netlify.app/">https://p2p-handshare-peerjs.netlify.app/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91aed304368b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe Coding Adventures: Day 5— KI Invoicing]]></title>
            <link>https://medium.com/@enzovezzaro/vibe-coding-adventures-day-5-ki-invoicing-f8d4083abdb0?source=rss-a225e16db862------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8d4083abdb0</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ki-invoicing]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Enzo Junior Vezzaro]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 13:20:09 GMT</pubDate>
            <atom:updated>2025-03-24T13:20:09.609Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey, happy coders! Time for a quick update on our Vibe Coding Adventures. 🚀</p><p>Today, I’m excited to share an app I built in just about two hours using some of our favorite tools: <a href="https://lovable.dev/"><strong>Lovable.dev</strong></a><strong>, </strong><a href="https://cline.bot/"><strong>Cline</strong></a><strong>, and, of course, a little bit of human coding magic</strong> by yours truly.</p><p>So, what is <strong>KI Invoicing</strong>? It’s a simple, <strong>open-source</strong> invoicing application designed to be completely <strong>local</strong>, lightweight, and free. It allows you to:</p><p>✅ <strong>Create and manage invoices easily</strong><br>✅ <strong>Preview invoices in real-time</strong><br>✅ <strong>Download invoices as PDFs</strong><br>✅ <strong>Import/Export local database</strong> for seamless backup and restoration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f32KoXCeDbO7-8LPl_goUQ.png" /><figcaption>KI Invoicing</figcaption></figure><h3>Why I Built KI Invoicing</h3><p>This project came to life over the weekend when my wife needed a simple, no-fuss invoicing tool. Most available solutions were either too complex or locked behind expensive paywalls. She just needed <strong>something quick and efficient</strong>, so I decided to build it myself. 💡</p><h3>How I Built KI Invoicing</h3><p>With the power of <strong>AI and modern development tools</strong>! 🦾</p><p>I started with a simple prompt to ChatGPT:</p><blockquote>“Let’s create a modern Single Page Application (SPA) for generating invoices. The app should have editable fields for invoice details (such as item descriptions, prices, taxes, and client information) and display a live preview of the final invoice as users input data. It should also include a section for the business name, logo, and other branding elements. Additionally, the app must have a ‘Download PDF’ button to generate and save the invoice as a PDF.”</blockquote><p>From there, I jumped into <strong>Lovable.dev</strong> to prototype the UI and refine the idea. Within minutes, I had a working visual concept, and with some iterations, I turned it into a functional tool.</p><p>In just few minutes, my idea had a visual concept, and I was able to iterate to better improve the product.</p><p>Since this is such a small project I won’t bore you with the tecnical details, but let me just highlight something really cool about this project.</p><h3>Cool Features of KI Invoicing</h3><p>✨ <strong>100% Local &amp; Private:</strong> The app stores all data in your browser’s local storage. No cloud, no servers, no tracking.</p><p>🔄 <strong>Import/Export Your Data:</strong> Need to switch devices? Download your invoice database and import it back in one click.</p><p>📝 <strong>Open Source &amp; Free:</strong> Modify it, improve it, or use it as is — completely free!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*7FmByjHF0jMjFW1CxXbotg.png" /><figcaption>Export / Import</figcaption></figure><p>KI Invoicing isn’t a revolutionary app, but it <strong>solves a real problem</strong> in a simple way. It’s been super useful for my wife and me, and maybe it will be for you too.</p><p>Hope you enjoyed this quick project! It might not be flashy, but it’s <strong>practical and efficient</strong> — and that’s what coding is all about.</p><p>Thanks for tuning in to my <strong>Vibe Coding Adventures</strong>, and see you in the next one! 🚀</p><p>🔗 <strong>GitHub:</strong> <a href="https://github.com/EnzoVezzaro/invoice-preview-genie">https://github.com/EnzoVezzaro/invoice-preview-genie</a><br>🔗 <strong>Live Demo:</strong> <a href="https://kinvoice.netlify.app/">https://kinvoice.netlify.app/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8d4083abdb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>