Build a 3D Smart Home with Claude Code

Build a 3D smart home that controls a local bulb from your menu bar.

Introduction

30 Second Summary

A lamp can be easy to switch until its controls are buried in a brand-specific app. That friction grows when every device asks for a different screen.

In this project, you will use Claude Code to build a draggable three.js room that switches one bulb through a local HTTP API. You will package the finished controller with Electron so it opens from the Mac menu bar or Windows system tray.

What You'll Build

You will click a floor lamp in your draggable room to watch the 3D scene glow warm yellow at the same moment as your simulated or real bulb.

By the end of this project, you'll have:

  • A simulated bulb page that turns yellow with ON or grey with OFF.
  • A shared lamp controller that lets you choose simulated lighting, Philips Hue, or Home Assistant while keeping credentials out of the web page.
  • A synchronized desktop room that opens from your menu bar or system tray. Its floor lamp switches the selected bulb.
  • Secret Mission: Add Bright, Cozy, and Movie scene buttons that synchronize bulb brightness with the 3D room.

Are there any prerequisites?

You need a Claude plan that includes Claude Code.

You also need internet access on a supported Mac or Windows PC.

A Philips Hue or Home Assistant light is optional because the project includes a simulator.

Before We Start

Before the hands-on work begins, this step helps you commit to the lamp controller you want to build. You will choose a bulb path that makes the finished 3D home meaningful to you.

Install Node.js and Claude Code

Claude Code writes the project files while Node.js runs every local part of your lamp controller.

This setup gives you one command window for checking both tools. You will finish with Claude Code inside ~/Desktop/my-3d-home.

In this step, get ready to:
  • Install Node.js 26.13.1 LTS and confirm node -v prints v26.13.1.
  • Install Claude Code and confirm claude --version prints a version number.
  • Create ~/Desktop/my-3d-home and open Claude Code there after signing in.
Install Node.js 26.13.1 LTS

Node.js provides the runtime that executes the simulator, local server, and desktop app. This project uses the 26.13.1 LTS release so everyone works with the same version.

macOS

  • Download node-v26.13.1.pkg.
  • Locate node-v26.13.1.pkg on the download page.
  • Select the filename to begin the download.
  • Install Node.js from node-v26.13.1.pkg with the default installer options.
  • Open the downloaded package.
  • Keep each preselected installer option unchanged.
  • Complete the installer.

You should see the installer finish successfully.

Windows

  • Download node-v26.13.1-x64.msi, or choose node-v26.13.1-arm64.msi on a Windows ARM PC.
  • Locate the installer matching your Windows computer on the download page.
  • Select its filename to begin the download.
  • Install Node.js from the downloaded .msi file with the default installer options.
  • Open the downloaded installer.
  • Keep each preselected installer option unchanged.
  • Complete the installer.

You should see the installer finish successfully.

Before you check, which exact version do you expect the command window to print?

  • Check the installed Node.js version by running this command:
node -v

What does this command do?

The node command starts the Node.js runtime. The -v option asks it to print the installed version.

You should see v26.13.1 in the command window.

✔️ I see v26.13.1

That check confirms Node.js is ready to run every local part of your smart home.

ⓧ I see an older version

The command is finding an older Node.js installation. Install the pinned release before continuing.

  • Return to the Node.js download page.
  • Download the 26.13.1 installer for your operating system.
  • Run the installer with its default options.
  • Start a fresh command window after installation.
  • Run the version check again.

ⓧ Command not found

Your command window cannot find Node.js yet. Install it before moving on.

  • Return to the Node.js download page.
  • Download node-v26.13.1.pkg on macOS.
  • Download node-v26.13.1-x64.msi on most Windows PCs.
  • Download node-v26.13.1-arm64.msi on a Windows ARM PC.
  • Run the downloaded installer with its default options.
  • Start a fresh command window after installation.
  • Run the version check again.
Prepare your Claude Code workspace

Claude Code turns instructions into project files from your command window. Its native installer adds the claude command to your computer.

macOS

  • Launch the official Claude Code installer in Terminal by running this command:
curl -fsSL https://claude.ai/install.sh | bash

What does this command do?

This command downloads the official macOS installation script from Claude. It passes that script to your shell so Claude Code can be installed.

You should see the installation command finish without reporting a failed installation.

Windows

  • Launch the official Claude Code installer in PowerShell by running this command:
irm https://claude.ai/install.ps1 | iex

What does this command do?

This command downloads the official Windows installation script from Claude. It passes that script to PowerShell so Claude Code can be installed.

You should see the installation command finish without reporting a failed installation.

  • Close the current command window.
  • Start a new Terminal window on macOS or a new PowerShell window on Windows.
  • Open your computer's app search.
  • Search for Terminal on macOS or PowerShell on Windows.
  • Select the matching result.

You should see a fresh command window with a new prompt.

  • Check the Claude Code installation by running this command:
claude --version

What does this command do?

The --version option asks Claude Code to print its installed version. A version number confirms that your fresh command window can find the tool.

You should see Claude Code print a version number.

✔️ I see a version number

Claude Code is installed and ready to open your project workspace.

ⓧ Command not found

The current window has not picked up the installed command.

  • Close every open Terminal or PowerShell window.
  • Start a fresh Terminal or PowerShell window.
  • Run the Claude Code version check again.
  • Rerun the installer for your operating system if the command remains unavailable.

Still missing an installed command?

A newly installed command may be unavailable in a window that was already open. Close every command window before starting a fresh one.

If node -v or claude --version still fails, help me troubleshoot my Node.js or Claude Code installation.

Give Claude Code a project workspace

Claude Code uses the current folder as its project workspace. Starting it inside my-3d-home keeps every generated file together on your Desktop.

The final command opens Claude Code. It can prompt you to sign in with the Claude account that includes your Claude Code access.

Before you run these commands, which folder do you expect Claude Code to use as its workspace?

  • Create my-3d-home on your Desktop and start Claude Code inside it by running these commands:
cd ~/Desktop
mkdir my-3d-home
cd ~/Desktop/my-3d-home
claude

What does this command do?

  • The first cd command moves the command window to your Desktop.
  • The mkdir command creates the my-3d-home folder.
  • The second cd command moves into that new folder.
  • The claude command starts Claude Code with that folder as its workspace.
  • Complete the sign-in prompts using your existing Claude account if Claude Code asks you to sign in.
  • Continue through the sign-in flow shown by Claude Code.
  • Return to Claude Code after the sign-in flow completes.

That is your development workspace ready. You should see Claude Code running with a project path ending in ~/Desktop/my-3d-home.

Node.js and Claude Code are ready inside your project folder. Next, you will use them to switch your selected bulb from code.

Switch a Bulb from Code

Your development tools are ready. Now you can create the first working connection between your project and a bulb.

A server-side adapter built with Claude Code and Node.js lets the future 3D room control one bulb while its credentials stay in config.json.

