Vibe Coding: build real apps with AI · Episode 10. Every agent run below is real: Claude Code 2.1.319 (model claude-sonnet-5-5) in print mode (claude -p), on 7 November 2026, in /home/ravi/projects/todo (a Git repository). The agent's file was served with python3 -m http.server 8090 and tested in Chromium with Playwright (two pages in one browser = two tabs). Replies are quoted exactly, shortened where marked .... Compiler outputs are from the SyntaxPilot compiler (Node.js 24).
The problem: tasks on paper get lost
Ravi's to-do list is on paper (it went through the wash) and in messages to himself (nothing can be ticked off). He wants a small app: add a task, tick it as done, edit it, delete it, and it must remember everything after the browser closes.
One prompt, one app
claude -p "Make me a to-do list web app in a single index.html (HTML, CSS and JavaScript together).
I can add a task, tick it as done, edit it, and delete it. Keep it simple and clean."
--allowedTools Read Write Edit Glob
Real result: one Write of index.html (166 lines) and this reply:
I've created
index.html, a single file with the HTML, CSS and JavaScript together. I haven't opened it in a browser or tested it yet. ... It also shows how many tasks are left, and it saves your tasks in the browser so they're still there after a reload.
Saving was not in the prompt. An unasked extra is still a claim you must test.
State and render (a cricket scoreboard)
| A cricket match | The to-do app |
|---|---|
| the scorer's book: runs, wickets, overs | state: let tasks = [ ... ] |
| the big scoreboard shows the book | render() draws the list from tasks |
| a four is hit: book first, then board | change the array, then render() |
State is everything the app remembers right now. Rendering means drawing the screen from that state. The screen is never edited directly: change the state, then redraw.
let tasks = []; // the state: everything the app remembers
function render() {
list.innerHTML = ''; // wipe the screen list
tasks.forEach(t => {
// build one <li> per task: checkbox, text, Edit, Delete
});
}
Each task is an object (a bundle of named values): { id, text, done }. forEach runs some code for every item of an array.
Add, edit, delete
// ADD
tasks.push({ id: Date.now() + Math.random(), text: v, done: false });
// TICK
t.done = cb.checked;
// EDIT
if (v) t.text = v;
// DELETE: keep every task except this one
tasks = tasks.filter(x => x.id !== t.id);
save(); render(); // after every change
pushadds to the end of an array.- The id is the time in milliseconds plus a random fraction, so no two tasks share one.
filtermakes a new array with only the items that pass a test.
Why apps forget (run it in the compiler)
let tasks = []; // starts here every time
console.log("Loaded:", tasks.length, "tasks");
tasks.push("Buy milk");
console.log("Now:", tasks.length, "task");
Real output, run twice:
Loaded: 0 tasks
Now: 1 task
Both runs print Loaded: 0 tasks. Variables live in memory (RAM), which is cleared when the program ends or the tab closes.
localStorage (a cloakroom locker)
| A railway cloakroom | localStorage |
|---|---|
| a locker with a tag | a key: 'tasks' |
| what's inside stays while you travel | a value, always text; survives a reload |
| this station's cloakroom only | one store per website (origin = scheme + domain + port) |
MDN (fetched 7 Nov 2026): localStorage data has no expiration time (unlike sessionStorage, which is cleared when the page session ends); keys and values are always UTF-16 strings; in a private/incognito window the data is cleared when the last private tab closes.
localStorage.setItem('tasks', value) // save under a key
localStorage.getItem('tasks') // read it back (null if missing)
localStorage.removeItem('tasks') // delete it
The [object Object] trap
const tasks = [{ text: "Buy milk", done: false }];
const saved = String(tasks); // what storage does to a non-string
console.log(saved);
const back = JSON.parse(saved);
console.log(back);
Real output (the SyntaxPilot compiler, Node.js 24):
[object Object]
SyntaxError: "[object Object]" is not valid JSON
The same in Chromium:
> localStorage.setItem('x', [{ text: 'Buy milk', done: false }])
> localStorage.getItem('x')
'[object Object]'
> JSON.parse(localStorage.getItem('x'))
SyntaxError: "[object Object]" is not valid JSON
JSON (pack a cupboard into a parcel)
JSON (JavaScript Object Notation) is a way of writing data as text that almost every language can read. JSON.stringify packs an object or array into text; JSON.parse unpacks the text back.
const tasks = [{ text: "Buy milk", done: false }];
const saved = JSON.stringify(tasks); // pack
console.log(saved);
console.log(typeof saved);
const back = JSON.parse(saved); // unpack
console.log(back[0].text, back[0].done);
console.log(typeof back);
Real output:
[{"text":"Buy milk","done":false}]
string
Buy milk false
object
The AI's load, save and empty state
let tasks = [];
try { tasks = JSON.parse(localStorage.getItem('tasks')) || []; } catch (e) {}
function save() {
try { localStorage.setItem('tasks', JSON.stringify(tasks)); } catch (e) {}
}
if (!tasks.length) {
list.innerHTML = '<li class="empty">Nothing to do. Add a task above.</li>';
}
- First visit:
getItemgivesnull,JSON.parse(null)givesnull, and|| []("or an empty list") makes it[]. try { } catch (e) { }: if something throws an error, handle it instead of crashing the page.- Empty state: what an app shows when there is no data yet. A blank box looks broken; "Nothing to do. Add a task above." explains and gives the next step.
Testing by hand: the checklist
An edge case is an unusual input at the edge of normal use. Write the checklist before you test:
- Add with an empty box
- Add only spaces
- Add the same task twice ("Buy milk", "buy milk")
- A very long task name
- Reload the page
- Use it in two tabs at once
Real results on version 1:
after empty/spaces count: 3 # nothing added: good
after duplicates count: 5 # "Buy milk" twice + "buy milk": bad
after reload count: 5 # saved: good
tab B shows: [ 'Buy milk', 'Finish episode 9 homework', 'Pay electricity bill' ]
tab A shows: [ 'Buy milk', 'Finish episode 9 homework', 'Book train ticket' ]
tab B after reload: [ 'Buy milk', 'Finish episode 9 homework', 'Book train ticket' ]
"Pay electricity bill" was silently lost.
Why: two copies of one shopping list
Each tab read the list once when it opened and kept its own copy in memory. Every change wrote that tab's whole list back. Tab B saved the bill; tab A then saved its older copy plus the ticket, over the top. The last save wins.
Fix 1: re-read before every change
claude -p "Bug: I opened the app in two browser tabs. In tab B I added "Pay electricity bill". Then in tab A
I added "Book train ticket". When I reload tab B, "Pay electricity bill" is gone ... Tasks added in one tab must
never be lost when I use another tab. Find the cause and fix it. Change only what's needed." --allowedTools Read Edit
The agent first tried a python3 command; it was refused (Bash was not allowed), and it said "I'll make the same edits with the Edit tool instead." Its explanation:
Cause: each tab read the task list from localStorage once, when the page loaded. Every add, edit, check or delete then wrote that tab's whole list back to storage. ... Not changed: a tab's displayed list still doesn't refresh until you reload it or make a change.
+ function load() {
+ try { tasks = JSON.parse(localStorage.getItem('tasks')) || []; } catch (e) {}
+ }
+ // Re-read storage before every change so edits made in other tabs are not overwritten.
+ function update(fn) { load(); fn(); save(); render(); }
- tasks.push({ id: Date.now() + Math.random(), text: v, done: false });
- save(); render();
+ update(() => tasks.push({ id: Date.now() + Math.random(), text: v, done: false }));
Re-test: tab A ends with all four tasks; tab B after reload shows all four. But tab A showed an old list until it made a change.
Fix 2: the storage event
MDN: the storage event "fires when another document that shares the same storage area ... updates that storage area. The event is not fired on the window that made the change."
+ // Keep this tab in sync when another tab changes the tasks.
+ window.addEventListener('storage', e => {
+ if (e.key !== 'tasks' && e.key !== null) return;
+ ... // remember text being typed in an edit box
+ load();
+ render();
+ });
Re-test: tab A, no reload: [ 'Buy milk', 'Finish episode 9 homework', 'Pay electricity bill' ].
Fix 3: duplicates (you decide the rule)
Rule chosen by Ravi: don't add a task if an unfinished task has the same text, ignoring capitals and extra spaces; show a message; keep the typed text.
+ const norm = s => s.trim().replace(/\s+/g, ' ').toLowerCase();
+ update(() => {
+ dup = tasks.some(t => !t.done && norm(t.text) === norm(v));
+ if (!dup) tasks.push({ id: Date.now() + Math.random(), text: v, done: false });
+ });
+ dupMsg.textContent = dup ? 'That task is already on the list.' : '';
The agent's own note: "I didn't change the Edit feature. Renaming a task to match another unfinished one is still allowed."
The checklist again (version 4, real)
dup msg: That task is already on the list. | input: " buy MILK " | count 3
after ticking, re-add: [ 'Buy milk', 'Finish episode 9 homework', 'Call Asha about rent', 'Buy milk' ]
edit to empty: (unchanged: the old text is kept)
after reload: 5
storage after clear: null → "Nothing to do. Add a task above."
75dab5c Block duplicate unfinished tasks
2cb82ec Sync tabs with the storage event
ae1b7b4 Re-read storage before every change
c0f309d To-do v1 (AI)
1c32077 Empty project
The final script (real, after the three fixes)
<script>
let tasks = [];
function load() {
try { tasks = JSON.parse(localStorage.getItem('tasks')) || []; } catch (e) {}
}
load();
// Re-read storage before every change so edits made in other tabs are not overwritten.
function update(fn) { load(); fn(); save(); render(); }
let editingId = null;
const list = document.getElementById('list');
const input = document.getElementById('input');
const dupMsg = document.getElementById('dupMsg');
function save() {
try { localStorage.setItem('tasks', JSON.stringify(tasks)); } catch (e) {}
}
function render() {
list.innerHTML = '';
if (!tasks.length) {
list.innerHTML = '<li class="empty" style="display:block">Nothing to do. Add a task above.</li>';
}
tasks.forEach(t => {
const li = document.createElement('li');
if (t.done) li.className = 'done';
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.checked = t.done;
cb.setAttribute('aria-label', 'Mark done');
cb.onchange = () => update(() => { const x = tasks.find(y => y.id === t.id); if (x) x.done = cb.checked; });
li.appendChild(cb);
if (editingId === t.id) {
const edit = document.createElement('input');
edit.type = 'text';
edit.value = t.text;
const commit = () => {
const v = edit.value.trim();
editingId = null;
update(() => { const x = tasks.find(y => y.id === t.id); if (x && v) x.text = v; });
};
edit.onkeydown = e => {
if (e.key === 'Enter') commit();
if (e.key === 'Escape') { editingId = null; render(); }
};
li.appendChild(edit);
const ok = document.createElement('button');
ok.textContent = 'Save';
ok.onclick = commit;
li.appendChild(ok);
setTimeout(() => edit.focus(), 0);
} else {
const s = document.createElement('span');
s.textContent = t.text;
li.appendChild(s);
const ed = document.createElement('button');
ed.textContent = 'Edit';
ed.onclick = () => { editingId = t.id; render(); };
li.appendChild(ed);
}
const del = document.createElement('button');
del.className = 'del';
del.textContent = 'Delete';
del.onclick = () => update(() => { tasks = tasks.filter(x => x.id !== t.id); });
li.appendChild(del);
list.appendChild(li);
});
const left = tasks.filter(t => !t.done).length;
document.getElementById('count').textContent =
tasks.length ? left + ' of ' + tasks.length + ' remaining' : '';
}
document.getElementById('form').onsubmit = e => {
e.preventDefault();
const v = input.value.trim();
if (!v) return;
const norm = s => s.trim().replace(/\s+/g, ' ').toLowerCase();
let dup = false;
update(() => {
dup = tasks.some(t => !t.done && norm(t.text) === norm(v));
if (!dup) tasks.push({ id: Date.now() + Math.random(), text: v, done: false });
});
dupMsg.textContent = dup ? 'That task is already on the list.' : '';
if (!dup) input.value = '';
};
input.addEventListener('input', () => { dupMsg.textContent = ''; });
// Keep this tab in sync when another tab changes the tasks.
window.addEventListener('storage', e => {
if (e.key !== 'tasks' && e.key !== null) return;
const editBox = editingId !== null ? list.querySelector('li input[type=text]') : null;
const draft = editBox ? editBox.value : null;
load();
render();
if (draft !== null) {
const box = list.querySelector('li input[type=text]');
if (box) box.value = draft; // don't lose text being typed
}
});
render();
</script>
Common mistakes (real)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
| Tasks only in a variable | Loaded: 0 tasks, every run |
memory is cleared when the page closes | save to localStorage |
setItem('tasks', tasks) |
SyntaxError: "[object Object]" is not valid JSON |
storage keeps only text | JSON.stringify to save, JSON.parse to load |
| Each tab saves its old copy | "Pay electricity bill" silently lost | last save wins | re-read before every change + the storage event |
| No duplicate rule | "Buy milk" and "buy milk" | edge cases weren't in the prompt | decide the rule, then ask for it |
Mini project
Build the to-do app with any AI tool. Add due dates and a "Clear completed" button, one prompt per change. Run the six-item checklist after every change, and fix the agent's open gap: Edit can still rename a task into a duplicate.
What a good outcome looks like
Every checklist item passes on the final version; editing "Call Asha" to "buy milk" while an unfinished "Buy milk" exists is refused with the same message; tasks survive a reload and appear in a second tab without a reload; one commit per change.
Practice questions
- What does
localStorage.getItem('missing')return?
Answer
null: the key doesn't exist.
- Why does
JSON.parse(localStorage.getItem('tasks')) || []work on the very first visit?
Answer
getItem returns null, JSON.parse(null) returns null, and null || [] gives the empty array.
- Write one line that deletes the task with id
7fromtasks.
Answer
tasks = tasks.filter(t => t.id !== 7);
- In which tab does the
storageevent fire: the one that saved, or the others?
Answer
Only the others (same origin). It is not fired on the window that made the change.
- Name three edge cases for a "add task" box.
Answer
Empty input, only spaces, a duplicate with different capitals (also: very long text, special characters like <b>).
Quiz
const tasks = [{ text: "Call Asha" }];
const saved = JSON.stringify(tasks);
console.log(typeof saved);
A) object B) string C) [object Object] D) array
Answer
B) string. JSON.stringify turns the array into text, which is what localStorage stores.
Interview questions
- What is the difference between
localStorageandsessionStorage? - Why must objects be serialised before saving them in Web Storage?
- Describe a "lost update" (last write wins) and two ways to prevent it.
- What is the
storageevent, and when does it fire? - What is state in a front-end app, and why redraw from state instead of editing the page directly?
Glossary
| Term | Meaning (plain words) | Example |
|---|---|---|
| State | everything the app remembers right now | let tasks = [...] |
| Render | draw the screen from the state | render() |
| Array | an ordered list of values | ["Buy milk", "Call Asha"] |
| Object | a bundle of named values | { id: 1, text: "Buy milk", done: false } |
push |
add an item to the end of an array | tasks.push(task) |
filter |
make a new array with only the items that pass a test | tasks.filter(t => !t.done) |
forEach |
run code for every item | tasks.forEach(t => ...) |
| id | a value that identifies exactly one item | Date.now() + Math.random() |
| CRUD | create, read, update, delete: the four basic data actions | add, show, edit, delete |
| Memory (RAM) | the computer's short-term memory; cleared when a program ends | a variable |
| localStorage | a small store in the browser for each website; survives reloads | localStorage.setItem('tasks', ...) |
| Key / value | the name you save under, and what you save | 'tasks' / the JSON text |
| Origin | scheme + domain + port; each gets its own storage | http://localhost:8090 |
| sessionStorage | like localStorage, but cleared when the page session ends | a one-tab draft |
| String | text | "Buy milk" |
null |
"nothing here" | getItem('missing') |
| JSON | a text format for data most languages can read | [{"text":"Buy milk"}] |
JSON.stringify |
object/array → JSON text (pack) | save |
JSON.parse |
JSON text → object/array (unpack) | load |
typeof |
tells you what kind of value you have | typeof "hi" → "string" |
try / catch |
run code, and handle an error instead of crashing | around JSON.parse |
\|\| (or) |
"if the left side is empty, use the right" | x \|\| [] |
| Empty state | what an app shows when there is no data yet | "Nothing to do. Add a task above." |
| Edge case | an unusual input at the edge of normal use | only spaces |
| Hand-test checklist | a written list of checks you run on every version | the six items |
| Playwright | a tool that drives a real browser like a person | clicks, types, reads |
| Last write wins (lost update) | a later save overwrites a change it never saw | the lost bill |
storage event |
fires in other tabs when localStorage changes | live sync |
| Event listener | code that runs when something happens | addEventListener('storage', ...) |
| Normalise | make text comparable | trim, squeeze spaces, lower-case |
| Commit | a Git save point | 2cb82ec |
Summary
State is what the app remembers; render draws it. Variables forget, so the AI saved to localStorage, which stores only text: JSON.stringify to save, JSON.parse to load, || [] and an empty state for the first visit. A written checklist found a real data-loss bug (two tabs, last save wins), fixed by re-reading before every change and syncing with the storage event, plus a duplicate rule you choose. Re-run the whole checklist after every fix.