In this step, get ready to:
  • Configure a simulated, Philips Hue, or Home Assistant bulb path with its credentials kept in server-side configuration.
  • Create a shared lamp adapter with getLamp() and setLamp(on).
  • Run the adapter test and observe the selected bulb turn on for three seconds before turning off.
Configure one bulb path

Each bulb exposes a different HTTP API. Your server-side configuration identifies which API the shared adapter should use.

Why start with the simulator?

The simulator removes hardware setup while preserving the same bulb-shaped data used by the shared adapter. This gives you a visible result before the 3D interface exists.

Direct browser requests could expose device credentials. Keeping requests behind the adapter gives every bulb path the same safe interface.

  • Choose the tab that matches the bulb you want to control.

No Smart Bulb

The default path runs a simulated bulb on your computer. Its page gives you a visible ON or OFF state without any hardware.

  • Switch back to Claude Code and paste this request:
Create bulb.js as a readable, commented Node.js program using only node:http. Listen on 127.0.0.1 port 4001. GET /light must return the Hue-shaped JSON {"on":{"on":false}} or the current true value. PUT /light must accept the same shape and update the state. GET / must show one large simulated bulb that is grey with the exact word OFF when off and yellow with the exact word ON when on. Poll GET /light every second. Also create config.json with type fake and the simulator URL http://127.0.0.1:4001. Do not create style.css. Keep all simulator page styles inside bulb.js.

What does this prompt create?

Claude creates bulb.js as a local simulator bound to 127.0.0.1. Its GET /light route reports the current state.

The PUT /light route changes that state. The generated config.json selects this simulator as the active bulb path.

You should see bulb.js and config.json in ~/Desktop/my-3d-home.

macOS

  • Start the simulator in a second Terminal window by running these commands:
  • Press Cmd+Space to open Spotlight.
  • Type Terminal and press Enter to open another window.
cd ~/Desktop/my-3d-home
node bulb.js
What does this command do?

The first command returns this Terminal window to your existing project directory. The second command starts the simulator from bulb.js.

Windows

  • Start the simulator in a second PowerShell window by running these commands:
  • Press the Windows key to open search.
  • Type PowerShell and press Enter to open another window.
cd ~/Desktop/my-3d-home
node bulb.js
What does this command do?

The first command returns this PowerShell window to your existing project directory. The second command starts the simulator from bulb.js.

You should see a grey bulb with the exact word OFF. Keep the simulator command running in this window.

Philips Hue

The Hue path registers a local application with your bridge. A dedicated HTTPS agent limits the relaxed certificate setting to bridge requests.

  • Record the bridge IP as your Hue Bridge IP.
  • Open the Philips Hue app on the device where it is installed.
  • Select Settings.
  • Select Hue Bridges to find the bridge IP.
  • Press the physical link button on the Hue Bridge.
  • Switch back to Claude Code and paste this request:
Create a temporary setup-hue.js for my local Hue Bridge. Use node:https and one dedicated https.Agent with rejectUnauthorized false only for requests to my bridge. Never set NODE_TLS_REJECT_UNAUTHORIZED. POST https://BRIDGE-IP/api with {"devicetype":"my-3d-home#laptop","generateclientkey":true}, print the returned username, then use it as the hue-application-key header for GET https://BRIDGE-IP/clip/v2/resource/light and print every light id and name. Replace BRIDGE-IP only after asking me for it. Also create config.json with type hue and placeholders for bridgeIp, applicationKey, and lightId. Never put the key in index.html.

What does this prompt create?

The temporary helper registers your project with the local bridge. It then lists the lights that the bridge can control.

The application key stays in config.json on the server side. The future browser page never receives it.

macOS

  • Run the temporary Hue helper in a second Terminal window with these commands:
  • Press Cmd+Space to open Spotlight.
  • Type Terminal and press Enter to open another window.
cd ~/Desktop/my-3d-home
node setup-hue.js
What does this command do?

This starts the temporary registration helper from your existing project directory. The helper contacts only the bridge IP you provide.

Windows

  • Run the temporary Hue helper in a second PowerShell window with these commands:
  • Press the Windows key to open search.
  • Type PowerShell and press Enter to open another window.
cd ~/Desktop/my-3d-home
node setup-hue.js
What does this command do?

This starts the temporary registration helper from your existing project directory. The helper contacts only the bridge IP you provide.

You should see a Hue username or application key followed by a list of light IDs and names. Keep the key private.

  • Replace the bridgeIp placeholder in config.json with your Hue Bridge IP.
  • Replace the applicationKey placeholder with the application key printed by the helper.
  • Replace the lightId placeholder with the ID of the light you want to control.
  • Delete the temporary setup-hue.js file after saving those values.

Your selected Hue light is now represented by server-side values in config.json.

Home Assistant

The Home Assistant path uses its REST API. Your local server stores the address and token so the browser never needs direct access.

A long-lived access token is a live credential. Keep it only in config.json and keep it out of screenshots.

  • Create a long-lived access token from your Home Assistant profile.
  • Open the profile page in your existing Home Assistant interface.
  • Select Security.
  • Use the long-lived access token control to create a token for this project.
  • Record the address you already use as your Home Assistant address.
  • Record the light entity ID as your light entity ID.
  • Switch back to Claude Code and paste this request:
Create config.json with type home-assistant and placeholders for baseUrl, token, and entityId. I will replace them with my Home Assistant address, long-lived access token, and light entity id. Keep the token only in config.json. Never put it in index.html and do not add CORS configuration.

What does this prompt create?

Claude creates the server-side fields required by the Home Assistant adapter. The browser-facing code receives none of these values.

Home Assistant OS commonly uses port 80. Home Assistant Container commonly uses port 8123.

  • Replace the baseUrl placeholder in config.json with your Home Assistant address.
  • Replace the token placeholder with the long-lived access token.
  • Replace the entityId placeholder with your light entity ID.

Your Home Assistant settings now remain on the server side. No browser CORS configuration is required.

Build the shared lamp adapter

A state adapter gives different devices one shared interface. The rest of your project can call getLamp() or setLamp(on) without knowing which bulb path is active.

  • Switch back to Claude Code and paste this request:
Create readable, commented lamp.js with async functions getLamp() and setLamp(on), and export both. Read settings from config.json. For type fake, use GET and PUT at /light with the body {"on":{"on":true}} or false. For type hue, use GET and PUT at /clip/v2/resource/light/{lightId}, send hue-application-key, and use one dedicated https.Agent with rejectUnauthorized false only for Hue requests. Never use NODE_TLS_REJECT_UNAUTHORIZED. For type home-assistant, read GET /api/states/{entityId} and send POST /api/services/light/turn_on or turn_off with Authorization Bearer token and {"entity_id":"..."}. Then create test-lamp.js that calls setLamp(true), waits three seconds, and calls setLamp(false). Do not run it.

What does this prompt create?

The requestJson() helper handles local HTTP requests and secure HTTPS requests. The dedicated hueAgent applies its certificate setting only to Hue Bridge traffic.

The adapter translates each provider's response into one boolean state. The test script exercises that shared interface without exposing any credential.

You should now have lamp.js and test-lamp.js alongside your configuration. Every bulb path exposes the same two lamp functions.

Run the adapter test

The test gives the adapter one complete job. It switches the selected bulb on before returning it to the off state.

  • Ask Claude Code to review the generated files by pasting this request:
Review bulb.js, config.json, lamp.js, and test-lamp.js. Confirm that secrets are absent from every browser-facing string, both local servers use 127.0.0.1, and test-lamp.js is ready. Do not run node test-lamp.js. Tell me only what I should expect when I run it.

What does this review check?

Claude checks the security boundary before the script touches your selected bulb. It also confirms that the simulator and future app server remain available only on your computer.

The review deliberately leaves the final run to you. This lets you observe the device change outside Claude Code.

Claude should report that the test turns the selected lamp on before waiting three seconds. It should report that the lamp turns off afterward.

Before you run the test, do you expect the adapter to reach the bulb path you configured?

macOS

  • Run the adapter test in a third Terminal window with these commands:
  • Press Cmd+Space to open Spotlight.
  • Type Terminal and press Enter to open another window.
cd ~/Desktop/my-3d-home
node test-lamp.js

What does this command do?

The node test-lamp.js command runs the adapter test with your active config.json settings.

Windows

  • Run the adapter test in a third PowerShell window with these commands:
  • Press the Windows key to open search.
  • Type PowerShell and press Enter to open another window.
cd ~/Desktop/my-3d-home
node test-lamp.js

What does this command do?

The node test-lamp.js command runs the adapter test with your active config.json settings.

You should see Turning the lamp on. followed by Turning the lamp off. and Test complete..

The simulated page should change to yellow ON before returning to grey OFF. A selected physical bulb should light before going dark.

That is your first working device loop. One shared adapter has now controlled the bulb path you selected.

Did the lamp test fail?

  • For the simulator path, confirm the second command window is still running node bulb.js.
  • For a Hue link-button problem, press the bridge button before running the temporary helper again.
  • For a Hue certificate problem, confirm only the dedicated https.Agent uses rejectUnauthorized: false.
  • For a Home Assistant authentication problem, replace the token carefully without sharing it.
  • For a Home Assistant connection problem, confirm whether your installation uses port 80 or 8123.

Ask for help with the failing path by using help me diagnose why test-lamp.js cannot control my selected bulb.

Compare your generated files with the complete working versions before moving on.

✔️ My Lamp Test Works

Great. Keep config.json private and leave node bulb.js running if you selected the simulator.

ⓧ I'd Like to Double Check the Full Code

Compare the structure of these files with your project. Keep your real device values in config.json if you selected Hue or Home Assistant.

const http = require('node:http');

let lightState = { on: { on: false } };

function sendJson(response, statusCode, value) {
  response.writeHead(statusCode, { 'Content-Type': 'application/json' });
  response.end(JSON.stringify(value));
}

function readJson(request) {
  return new Promise((resolve, reject) => {
    let body = '';

    request.on('data', (chunk) => {
      body += chunk;
    });

    request.on('end', () => {
      try {
        resolve(body ? JSON.parse(body) : {});
      } catch (error) {
        reject(error);
      }
    });
  });
}

const simulatorPage = `<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Simulated Bulb</title>
  <style>
    body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #111827; color: white; font-family: system-ui, sans-serif; }
    main { text-align: center; }
    #bulb { width: 180px; height: 180px; margin: 0 auto 24px; border-radius: 50%; background: #6b7280; box-shadow: 0 0 30px transparent; transition: 200ms ease; }
    #bulb.on { background: #ffd166; box-shadow: 0 0 80px #ffd166; }
    #state { font-size: 56px; font-weight: 800; letter-spacing: 0.12em; }
  </style>
</head>
<body>
  <main>
    <div id="bulb" aria-hidden="true"></div>
    <div id="state">OFF</div>
  </main>
  <script>
    async function refresh() {
      const response = await fetch('/light');
      const state = await response.json();
      const on = state.on.on;
      document.querySelector('#bulb').classList.toggle('on', on);
      document.querySelector('#state').textContent = on ? 'ON' : 'OFF';
    }

    refresh();
    setInterval(refresh, 1000);
  </script>
</body>
</html>`;

const server = http.createServer(async (request, response) => {
  try {
    if (request.method === 'GET' && request.url === '/') {
      response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
      response.end(simulatorPage);
      return;
    }

    if (request.method === 'GET' && request.url === '/light') {
      sendJson(response, 200, lightState);
      return;
    }

    if (request.method === 'PUT' && request.url === '/light') {
      const nextState = await readJson(request);

      if (!nextState.on || typeof nextState.on.on !== 'boolean') {
        sendJson(response, 400, { error: 'Expected {"on":{"on":true}} or false.' });
        return;
      }

      lightState = { on: { on: nextState.on.on } };
      sendJson(response, 200, lightState);
      return;
    }

    sendJson(response, 404, { error: 'Not found' });
  } catch (error) {
    sendJson(response, 500, { error: error.message });
  }
});

server.listen(4001, '127.0.0.1', () => {
  console.log('Simulated bulb: http://localhost:4001');
});
{
  "type": "fake",
  "fake": {
    "baseUrl": "http://127.0.0.1:4001"
  },
  "hue": {
    "bridgeIp": "your-bridge-ip",
    "applicationKey": "your-hue-application-key",
    "lightId": "your-light-id"
  },
  "homeAssistant": {
    "baseUrl": "http://homeassistant.local:8123",
    "token": "your-long-lived-access-token",
    "entityId": "light.your_light"
  }
}
const fs = require('node:fs');
const http = require('node:http');
const https = require('node:https');

// This relaxed TLS agent is scoped only to local Hue Bridge requests.
const hueAgent = new https.Agent({ rejectUnauthorized: false });

function loadConfig() {
  return JSON.parse(fs.readFileSync('config.json', 'utf8'));
}

function requestJson(url, options = {}, value) {
  return new Promise((resolve, reject) => {
    const body = value === undefined ? undefined : JSON.stringify(value);
    const transport = url.startsWith('https:') ? https : http;
    const headers = { ...(options.headers || {}) };

    if (body !== undefined) {
      headers['Content-Type'] = 'application/json';
    }

    const request = transport.request(
      url,
      {
        method: options.method || 'GET',
        headers,
        agent: options.agent
      },
      (response) => {
        let responseBody = '';

        response.on('data', (chunk) => {
          responseBody += chunk;
        });

        response.on('end', () => {
          let parsed = {};

          try {
            parsed = responseBody ? JSON.parse(responseBody) : {};
          } catch (error) {
            reject(new Error(`Invalid JSON response: ${responseBody}`));
            return;
          }

          if (response.statusCode < 200 || response.statusCode >= 300) {
            reject(new Error(`Request failed with ${response.statusCode}: ${responseBody}`));
            return;
          }

          resolve(parsed);
        });
      }
    );

    request.on('error', reject);
    request.end(body);
  });
}

async function getLamp() {
  const config = loadConfig();

  if (config.type === 'fake') {
    const state = await requestJson(`${config.fake.baseUrl}/light`);
    return state.on.on;
  }

  if (config.type === 'hue') {
    const state = await requestJson(
      `https://${config.hue.bridgeIp}/clip/v2/resource/light/${config.hue.lightId}`,
      {
        headers: { 'hue-application-key': config.hue.applicationKey },
        agent: hueAgent
      }
    );
    return state.data[0].on.on;
  }

  if (config.type === 'home-assistant') {
    const state = await requestJson(
      `${config.homeAssistant.baseUrl}/api/states/${config.homeAssistant.entityId}`,
      {
        headers: { Authorization: `Bearer ${config.homeAssistant.token}` }
      }
    );
    return state.state === 'on';
  }

  throw new Error(`Unknown lamp type: ${config.type}`);
}

async function setLamp(on) {
  const config = loadConfig();

  if (config.type === 'fake') {
    await requestJson(
      `${config.fake.baseUrl}/light`,
      { method: 'PUT' },
      { on: { on } }
    );
    return on;
  }

  if (config.type === 'hue') {
    await requestJson(
      `https://${config.hue.bridgeIp}/clip/v2/resource/light/${config.hue.lightId}`,
      {
        method: 'PUT',
        headers: { 'hue-application-key': config.hue.applicationKey },
        agent: hueAgent
      },
      { on: { on } }
    );
    return on;
  }

  if (config.type === 'home-assistant') {
    const action = on ? 'turn_on' : 'turn_off';
    await requestJson(
      `${config.homeAssistant.baseUrl}/api/services/light/${action}`,
      {
        method: 'POST',
        headers: { Authorization: `Bearer ${config.homeAssistant.token}` }
      },
      { entity_id: config.homeAssistant.entityId }
    );
    return on;
  }

  throw new Error(`Unknown lamp type: ${config.type}`);
}

module.exports = { getLamp, setLamp };
const { setLamp } = require('./lamp');

function wait(milliseconds) {
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
}

async function run() {
  console.log('Turning the lamp on.');
  await setLamp(true);
  await wait(3000);
  console.log('Turning the lamp off.');
  await setLamp(false);
  console.log('Test complete.');
}

run().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Your bulb now responds through one shared server-side interface. Next up, you will build the 3D room that sits in front of it.

Build the 3D Room

Your bulb adapter already proved that code can switch the selected light. Now you need a place where someone can see the smart home taking shape.

This step gives your working bulb a visual home that you can inspect in the browser.

In this step, get ready to:
  • Create a furnished 3D room that responds when you drag the view.
  • Create a local server that serves the room through the bulb adapter.
  • Run the room to establish its dragging and lamp-clicking behavior.
Create the visible room

A browser needs a scene before it can display your smart home. An import map loads three.js directly from its pinned web address.

The OrbitControls helper turns pointer drags into camera movement. Simple geometry supplies the room and its furniture.

  • Ask Claude Code to create index.html with the prompt below:
  • Switch back to Claude Code from the previous step.
  • Select the prompt field at the bottom of the window.
  • Paste the prompt below.
  • Press Enter.
Create index.html as one readable file with all styles inside it. Use three.js 0.187.0 from jsDelivr through an import map. Map three to https://cdn.jsdelivr.net/npm/three@0.187.0/build/three.module.js and three/addons/ to https://cdn.jsdelivr.net/npm/three@0.187.0/examples/jsm/. Import OrbitControls from three/addons/controls/OrbitControls.js. Build a dark room from simple geometry with a floor, two walls, sofa, table, and a floor-lamp group named lamp. Add OrbitControls so dragging orbits the camera. Keep the lamp off and do not add click handling yet. Do not use a bundler, npm package for three, or style.css.

What does this prompt do?

  • The prompt keeps the page structure and styles together in index.html.
  • The import map loads the pinned 3D modules without adding another build tool.
  • The group named lamp gives the floor lamp one shared object for later interaction.

You should see Claude Code create index.html. The file contains the inline-styled room requested in the prompt.

Create the same-origin server

The browser page needs a local HTTP API to reach the bulb adapter. Same-origin requests keep the browser on port 4000 while server.js talks to the selected device.

  • Ask Claude Code to create server.js with the prompt below:
  • Return to the Claude Code prompt field.
  • Paste the prompt below.
  • Press Enter.
Create readable, commented server.js using only node:http and node:fs. Listen on 127.0.0.1 port 4000. GET / must serve index.html. GET /lamp must call getLamp() and return {"on":true} or false. POST /lamp/toggle must read the current state, call setLamp with the opposite state, and return the new state. Add no CORS headers because index.html and these routes share one origin. Print http://localhost:4000 when the server is ready.

What does this prompt do?

  • The GET / route serves the 3D page from index.html.
  • The GET /lamp route reads the selected bulb through getLamp().
  • The POST /lamp/toggle route reverses the current state through setLamp().
  • The local server keeps device credentials outside the browser-facing file.

You should see Claude Code create server.js. The file serves the room from 127.0.0.1:4000.

Run the room outside Claude Code

Before the first run, Claude can inspect the browser boundary. This catches a leaked credential or public server binding before the page starts.

  • Ask Claude Code to review the two new files with the prompt below:
  • Return to the Claude Code prompt field.
  • Paste the review prompt below.
  • Press Enter.
Review index.html and server.js without running them. Confirm that index.html contains no Hue key, Home Assistant token, or direct smart-home URL, and that server.js listens on 127.0.0.1:4000. Do not run node server.js.

What does this review check?

Claude checks that index.html talks only to its own local routes. It also checks that the server accepts connections only from your computer.

You should see Claude confirm that the page contains no device credentials. Claude should also confirm that the server binds to 127.0.0.1:4000.

Before you run the server, do you think the room will load as a flat page or as a draggable 3D scene?

  • Start the local room server from ~/Desktop/my-3d-home by running these commands in command window 3:
cd ~/Desktop/my-3d-home
node server.js

What does this command do?

The cd command returns the window to your project folder. The node command asks Node.js to start server.js.

You should see 3D home: http://localhost:4000 in command window 3. Keep this server running while you test the room.

You should see a dark furnished room with two walls. The sofa and table should sit beside the floor lamp.

  • Drag inside the 3D room to test the camera controls.
  • Place your pointer over the room.
  • Hold the primary mouse button.
  • Move the pointer across the room.
  • Release the mouse button.

You should see the camera orbit around the furniture. The room stays in view from each angle.

Before you test the floor lamp, do you think it already responds to a short click?

  • Click the floor lamp once to test its current behavior.
  • Move your pointer over the floor lamp.
  • Press the primary mouse button without dragging.
  • Release the mouse button.

You should see no visible change when you click the lamp. That quiet click is the intended baseline for the room.

Room page blank?

  • Check command window 3 for the first reported error.
  • Open your browser's developer console if the page remains blank.
  • Stop an older server with Control+C if you see EADDRINUSE.
  • Serve the page through server.js instead of double-clicking index.html.

help me debug my local 3D room without exposing device credentials.

✔️ My room is running

Great work. Your furnished room now runs from its local server with a camera you can orbit.

ⓧ I'd like to double check the full code

The complete cumulative versions of your two new files are below.

const fs = require('node:fs');
const http = require('node:http');
const { getLamp, setLamp } = require('./lamp');

function sendJson(response, statusCode, value) {
  response.writeHead(statusCode, { 'Content-Type': 'application/json' });
  response.end(JSON.stringify(value));
}

const server = http.createServer(async (request, response) => {
  try {
    if (request.method === 'GET' && request.url === '/') {
      const page = fs.readFileSync('index.html', 'utf8');
      response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
      response.end(page);
      return;
    }

    if (request.method === 'GET' && request.url === '/lamp') {
      sendJson(response, 200, { on: await getLamp() });
      return;
    }

    if (request.method === 'POST' && request.url === '/lamp/toggle') {
      const nextState = !(await getLamp());
      await setLamp(nextState);
      sendJson(response, 200, { on: nextState });
      return;
    }

    sendJson(response, 404, { error: 'Not found' });
  } catch (error) {
    sendJson(response, 500, { error: error.message });
  }
});

server.listen(4000, '127.0.0.1', () => {
  console.log('3D home: http://localhost:4000');
});
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>My 3D Home</title>
  <style>
    html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; background: #09111f; font-family: system-ui, sans-serif; }
    #app { width: 100%; height: 100%; }
    #hud { position: fixed; inset: 14px 14px auto 14px; z-index: 2; display: flex; justify-content: space-between; color: white; pointer-events: none; }
    #title { font-weight: 750; }
    canvas { display: block; }
  </style>
  <script type="importmap">
    {
      "imports": {
        "three": "https://cdn.jsdelivr.net/npm/three@0.187.0/build/three.module.js",
        "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.187.0/examples/jsm/"
      }
    }
  </script>
</head>
<body>
  <div id="app"></div>
  <div id="hud">
    <div id="title">My 3D Home</div>
  </div>

  <script type="module">
    import * as THREE from 'three';
    import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

    const container = document.querySelector('#app');
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x09111f);

    const camera = new THREE.PerspectiveCamera(48, innerWidth / innerHeight, 0.1, 100);
    camera.position.set(7, 5, 8);

    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
    renderer.setSize(innerWidth, innerHeight);
    renderer.shadowMap.enabled = true;
    container.appendChild(renderer.domElement);

    const controls = new OrbitControls(camera, renderer.domElement);
    controls.target.set(0, 1.2, 0);
    controls.enableDamping = true;
    controls.minDistance = 5;
    controls.maxDistance = 14;

    scene.add(new THREE.AmbientLight(0x8aa0c8, 0.42));

    function box(name, size, position, colour) {
      const mesh = new THREE.Mesh(
        new THREE.BoxGeometry(...size),
        new THREE.MeshStandardMaterial({ color: colour, roughness: 0.8 })
      );
      mesh.name = name;
      mesh.position.set(...position);
      mesh.receiveShadow = true;
      mesh.castShadow = true;
      scene.add(mesh);
      return mesh;
    }

    box('floor', [8, 0.2, 6], [0, -0.1, 0], 0x263449);
    box('back-wall', [8, 3.2, 0.15], [0, 1.6, -3], 0x35445c);
    box('left-wall', [0.15, 3.2, 6], [-4, 1.6, 0], 0x2d3b50);
    box('sofa-seat', [3.1, 0.55, 1.25], [-1.1, 0.48, -1.8], 0x44607d);
    box('sofa-back', [3.1, 1.0, 0.35], [-1.1, 1.05, -2.25], 0x44607d);
    box('table-top', [1.7, 0.18, 1.0], [0.3, 0.75, 0.7], 0x7a5540);
    box('table-leg', [0.18, 0.75, 0.18], [0.3, 0.37, 0.7], 0x533929);

    const lamp = new THREE.Group();
    lamp.name = 'lamp';
    lamp.position.set(2.6, 0, -1.8);
    scene.add(lamp);

    const darkMetal = new THREE.MeshStandardMaterial({ color: 0x252b35, metalness: 0.7, roughness: 0.35 });
    const base = new THREE.Mesh(new THREE.CylinderGeometry(0.45, 0.55, 0.16, 32), darkMetal);
    base.position.y = 0.08;
    lamp.add(base);

    const pole = new THREE.Mesh(new THREE.CylinderGeometry(0.06, 0.06, 2.4, 20), darkMetal);
    pole.position.y = 1.3;
    lamp.add(pole);

    const shade = new THREE.Mesh(
      new THREE.ConeGeometry(0.62, 0.8, 32, 1, true),
      new THREE.MeshStandardMaterial({ color: 0xc9a66b, side: THREE.DoubleSide, roughness: 0.9 })
    );
    shade.position.y = 2.55;
    lamp.add(shade);

    addEventListener('resize', () => {
      camera.aspect = innerWidth / innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(innerWidth, innerHeight);
    });

    renderer.setAnimationLoop(() => {
      controls.update();
      renderer.render(scene, camera);
    });
  </script>
</body>
</html>

Your visual home is live with a draggable camera. Next up, you will turn the floor lamp into a control for the selected bulb.

Connect the 3D Lamp

Your draggable room is running through the local server. The lamp still behaves like scenery.

This step connects the 3D lamp to the existing HTTP API for two-way bulb control.

In this step, get ready to:
  • Add raycast clicking so a short lamp click toggles the bulb while dragging still orbits the camera.
  • Make the 3D bulb glow while its point light illuminates the room.
  • Synchronize outside bulb changes with the 3D lamp within two seconds.
Add raycast clicking

Raycasting lets three.js project the pointer through the camera into the scene. Movement below 5 pixels counts as a click while larger movement stays with OrbitControls.

  • Ask Claude Code to update index.html with THREE.Raycaster plus normalized pointer coordinates. Require each mesh inside lamp to receive userData.isLampPart. Require a short click to call POST /lamp/toggle. Preserve pointer drags for OrbitControls. Show the pointer cursor only over the lamp.
  • Refresh the 3D room in your browser.
  • Move your pointer over the floor lamp.

You should see the cursor change to a pointer only while it is over the lamp.

  • Click the floor lamp once.

You should see the selected bulb change state through the existing local route.

  • Drag inside the room to orbit the camera.

You should see the camera move without another bulb toggle.

Light the room from the lamp

An emissive material makes the bulb surface appear bright. A point light casts that warm colour onto nearby furniture.

  • Ask Claude Code to update index.html so bulbMaterial uses THREE.MeshStandardMaterial with an emissive colour. Require a THREE.PointLight inside lamp. Set the emissive colour to warm yellow while the lamp is on. Set lampLight.intensity to 24 while on. Set the emissive colour to black while off. Set the intensity to 0 while off.
  • Refresh the 3D room in your browser.
  • Click the 3D lamp once to switch it to the opposite state.

You should see the selected bulb change state.

  • Click the 3D lamp again to switch it on.

You should see the 3D bulb glow warm yellow. You should also see warm light fall across the nearby furniture.

Synchronize external changes

State synchronization keeps the room accurate when the bulb changes somewhere else. Polling the local route every two seconds gives the page a fresh server-side state without exposing device credentials.

  • Ask Claude Code to update index.html with showLamp, syncLamp, and toggleLamp. Require syncLamp to call GET /lamp immediately. Repeat that call every two seconds. Require showLamp to update the emissive colour. Require it to update the point light intensity. Require it to show the exact status word ON or OFF. Keep every browser request on the page's own origin.
  • Refresh the 3D room in your browser.

Why poll the local route?

The page reads GET /lamp from its own origin. The Hue key or Home Assistant token stays in config.json on the server side.

This keeps index.html independent of the selected bulb path. The browser never needs to contact Hue, Home Assistant, or port 4001 directly.

Before the final checks, predict what the room will show after the bulb changes outside the 3D page.

Simulated bulb

  • Return to the separate command window used for test-lamp.js.
  • Rerun the lamp test from earlier.

During the three-second on phase, you should see the simulator and 3D room change to ON. Both should return to OFF when the test finishes.

Philips Hue

  • Use the Philips Hue app to switch the selected light off.

Within two seconds, you should see the 3D lamp go dark. Its status should change to OFF.

Home Assistant

  • Use Home Assistant to switch the selected light off.

Within two seconds, you should see the 3D lamp go dark. Its status should change to OFF.

  • Click the 3D lamp once after the selected bulb reaches its off state.

You should see the selected bulb turn on. The 3D bulb should glow with the exact status ON.

Lamp state not staying synchronized?

Confirm that syncLamp requests GET /lamp immediately. Check that its interval is set to 2000 milliseconds.

If clicking changes the bulb without updating the room, confirm that toggleLamp passes the returned on value into showLamp.

help me debug synchronization between GET /lamp and the three.js lamp

✔️ Awesome, I've got everything!

Great. Double check that Claude Code saved index.html before moving on.

ⓧ I'd like to double check the full code

Compare your index.html with this complete version.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>My 3D Home</title>
  <style>
    html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; background: #09111f; font-family: system-ui, sans-serif; }
    #app { width: 100%; height: 100%; }
    #hud { position: fixed; inset: 14px 14px auto 14px; z-index: 2; display: flex; justify-content: space-between; color: white; pointer-events: none; }
    #title { font-weight: 750; }
    #status { padding: 6px 10px; border-radius: 999px; background: rgba(15, 23, 42, 0.8); font-weight: 800; letter-spacing: 0.08em; }
    #hint { position: fixed; left: 14px; bottom: 12px; z-index: 2; color: #cbd5e1; font-size: 12px; pointer-events: none; }
    canvas { display: block; }
  </style>
  <script type="importmap">
    {
      "imports": {
        "three": "https://cdn.jsdelivr.net/npm/three@0.187.0/build/three.module.js",
        "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.187.0/examples/jsm/"
      }
    }
  </script>
</head>
<body>
  <div id="app"></div>
  <div id="hud">
    <div id="title">My 3D Home</div>
    <div id="status">OFF</div>
  </div>
  <div id="hint">Drag to look around. Click the lamp to switch it.</div>

  <script type="module">
    import * as THREE from 'three';
    import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

    const container = document.querySelector('#app');
    const status = document.querySelector('#status');
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x09111f);

    const camera = new THREE.PerspectiveCamera(48, innerWidth / innerHeight, 0.1, 100);
    camera.position.set(7, 5, 8);

    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
    renderer.setSize(innerWidth, innerHeight);
    renderer.shadowMap.enabled = true;
    container.appendChild(renderer.domElement);

    const controls = new OrbitControls(camera, renderer.domElement);
    controls.target.set(0, 1.2, 0);
    controls.enableDamping = true;
    controls.minDistance = 5;
    controls.maxDistance = 14;

    scene.add(new THREE.AmbientLight(0x8aa0c8, 0.42));

    function box(name, size, position, colour) {
      const mesh = new THREE.Mesh(
        new THREE.BoxGeometry(...size),
        new THREE.MeshStandardMaterial({ color: colour, roughness: 0.8 })
      );
      mesh.name = name;
      mesh.position.set(...position);
      mesh.receiveShadow = true;
      mesh.castShadow = true;
      scene.add(mesh);
      return mesh;
    }

    box('floor', [8, 0.2, 6], [0, -0.1, 0], 0x263449);
    box('back-wall', [8, 3.2, 0.15], [0, 1.6, -3], 0x35445c);
    box('left-wall', [0.15, 3.2, 6], [-4, 1.6, 0], 0x2d3b50);
    box('sofa-seat', [3.1, 0.55, 1.25], [-1.1, 0.48, -1.8], 0x44607d);
    box('sofa-back', [3.1, 1.0, 0.35], [-1.1, 1.05, -2.25], 0x44607d);
    box('table-top', [1.7, 0.18, 1.0], [0.3, 0.75, 0.7], 0x7a5540);
    box('table-leg', [0.18, 0.75, 0.18], [0.3, 0.37, 0.7], 0x533929);

    const lamp = new THREE.Group();
    lamp.name = 'lamp';
    lamp.position.set(2.6, 0, -1.8);
    scene.add(lamp);

    const darkMetal = new THREE.MeshStandardMaterial({ color: 0x252b35, metalness: 0.7, roughness: 0.35 });
    const base = new THREE.Mesh(new THREE.CylinderGeometry(0.45, 0.55, 0.16, 32), darkMetal);
    base.position.y = 0.08;
    lamp.add(base);

    const pole = new THREE.Mesh(new THREE.CylinderGeometry(0.06, 0.06, 2.4, 20), darkMetal);
    pole.position.y = 1.3;
    lamp.add(pole);

    const shade = new THREE.Mesh(
      new THREE.ConeGeometry(0.62, 0.8, 32, 1, true),
      new THREE.MeshStandardMaterial({ color: 0xc9a66b, side: THREE.DoubleSide, roughness: 0.9 })
    );
    shade.position.y = 2.55;
    lamp.add(shade);

    const bulbMaterial = new THREE.MeshStandardMaterial({
      color: 0xf8e7bd,
      emissive: 0x000000,
      emissiveIntensity: 1.5
    });
    const bulb = new THREE.Mesh(new THREE.SphereGeometry(0.22, 24, 16), bulbMaterial);
    bulb.position.y = 2.45;
    lamp.add(bulb);

    const lampLight = new THREE.PointLight(0xffbf69, 0, 7, 2);
    lampLight.position.y = 2.4;
    lampLight.castShadow = true;
    lamp.add(lampLight);

    lamp.traverse((object) => {
      if (object.isMesh) object.userData.isLampPart = true;
    });

    const raycaster = new THREE.Raycaster();
    const pointer = new THREE.Vector2();
    let pointerDown = null;

    function lampHit(event) {
      const rect = renderer.domElement.getBoundingClientRect();
      pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
      pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
      raycaster.setFromCamera(pointer, camera);
      return raycaster.intersectObject(lamp, true).some((hit) => hit.object.userData.isLampPart);
    }

    function showLamp(on) {
      bulbMaterial.emissive.setHex(on ? 0xffa62b : 0x000000);
      lampLight.intensity = on ? 24 : 0;
      status.textContent = on ? 'ON' : 'OFF';
      status.style.color = on ? '#ffd166' : '#e5e7eb';
    }

    async function syncLamp() {
      const response = await fetch('/lamp');
      const state = await response.json();
      showLamp(state.on);
    }

    async function toggleLamp() {
      const response = await fetch('/lamp/toggle', { method: 'POST' });
      const state = await response.json();
      showLamp(state.on);
    }

    renderer.domElement.addEventListener('pointerdown', (event) => {
      pointerDown = { x: event.clientX, y: event.clientY };
    });

    renderer.domElement.addEventListener('pointerup', async (event) => {
      if (!pointerDown) return;
      const movement = Math.hypot(event.clientX - pointerDown.x, event.clientY - pointerDown.y);
      pointerDown = null;
      if (movement < 5 && lampHit(event)) await toggleLamp();
    });

    renderer.domElement.addEventListener('pointermove', (event) => {
      renderer.domElement.style.cursor = lampHit(event) ? 'pointer' : 'grab';
    });

    addEventListener('resize', () => {
      camera.aspect = innerWidth / innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(innerWidth, innerHeight);
    });

    renderer.setAnimationLoop(() => {
      controls.update();
      renderer.render(scene, camera);
    });

    syncLamp().catch(console.error);
    setInterval(() => syncLamp().catch(console.error), 2000);
  </script>
</body>
</html>

That connection is live: your 3D lamp and selected bulb now move as one. Next, you will place the room behind a persistent desktop icon.

Launch the Tray App

Your 3D room already controls the selected bulb from a synchronized browser page. The final handoff uses Electron to place that room behind a persistent desktop icon.

The synchronized room still hides in a browser tab, so this step packages it behind one persistent desktop icon.

In this step, get ready to:
  • Pin Electron 45.4.1 with menubar 9.5.3. npm creates node_modules and package-lock.json.
  • Create main.js. It starts the local server and generates the platform tray icon.
  • Launch the desktop app. Its tray icon opens a 480 by 360 room that still controls the selected bulb.
Pin the desktop dependencies

A package manifest gives npm one fixed dependency set for the desktop app. Exact versions keep every installation aligned with the code you are about to run.

  • In Claude Code, create package.json with this exact content:
{
  "name": "my-3d-home",
  "version": "1.0.0",
  "description": "A local 3D lamp controller",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "dependencies": {
    "menubar": "9.5.3"
  },
  "devDependencies": {
    "electron": "45.4.1"
  }
}

What does this code do?

  • The main field tells Electron to begin with main.js.
  • The start script gives npm one command for launching the desktop app.
  • The dependencies pin menubar to 9.5.3.
  • The development dependencies pin Electron to 45.4.1.
  • Press Cmd+Space on macOS or the Windows key on Windows to open system search.
  • Type Terminal on macOS or PowerShell on Windows.
  • Press Enter to open a new command window.
  • Install the pinned dependencies from my-3d-home by running these commands in the new command window:
cd ~/Desktop/my-3d-home
npm install

What does this command do?

The first line returns the command window to your existing project folder. The second line installs the packages listed in package.json.

npm stores the installed dependency tree in node_modules. It records the resolved package versions in package-lock.json.

You should see installation output in the command window. You should also see node_modules and package-lock.json inside my-3d-home.

Good, the desktop dependencies are now locked to the versions this tray shell expects.

Install not completing?

  • Confirm the command window is inside ~/Desktop/my-3d-home before retrying the installation.
  • Confirm package.json matches the code above if npm reports a problem reading the package manifest.

Ask for help to fix the dependency installation in my-3d-home.

Connect the server to the tray

The desktop shell owns the local server process and the tray window. It also generates the correct icon file for the learner's operating system when the app starts.

  • In Claude Code, create main.js from the complete reference in the double-check tab below.

You should see main.js inside my-3d-home.

How the tray shell works

Requiring server.js starts the same local server inside Electron. The tray window loads http://127.0.0.1:4000 from that process.

The platform icon function writes lampTemplate.png on macOS. It writes lamp.ico on Windows.

Use these tabs to confirm both desktop files match the finished project before you launch them.

✔️ Awesome, I've got everything!

Great. Confirm that Claude Code saved both package.json and main.js inside my-3d-home.

ⓧ I'd like to double check the full code

Your complete package.json should look like this.

{
  "name": "my-3d-home",
  "version": "1.0.0",
  "description": "A local 3D lamp controller",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "dependencies": {
    "menubar": "9.5.3"
  },
  "devDependencies": {
    "electron": "45.4.1"
  }
}

What does this file control?

This manifest fixes the desktop entry point and launch script. It also keeps both desktop packages on the required versions.

Your complete main.js should look like this.

const fs = require('node:fs');
const { Buffer } = require('node:buffer');
const { nativeImage } = require('electron');
const { menubar } = require('menubar');

// Starting server.js in this process avoids a second background Node process.
require('./server');

function makeLampImage() {
  const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
      <path fill="#111111" d="M24 6h16l8 20H16L24 6zm6 20h4v22h10v6H20v-6h10V26z"/>
    </svg>`;

  const dataUrl = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
  return nativeImage.createFromDataURL(dataUrl);
}

function wrapPngAsIco(png) {
  const header = Buffer.alloc(22);

  header.writeUInt16LE(0, 0);       // Reserved.
  header.writeUInt16LE(1, 2);       // ICO file type.
  header.writeUInt16LE(1, 4);       // One image.
  header[6] = 32;                   // Width.
  header[7] = 32;                   // Height.
  header.writeUInt16LE(1, 10);      // Colour planes.
  header.writeUInt16LE(32, 12);     // Bits per pixel.
  header.writeUInt32LE(png.length, 14);
  header.writeUInt32LE(22, 18);     // PNG data offset.

  return Buffer.concat([header, png]);
}

function createPlatformIcon() {
  const source = makeLampImage();

  if (process.platform === 'darwin') {
    const macImage = source.resize({ width: 16, height: 16 });
    macImage.setTemplateImage(true);
    fs.writeFileSync('lampTemplate.png', macImage.toPNG());
    return 'lampTemplate.png';
  }

  const windowsImage = source.resize({ width: 32, height: 32 });
  fs.writeFileSync('lamp.ico', wrapPngAsIco(windowsImage.toPNG()));
  return 'lamp.ico';
}

const menuApp = menubar({
  index: 'http://127.0.0.1:4000',
  icon: createPlatformIcon(),
  tooltip: 'My 3D Home',
  preloadWindow: true,
  browserWindow: {
    width: 480,
    height: 360,
    resizable: false,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false
    }
  }
});

menuApp.on('ready', () => {
  console.log('My 3D Home is ready in the menu bar or system tray.');
});

What does this file control?

The file starts server.js inside the Electron process. It generates one platform-specific icon before creating the tray window.

The browser window is fixed at 480 by 360. Its web preferences keep Node.js APIs outside the browser-facing page.

Hand off the local server

Only one process can own 127.0.0.1:4000 at a time. Electron now starts that server itself, so the standalone process from earlier must release the address first.

  • In the command window where server.js is running, press Control+C to stop the standalone server.

The standalone server process should end. The command prompt should return in that window.

  • Ask Claude Code to review main.js, package.json, and server.js without running them.

Claude Code should confirm that the Electron process starts the only server on 127.0.0.1:4000. It should also confirm the platform icon and secure tray window settings.

Before you run the app, where do you expect the room to appear after the browser tab is no longer the main entry point?

  • Start the tray app from my-3d-home by running these commands:
cd ~/Desktop/my-3d-home
npm start

What does this command do?

The first line returns to the existing project folder. The second line runs the start script from package.json.

Electron loads main.js. That file starts the local server before creating the menu bar or system tray app.

On macOS, you should see lampTemplate.png appear in the project folder. On Windows, you should see lamp.ico.

You should also see a lamp icon in the macOS menu bar or Windows system tray.

That completes the browser-to-desktop handoff. Your local controller now lives behind one persistent icon.

  • Select the lamp icon to open the tray window.
  • On macOS, find the lamp icon in the menu bar at the top of the screen.
  • On Windows, find the lamp icon in the system tray at the bottom-right of the screen.
  • On Windows 11, select the ^ button if the lamp icon is inside the tray overflow.

You should see the synchronized 3D room inside a 480 by 360 non-resizable window.

  • Click the 3D floor lamp with a short press.
  • Keep the pointer still during the click so the app treats it as a lamp selection instead of an orbit drag.

The selected bulb should switch state. The 3D lamp should update its glow and exact ON or OFF status at the same time.

Tray app not opening correctly?

  • If the command output mentions EADDRINUSE, return to the standalone server window and press Control+C.
  • If the icon is missing on Windows 11, check the tray overflow under the ^ button.
  • If the fake bulb does not switch, confirm the simulator process from earlier is still running.

Ask for help to debug my Electron tray app without exposing anything from config.json.

Secret mission

Add Three Lighting Scenes

Turn the binary lamp switch into three useful lighting scenes. Bright, Cozy, and Movie will synchronize the selected bulb with the 3D room at 100%, 40%, and 10% brightness.

Clean Up Your Resources

Clean Up Your Resources

This project creates no paid cloud resources. Your existing Claude plan remains a separate subscription.

Your bulb requests stay on your local network. Choose whether to keep your resources running, pause them to come back later, or delete them entirely.

Resources you used:

  • The ~/Desktop/my-3d-home folder containing your source files and bulb configuration.
  • The npm dependencies inside node_modules and the dependency record in package-lock.json.
  • The local bulb simulator and tray app processes.
  • The runtime tray icon stored as lampTemplate.png on macOS or lamp.ico on Windows.

Keep everything running

No action is needed. Choose this if you are still testing scenes or want your controller available from the menu bar or system tray.

  • Your project files and npm dependencies remain inside ~/Desktop/my-3d-home.
  • Your local bulb simulator remains available if you selected the simulated path.
  • Your tray app continues to control Bright, Cozy, and Movie scenes while its project processes are running.

Pause - I'll come back to this later

Stop the local processes to free their ports and close the tray app. Your project files remain ready for another session.

  • Switch to each Terminal or PowerShell window running part of the project.
  • Press Ctrl+C in each window.

You should see the tray icon disappear. The simulated bulb page also stops responding if you used that path.

  • Keep the ~/Desktop/my-3d-home folder so you can restart the simulator and tray app using the commands from the project.

Delete - I don't want to use this again

Deleting the folder is permanent, so copy anything you want to keep first. This removes the source files, npm dependencies, local configuration, and generated tray icon.

  • Switch to each Terminal or PowerShell window running part of the project.
  • Press Ctrl+C in each window.
  • Open your Home Assistant profile if you created a long-lived access token for this project.
  • Select Security in your Home Assistant profile.
  • Revoke the long-lived access token created for this project.
  • Revoke the Philips Hue application key created for my-3d-home through your bridge's developer credential controls if you used the Hue path.

macOS

  • Move to your Desktop and delete the my-3d-home folder by running these commands:
cd ~/Desktop
rm -rf my-3d-home
What Do These Commands Do?
  • The first command moves your terminal to the Desktop.
  • The second command permanently removes my-3d-home and everything inside it.
  • Confirm that the folder is gone by running:
ls
What Does This Command Do?

This command lists the items remaining on your Desktop.

You should no longer see my-3d-home in the output.

Windows

  • Move to your Desktop and delete the my-3d-home folder by running these commands:
cd ~/Desktop
rmdir /s /q my-3d-home
What Do These Commands Do?
  • The first command moves PowerShell to the Desktop.
  • The second command permanently removes my-3d-home and everything inside it.
  • Confirm that the folder is gone by running:
ls
What Does This Command Do?

This command lists the items remaining on your Desktop.

You should no longer see my-3d-home in the output.

Nice Work!

Nice Work!

You made it! You built a synchronized 3D smart home with Electron that opens from the Mac menu bar or Windows system tray.

You've learned how to:

  • Build a simulated bulb with visible ON and OFF states. Unify it with Philips Hue and Home Assistant through the shared getLamp() and setLamp(on) adapter.
  • Protect device credentials behind a local HTTP API served by Node.js. Use raycasting and state synchronization to connect a three.js lamp to the selected bulb.
  • Package the room as a desktop tray app with Electron and menubar. Run the same interface from a Mac menu bar icon or Windows system tray icon.
  • Secret Mission: Add Bright, Cozy, and Movie scenes that synchronize bulb brightness with the 3D room at 100%, 40%, and 10%.

Ready to quiz yourself?