# openclaw-companion

Adopt this skill: https://proskills.md/skills/other/l-lesteryu-openclaw-companion

Page: https://proskills.md/skills/other/l-lesteryu-openclaw-companion
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 5964
sha: b3b4b0e8d6ce0eb56c16431853b39bba41e3c437
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/SKILL.md

````text
---
name: openclaw-companion
description: 龙虾伴侣 - 实时推送工作状态到桌面龙虾悬浮窗，并通过语音播报 session 日志
metadata: {"openclaw": {"emoji": "🦞", "always": true}}
---

# OpenClaw Companion Skill

## 描述
与桌面龙虾助手联动，实时推送 OpenClaw 工作状态，并通过 TTS 语音播报 session 日志。

## 自动化状态推送（Plugin Hook）

**推荐方式：** 已通过 `openclaw-companion-hook` 插件实现自动化。

插件会在每次工具调用后自动推送到龙虾，无需手动调用 `pushState`。插件功能：
- 监听 `after_tool_call` hook，自动捕获所有工具调用
- 根据工具类型映射为对应的龙虾状态、emoji 和文案
- 2 秒节流，同类工具合并，避免频繁推送
- `agent_end` 时自动推送 `done` 状态
- `message_received` 时自动推送 `idle` 状态

### 自动状态映射表

| 工具 | 龙虾状态 | Emoji | 文案示例 |
|------|---------|-------|---------|
| `read` | working | 📖 | "读取 config.json" |
| `write` | working | ✏️ | "写入 main.js" |
| `edit` | working | 🔧 | "修改 index.html" |
| `exec` | working | ⌨️ | "执行 npm..." |
| `web_fetch` | working | 🔍 | "访问 github.com" |
| `browser` | working | 🌐 | "浏览 example.com" |
| `tts` | working | 🔊 | "语音播报中..." |
| `message` | working | 💬 | "发送消息中..." |
| `sessions_spawn` | working | 🦞 | "派出助手~" |
| 其他工具 | working | 💻 | "处理中..." |
| agent 结束 | done | ✅ | "搞定啦！" |
| 收到消息 | idle | 📨 | "收到新消息" |

### Plugin 安装

插件位于 `~/.openclaw/extensions/openclaw-companion-hook/`，已在 `openclaw.json` 中启用。

管理命令：
```bash
openclaw plugins list          # 查看插件状态
openclaw plugins disable openclaw-companion-hook   # 禁用
openclaw plugins enable openclaw-companion-hook    # 启用
```

---

## 手动状态推送（备选/调试用）

Plugin 已自动处理大部分状态推送。以下手动命令仅在特殊场景或调试时使用。

### API 端点
- `POST http://localhost:18182/api/state` — 状态推送
- `GET http://localhost:18182/api/health` — 健康检查

有效状态：`idle` | `working` | `thinking` | `sleeping` | `done` | `error`

### POST /api/state 参数

```json
{
  "state": "working",       // 必填：状态名
  "message": "读取文件",     // 可选：气泡文案
  "emoji": "📖",            // 可选：覆盖默认 emoji
  "toolName": "read",       // 可选：工具名称（供动画扩展）
  "priority": "normal"      // 可选：high/normal/low
}
```

所有新增参数（`emoji`/`toolName`/`priority`）均为可选，不传则使用默认值。保持向后兼容。

### 命令

#### pushState(state, message?, emoji?, toolName?)

推送状态到龙虾。

```bash
# 基础用法
timeout 3 curl -s -X POST http://localhost:18182/api/state \
  -H "Content-Type: application/json" \
  -d '{"state":"working","message":"正在处理..."}'

# 带 emoji 和 toolName
timeout 3 curl -s -X POST http://localhost:18182/api/state \
  -H "Content-Type: application/json" \
  -d '{"state":"working","message":"读取 config.json","emoji":"📖","toolName":"read"}'
```

#### checkHealth()

检查龙虾是否存活。

```bash
timeout 3 curl -s http://localhost:18182/api/health
```

#### launchLobster()

启动龙虾程序。

```bash
cd ~/.openclaw/skills/openclaw-companion && nohup npx electron . --no-sandbox > /dev/null 2>&1 &
```

#### ensureLobster()

先健康检查，未运行则拉起。

---

## 核心功能：语音播报 Session 日志

### 工作原理
当 OpenClaw 正在工作时（派出子agent、执行任务等），通过 `tts` 工具将关键日志信息**语音播报**出来，让用户不用盯着屏幕也能了解进展。

### 播报时机与规则

**必须播报的事件：**
| 事件 | 播报内容示例 | 龙虾状态 |
|------|------------|---------|
| 派出子agent | "已派出XX助手处理任务" | working |
| 子agent完成 | "XX助手已完成任务，结果是..." | done |
| 子agent出错/超时 | "XX助手遇到了一些问题" | error |
| 收到用户消息 | "收到新消息" | idle |
| 重要工具调用结果 | "XX操作已完成" | done |

**不播报的事件：**
- 心跳轮询（HEARTBEAT_OK）
- 日常检查（无重要变化的）
- 重复性状态更新（避免刷屏）
- 内部系统事件

### 播报内容生成规则

1. **精简摘要** — 从 subagent 返回结果中提取关键信息（1-2句话）
2. **角色称呼** — 用友好的称呼（"开发助手"、"测试助手"、"文档助手"等）
3. **结果导向** — 重点说"做了什么"和"结果如何"，省略中间细节
4. **语气自然** — 用口语化表达，像在跟用户聊天

### 播报实现

使用 `tts` 工具进行语音播报：
```
调用 tts 工具，text 参数为播报文案
播报完成后回复 NO_REPLY（避免重复文字消息）
```

---

## 手动推送状态映射（无 Plugin 时）

| OpenClaw 场景 | 龙虾状态 | 气泡文案 | 是否播报 |
|--------------|---------|---------|---------|
| 收到用户消息 | idle | （消息前10字） | ✅ "收到新消息" |
| 开始处理请求 | working | "正在处理..." | ❌ |
| 派出子agent | working | "派出{角色}助手~" | ✅ 播报 |
| 子agent完成 | done | "搞定！" | ✅ 播报摘要 |
| 子agent出错/超时 | error | "出了点问题..." | ✅ 播报 |
| 心跳轮询 | — | 不推送 | ❌ |
| 用户离开（>5分钟） | sleeping | "zzZ..." | ❌ |

---

## 龙虾程序位置
`~/.openclaw/skills/openclaw-companion/`

## 注意事项
- 推送失败时静默处理，不要因龙虾挂了影响主流程
- TTS 播报失败时也静默处理
- 气泡文案要简短（<20字），TTS 播报文案控制在 1-2 句话
- 所有 curl 调用使用 `timeout 3` 防止阻塞
- 避免短时间内连续播报（间隔至少 3 秒）
````

## File: README.md
size: 10554
sha: 7b5b917d0114cdf5146d92c885ae7953dc899f5c
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/README.md

````text
# 🦞 OpenClaw Companion

[![OpenClaw Skill](https://img.shields.io/badge/OpenClaw-Skill-ff6b35?style=flat-square&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgd2lkdGg9IjE0IiBoZWlnaHQ9IjE0Ij48dGV4dCB5PSIxOCIgZm9udC1zaXplPSIxNiI+🦞PC90ZXh0Pjwvc3ZnPg==)](https://github.com/openclaw/openclaw)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Electron](https://img.shields.io/badge/Electron-339933?style=flat-square&logo=electron&logoColor=white)](https://www.electronjs.org/)

一个基于 Electron 的可爱龙虾桌面宠物，专为 [OpenClaw](https://openclaw.com) 设计的 Agent Skill。当你的 AI Agent 在工作时，龙虾会在桌面上实时展示工作状态，并通过语音播报关键进展——让你不用盯着屏幕也能掌握一切。

---

## ✨ 功能特性

| 功能 | 说明 |
|------|------|
| 🦞 **Q版可爱龙虾** | 手绘的红色龙虾，支持 6 种状态动画 |
| 🖥️ **桌面悬浮窗** | 无边框透明窗口，始终置顶，可拖拽、可缩放 |
| 🔔 **系统托盘** | 最小化到托盘，随时唤出 |
| 📡 **HTTP API** | 本地 API 端点，接收外部状态推送 |
| 💬 **语音气泡** | 根据状态显示不同的气泡文案和 Emoji |
| 🔊 **语音播报** | 通过 TTS 语音播报子 Agent 派出、完成、出错等关键事件 |
| 🤖 **OpenClaw 集成** | 作为 Skill 安装后，自动推送 OpenClaw 工作状态 |
| 🔌 **Plugin Hook** | 内置 `openclaw-companion-hook` 插件，全自动化状态推送 |

## 🎭 支持的状态

| 状态 | Emoji | 含义 | 触发场景 |
|------|-------|------|---------|
| `idle` | 📨 | 空闲 | 收到用户消息 |
| `working` | ⌨️ | 工作中 | 文件读写、执行命令、浏览网页等 |
| `thinking` | 🤔 | 思考中 | Agent 分析推理 |
| `sleeping` | 💤 | 休眠中 | 用户长时间离开 |
| `done` | ✅ | 完成 | 任务完成 |
| `error` | ❌ | 出错 | 任务执行失败 |

---

## 🛠️ 技术栈

- **[Electron](https://www.electronjs.org/)** — 跨平台桌面应用框架
- **Canvas 2D** — 纯手绘龙虾形象与动画，零外部依赖
- **[Express](https://expressjs.com/)** — 本地 HTTP API 服务器
- **Node.js** — 运行时环境

---

## 📦 安装

### 前置要求

- **Node.js** >= 18
- **npm**
- **桌面环境**（显示 GUI 窗口）：Linux 需要 X11 或 Wayland，macOS/Windows 无额外要求
- **服务器/无头环境**：需通过 X11 Forwarding（`ssh -X`）或虚拟帧缓冲（`xvfb`）提供显示服务

### 作为 OpenClaw Skill 安装

> ⚠️ 当前版本尚未发布到 ClawHub，请使用手动安装方式。

```bash
# 手动克隆到 skills 目录
cd ~/.openclaw/skills
git clone https://github.com/L-LesterYu/openclaw-companion.git
cd openclaw-companion
npm install
```

### 国内网络环境

国内网络环境下，`npm install` 和 Electron 二进制下载可能超时或失败，建议使用镜像源：

```bash
# 使用淘宝镜像安装依赖
cd ~/.openclaw/skills/openclaw-companion
npm install --registry=https://registry.npmmirror.com

# 使用 Electron 国内镜像安装二进制（如果首次安装失败）
ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/ npm install electron
```

如果 Electron 启动时报 `Electron failed to install correctly`，说明二进制文件下载不完整，执行以下命令修复：

```bash
# 删除损坏的 Electron 缓存
rm -rf node_modules/electron

# 使用国内镜像重新安装（--force 确保重新下载）
ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/ npm install electron --force

# 验证安装是否成功（应显示 dist 目录列表）
ls node_modules/electron/dist/
```

> 💡 如果仍然失败，可以尝试清理 npm 缓存后重试：`npm cache clean --force`

### Plugin Hook 安装（自动状态推送）

插件会在每次工具调用后自动推送到龙虾，无需手动调用。安装步骤：

```bash
# 1. 将插件复制到 OpenClaw extensions 目录
cp -r ~/.openclaw/skills/openclaw-companion/plugin-hook ~/.openclaw/extensions/openclaw-companion-hook

# 2. 在 openclaw.json 中启用插件（如果尚未配置）
# 确保 plugins.entries 中包含：
# "openclaw-companion-hook": { "enabled": true }

# 3. 重启 Gateway 加载插件
openclaw gateway restart

# 4. 验证插件状态
openclaw plugins list  # 查看 openclaw-companion-hook 是否为 loaded
```

#### Plugin Hook 事件说明

| Hook 事件 | 龙虾状态 | Emoji | 说明 |
|-----------|---------|-------|------|
| `message_received` | idle | 📨 | 收到用户消息 |
| `after_tool_call` | working | 📖/⌨️/🔧 等 | 10 种工具自动映射不同 emoji |
| `agent_end` | done / error | ✅ / ❌ | Agent 执行结束 |
| `subagent_spawned` | working | 🦞 | 派出子 Agent |
| `subagent_ended` | done / error | ✅ / ❌ | 子 Agent 完成/出错 |
| `gateway_start` | idle | 🦞 | 启动时健康检查 |

#### Plugin Hook 配置项

在 `openclaw.json` 的 `plugins.entries.openclaw-companion-hook.config` 中可自定义：

```json
{
  "apiUrl": "http://localhost:18182/api/state",
  "healthUrl": "http://localhost:18182/api/health",
  "throttleMs": 2000,
  "idleTimeoutMs": 300000,
  "enabled": true
}
```

| 参数 | 默认值 | 说明 |
|------|--------|------|
| `apiUrl` | `http://localhost:18182/api/state` | 状态推送 API 端点 |
| `healthUrl` | `http://localhost:18182/api/health` | 健康检查 URL |
| `throttleMs` | `2000` | 连续推送最小间隔（毫秒），防止刷屏 |
| `idleTimeoutMs` | `300000` | 空闲多久后进入休眠状态（默认 5 分钟） |
| `enabled` | `true` | 总开关，设为 false 可禁用推送 |

---

## 🎮 使用方法

### 启动龙虾

```bash
cd ~/.openclaw/skills/openclaw-companion
npx electron . --no-sandbox
```

> 💡 `--no-sandbox` 参数在 Linux 服务器环境下通常必须，避免 Chromium 沙箱权限问题。macOS/Windows 桌面环境可省略。启动时如果看到 `Exiting GPU process due to errors during initialization` 警告，属于正常现象，不影响功能。

### 推送状态（手动/调试用）

> Plugin Hook 已自动处理大部分状态推送，以下命令仅在特殊场景或调试时使用。

```bash
# 推送工作状态
curl -X POST http://localhost:18182/api/state \
  -H "Content-Type: application/json" \
  -d '{"state":"working","message":"正在处理...","emoji":"⌨️"}'

# 健康检查
curl http://localhost:18182/api/health
```

### API 端点

| 方法 | 路径 | 说明 |
|------|------|------|
| `POST` | `http://localhost:18182/api/state` | 推送状态变更 |
| `GET` | `http://localhost:18182/api/health` | 健康检查 |

**POST `/api/state` 参数：**

```json
{
  "state": "working",    // 必填：idle | working | thinking | sleeping | done | error
  "message": "读取文件",  // 可选：气泡文案（建议 <20 字）
  "emoji": "📖",         // 可选：覆盖默认 emoji
  "toolName": "read",    // 可选：工具名称（供动画扩展）
  "priority": "normal"   // 可选：high | normal | low
}
```

---

## 🔊 语音播报

配合 OpenClaw 的 TTS 工具，龙虾 companion 可以语音播报关键事件：

| 事件 | 播报内容示例 | 是否播报 |
|------|------------|---------|
| 派出子 agent | "已派出开发助手处理任务" | ✅ |
| 子 agent 完成 | "开发助手已完成，结果正常" | ✅ |
| 子 agent 出错 | "测试助手遇到了一些问题" | ✅ |
| 收到用户消息 | "收到新消息" | ✅ |
| 心跳轮询 | — | ❌ |

---

## 📁 项目结构

```
openclaw-companion/
├── index.html          # 主界面（Canvas 渲染）
├── main.js             # Electron 主进程 + Express 服务器
├── preload.js          # 预加载脚本
├── package.json        # 依赖配置
├── SKILL.md            # OpenClaw Skill 描述文件
├── LICENSE             # MIT 许可证
├── sprites/            # 龙虾各状态 PNG 精灵图
│   ├── lobster_waiting_*.png
│   ├── lobster_working_*.png
│   ├── lobster_eating_*.png
│   ├── lobster_coding_done.png
│   ├── lobster_coding_error_1_1.png
│   └── lobster_sleepy_bubbles_*.png
└── plugin-hook/        # OpenClaw Plugin Hook（自动状态推送）
    ├── openclaw.plugin.json   # 插件清单
    ├── package.json           # 包配置
    └── index.js               # Hook 核心逻辑
```

---

## ❓ 常见问题

<details>
<summary><b>Q: 启动时报 <code>Electron failed to install correctly</code></b></summary>

Electron 二进制未完整下载。删除后重新安装：

```bash
cd ~/.openclaw/skills/openclaw-companion
rm -rf node_modules/electron
ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/ npm install electron
```

</details>

<details>
<summary><b>Q: <code>npm install</code> 卡住不动</b></summary>

网络问题导致依赖下载超时。切换到国内镜像：

```bash
npm install --registry=https://registry.npmmirror.com
```

</details>

<details>
<summary><b>Q: 启动时出现 GPU 相关错误</b></summary>

服务器环境通常没有 GPU 加速，这是预期行为，不影响龙虾功能。可忽略。

</details>

<details>
<summary><b>Q: 服务器没有显示器，如何使用？</b></summary>

龙虾是一个桌面 GUI 应用，需要显示服务。以下方案可选：

- **X11 Forwarding**：`ssh -X user@server`，启动后窗口会转发到本地
- **Xvfb 虚拟帧缓冲**：`xvfb-run npx electron . --no-sandbox`
- **VNC / 远程桌面**：安装 VNC 服务后在远程桌面中启动

</details>

<details>
<summary><b>Q: Plugin Hook 提示加载失败或找不到</b></summary>

确保插件已正确安装到 `~/.openclaw/extensions/openclaw-companion-hook/`，并在 `openclaw.json` 中启用了 `openclaw-companion-hook`。安装步骤见上方 [Plugin Hook 安装](#plugin-hook-安装自动状态推送) 章节。没有该插件时，龙虾仍可通过手动 API 调用正常工作。

</details>

---

## 🤝 贡献

欢迎提交 Issue 和 Pull Request！

1. Fork 本仓库
2. 创建特性分支：`git checkout -b feature/amazing-feature`
3. 提交更改：`git commit -m 'Add amazing feature'`
4. 推送分支：`git push origin feature/amazing-feature`
5. 提交 Pull Request

---

## 📄 License

[MIT](LICENSE) © 2025 L-LesterYu

---

<p align="center">
  Made with 🦞 for <a href="https://openclaw.com">OpenClaw</a>
</p>
````

## File: .gitignore
size: 51
sha: e2932b29151f9b9d91233065668ef45edb9fe048
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/.gitignore

```text
node_modules/
.DS_Store
Thumbs.db
*.log
dist/
out/
```

## File: index.html
size: 21102
sha: f2bd13e8827502fff67e95f77d97266f1289eb7b
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/index.html

```text
<!--
 * 🦞 AI项目经理 · 龙虾工作室 v1.0.1 (Canvas 2D · 悬浮窗版)
 * 纯 Canvas 2D API，无外部依赖
 * Electron 悬浮窗模式：无边框、透明、始终置顶
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🦞 龙虾助手</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'PingFang SC','Microsoft YaHei','Noto Sans SC',sans-serif;background:transparent !important;overflow:hidden;user-select:none;width:100vw;height:100vh}
.canvas-wrapper{width:100%;height:100%;position:relative;display:flex;align-items:center;justify-content:center}
#scene-canvas{width:100%;height:100%;display:block;cursor:default}
.status-bubble{position:absolute;top:16px;left:50%;transform:translateX(-50%);background:rgba(255,255,255,.92);backdrop-filter:blur(8px);padding:10px 24px;border-radius:24px;box-shadow:0 4px 20px rgba(0,0,0,.1);font-size:15px;color:#555;font-weight:600;z-index:5;transition:all .4s ease;max-width:400px;text-align:center}
.status-bubble .se{font-size:20px;margin-right:6px}
.status-bubble .st{color:#333}
.lobster-thought-bubble{position:absolute;pointer-events:none;z-index:15;display:flex;flex-direction:column;align-items:center;transition:opacity .4s;opacity:0;transform:translate(-50%,-100%) scale(0)}
.lobster-thought-bubble.visible{opacity:1;animation:bIn .4s cubic-bezier(.34,1.56,.64,1) forwards}
.lobster-thought-bubble.hiding{opacity:0;animation:bOut .3s ease forwards}
@keyframes bIn{from{transform:translate(-50%,-100%) scale(0);opacity:0}to{transform:translate(-50%,-100%) scale(1);opacity:1}}
@keyframes bOut{from{transform:translate(-50%,-100%) scale(1);opacity:1}to{transform:translate(-50%,-100%) scale(.5);opacity:0}}
.thought-bubble-content{background:rgba(255,255,255,.95);backdrop-filter:blur(6px);border-radius:16px;padding:8px 16px;box-shadow:0 4px 16px rgba(0,0,0,.12);font-size:14px;color:#444;font-weight:600;white-space:nowrap;max-width:220px;overflow:hidden;text-overflow:ellipsis}
.thought-bubble-tail{width:0;height:0;border-left:8px solid transparent;border-right:8px solid transparent;border-top:10px solid rgba(255,255,255,.95);margin-top:-2px}
.transition-flash{position:absolute;top:0;left:0;right:0;bottom:0;pointer-events:none;z-index:12;opacity:0}
.transition-flash.active{animation:fA .3s ease-out forwards}
@keyframes fA{0%{opacity:.15}100%{opacity:0}}
.tf-done{background:#ffd700}.tf-error{background:#ff4444}.tf-normal{background:#fff}
</style>
</head>
<body>
<div class="canvas-wrapper">
  <canvas id="scene-canvas"></canvas>
  <div class="status-bubble" id="statusBubble"><span class="se" id="sEmoji">🌊</span><span class="st" id="sText">发呆中...</span></div>
  <div class="lobster-thought-bubble" id="thoughtBubble"><div class="thought-bubble-content" id="thoughtText"></div><div class="thought-bubble-tail"></div></div>
  <div class="transition-flash" id="tFlash"></div>
</div>
<script>
(function(){
'use strict';

// ===== Canvas Setup =====
var canvas = document.getElementById('scene-canvas');
var ctx = canvas.getContext('2d');
var W, H, dpr = Math.min(window.devicePixelRatio || 1, 2);

function resize() {
  var wr = canvas.parentElement;
  W = wr.clientWidth; H = wr.clientHeight;
  canvas.width = W * dpr; canvas.height = H * dpr;
  canvas.style.width = W + 'px'; canvas.style.height = H + 'px';
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
window.addEventListener('resize', resize);
resize();

// ===== State =====
var state = 'idle', stateTime = 0, gTime = 0;
var customEmoji = null;
var interactCount = 0;
var lobsterX = 0, lobsterY = 0;

// ===== Sprite Loader =====
var sprites = {};
var workingSprites = {};
var eatingSprites = [];   // 3 frames: idle-eating
var sleepySprites = [];   // 3 frames: sleeping, idle-napping, idle-bubbling
var waitingSprites = [];  // 3 frames: idle-dazing, thinking

function loadFrame(arr, src) {
  var img = new Image();
  img.src = src;
  arr.push(img);
}

function loadSprites() {
  // Single-frame: done, error
  var singleMap = { 'done': 'lobster_coding_done', 'error': 'lobster_coding_error_1_1' };
  for (var name in singleMap) {
    var img = new Image();
    img.src = 'sprites/' + singleMap[name] + '.png';
    sprites[name] = img;
  }
  // Multi-frame: eating (3), sleepy (3), waiting (3)
  for (var i = 1; i <= 3; i++) {
    loadFrame(eatingSprites,  'sprites/lobster_eating_' + i + '_1.png');
    loadFrame(sleepySprites,  'sprites/lobster_sleepy_bubbles_' + i + '_1.png');
    loadFrame(waitingSprites, 'sprites/lobster_waiting_' + i + '_1.png');
  }
  // Working sequence frames
  var wk = ['starting', 'claws_up', 'mixed', 'typing_down'];
  var wkFiles = ['lobster_working_starting_1', 'lobster_working_claws_up_1',
                  'lobster_working_mixed_action_1', 'lobster_working_typing_down_1'];
  for (var j = 0; j < wk.length; j++) {
    var img = new Image();
    img.src = 'sprites/' + wkFiles[j] + '.png';
    workingSprites[wk[j]] = img;
  }
}
loadSprites();

// Cached working loop frames (avoid per-frame array allocation)
var workingLoopFrames = [workingSprites.claws_up, workingSprites.mixed, workingSprites.typing_down];

var idleSubs = ['eating','dazing','napping','bubbling'], idleIdx = 0, idleTimer = 0;
var particles = [];
var thoughtTimer = 0, thoughtTarget = 12 + Math.random() * 8, snoreTimer = 0, bubbleTimer = 0;

// ===== Cached DOM refs =====
var elEmoji = document.getElementById('sEmoji');
var elText  = document.getElementById('sText');
var elFlash = document.getElementById('tFlash');
var elThought = document.getElementById('thoughtBubble');
var elThoughtTxt = document.getElementById('thoughtText');

// ===== Status Texts =====
var statusInfo = {
  idle:     { emoji: '🌊', texts: ['发呆中...', '打瞌睡...', '吹泡泡~'] },
  working:  { emoji: '💻', texts: ['努力工作中...', '正在写代码...', '专注开发中...'] },
  sleeping: { emoji: '😴', texts: ['呼呼大睡...', '做美梦中...', 'Zzz...'] },
  thinking: { emoji: '🤔', texts: ['思考中...', '让我想想...', '头脑风暴中...'] },
  done:     { emoji: '🎉', texts: ['搞定啦！', '任务完成！', '太棒了！'] },
  error:    { emoji: '💥', texts: ['哎呀出错啦！', '需要修复...', '呜呜...'] }
};

function setStatus() {
  var info = statusInfo[state];
  elEmoji.textContent = customEmoji || info.emoji;
  var idx = state === 'idle' ? idleIdx : Math.floor(gTime * 0.3) % info.texts.length;
  elText.textContent = info.texts[idx];
}

// ===== Audio Engine =====
var aCtx = null;
function ac() { if (!aCtx) aCtx = new (window.AudioContext || window.webkitAudioContext)(); return aCtx; }

function snd(type) {
  try {
    var c = ac(), t = c.currentTime, o = c.createOscillator(), g = c.createGain();
    o.connect(g); g.connect(c.destination);
    switch(type) {
      case 'success':
        o.type='sine'; o.frequency.setValueAtTime(523,t); o.frequency.setValueAtTime(659,t+.1); o.frequency.setValueAtTime(784,t+.2);
        g.gain.setValueAtTime(.15,t); g.gain.exponentialRampToValueAtTime(.001,t+.4);
        o.start(t); o.stop(t+.4); break;
      case 'error':
        o.type='sawtooth'; o.frequency.setValueAtTime(200,t); o.frequency.exponentialRampToValueAtTime(80,t+.3);
        g.gain.setValueAtTime(.1,t); g.gain.exponentialRampToValueAtTime(.001,t+.3);
        o.start(t); o.stop(t+.3); break;
      case 'pet':
        o.type='sine'; o.frequency.setValueAtTime(440,t); o.frequency.exponentialRampToValueAtTime(660,t+.15);
        g.gain.setValueAtTime(.12,t); g.gain.exponentialRampToValueAtTime(.001,t+.25);
        o.start(t); o.stop(t+.25); break;
      case 'transition':
        o.type='triangle'; o.frequency.setValueAtTime(300,t); o.frequency.exponentialRampToValueAtTime(600,t+.15);
        o.frequency.exponentialRampToValueAtTime(300,t+.3);
        g.gain.setValueAtTime(.1,t); g.gain.exponentialRampToValueAtTime(.001,t+.3);
        o.start(t); o.stop(t+.3); break;
      case 'achievement':
        o.type='sine'; o.frequency.setValueAtTime(523,t); o.frequency.setValueAtTime(659,t+.12);
        o.frequency.setValueAtTime(784,t+.24); o.frequency.setValueAtTime(1047,t+.36);
        g.gain.setValueAtTime(.15,t); g.gain.exponentialRampToValueAtTime(.001,t+.6);
        o.start(t); o.stop(t+.6); break;
      case 'snore':
        o.type='sine'; o.frequency.setValueAtTime(100,t); o.frequency.linearRampToValueAtTime(150,t+.3);
        o.frequency.linearRampToValueAtTime(80,t+.6);
        g.gain.setValueAtTime(.08,t); g.gain.exponentialRampToValueAtTime(.001,t+.6);
        o.start(t); o.stop(t+.6); break;
      case 'type':
        o.type='square'; o.frequency.setValueAtTime(1800,t);
        g.gain.setValueAtTime(.03,t); g.gain.exponentialRampToValueAtTime(.001,t+.03);
        o.start(t); o.stop(t+.03); break;
    }
  } catch(e) {}
}

// ===== Achievements =====
var ACHS = [
  { id:'first_click', name:'初次接触', icon:'👆', done:false },
  { id:'click_10', name:'人气王', icon:'🔥', done:false },
  { id:'click_50', name:'万人迷', icon:'💖', done:false },
  { id:'all_states', name:'百变龙虾', icon:'🎭', done:false }
];
var achDone = {}, visited = {};

function loadAch() {
  try {
    var d = JSON.parse(localStorage.getItem('lobster_ach') || '{}');
    for (var i = 0; i < ACHS.length; i++) if (d[ACHS[i].id]) { ACHS[i].done = true; achDone[ACHS[i].id] = true; }
    interactCount = d.ic || 0;
    visited = d.vs || {};
  } catch(e) {}
}
function saveAch() {
  try { localStorage.setItem('lobster_ach', JSON.stringify({ic: interactCount, vs: visited})); } catch(e) {}
}
function unlock(id) {
  if (achDone[id]) return;
  achDone[id] = true;
  for (var i = 0; i < ACHS.length; i++) if (ACHS[i].id === id) ACHS[i].done = true;
  snd('achievement');
  var a = ACHS.find(function(x) { return x.id === id; });
  for (var j = 0; j < 15; j++) addParticle(lobsterX + (Math.random()-.5)*120, lobsterY - 80, 'star');
  showThought(a.icon + ' ' + a.name + '!');
  updAchUI(); saveAch();
}
function checkAch() {
  if (interactCount >= 1) unlock('first_click');
  if (interactCount >= 10) unlock('click_10');
  if (interactCount >= 50) unlock('click_50');
  visited[state] = true;
  if (Object.keys(visited).length >= ACHS.length) unlock('all_states');
}
function updAchUI() {
  var c = 0; for (var i = 0; i < ACHS.length; i++) if (ACHS[i].done) c++;
  var el = document.getElementById('iAch');
  if (el) el.textContent = c + '/' + ACHS.length;
}
loadAch(); updAchUI();

// ===== Thought Bubble =====
var thoughtTimeout = null;

function showThought(txt) {
  elThoughtTxt.textContent = txt;
  elThought.className = 'lobster-thought-bubble visible';
  elThought.style.left = lobsterX + 'px';
  elThought.style.top = (lobsterY - 130) + 'px';
  if (thoughtTimeout) clearTimeout(thoughtTimeout);
  thoughtTimeout = setTimeout(function() {
    elThought.className = 'lobster-thought-bubble hiding';
  }, 2500);
}

var randomThoughts = ['今天也是元气满满的一天~','摸摸头~','加油鸭！','好吃好吃~','让我想想...','搞定了！','哎呀...','嘿嘿~','想吃海鲜~','代码写不完啦'];
function randomBubble() {
  showThought(randomThoughts[Math.floor(Math.random() * randomThoughts.length)]);
}

// ===== Transition Flash =====
function flash(type) {
  elFlash.className = 'transition-flash active tf-' + type;
  setTimeout(function() { elFlash.className = 'transition-flash'; }, 400);
}

// ===== Particle System =====
var CONFETTI_COLORS = ['#ff6b9d','#ffd700','#7c6cf0','#4caf50','#2196f3','#ff9800'];
var STAR_COLORS = ['#ffd700','#ffab00','#ff6d00'];

function addParticle(x, y, type) {
  var p = { x: x, y: y, life: 1, type: type };
  switch(type) {
    case 'zzz':
      p.vx = (Math.random()-.5)*0.5; p.vy = -0.5-Math.random()*0.5;
      p.decay = 0.005; p.size = 8+Math.random()*6; p.color = '#7c6cf0'; break;
    case 'heart':
      p.vx = (Math.random()-.5)*1.5; p.vy = -1.5-Math.random()*2;
      p.decay = 0.012; p.size = 6+Math.random()*6; p.color = '#ff6b9d'; break;
    case 'confetti':
      p.vx = (Math.random()-.5)*4; p.vy = -2-Math.random()*4;
      p.decay = 0.01; p.size = 3+Math.random()*4;
      p.color = CONFETTI_COLORS[Math.floor(Math.random()*6)];
      p.rot = Math.random()*Math.PI*2; p.rv = (Math.random()-.5)*0.2; break;
    case 'smoke':
      p.vx = (Math.random()-.5)*1; p.vy = -0.8-Math.random()*0.5;
      p.decay = 0.015; p.size = 5+Math.random()*8; p.color = '#999'; break;
    case 'star':
      p.vx = (Math.random()-.5)*3; p.vy = -1.5-Math.random()*2;
      p.decay = 0.015; p.size = 4+Math.random()*5;
      p.color = STAR_COLORS[Math.floor(Math.random()*3)]; break;
    case 'bubble':
      p.vx = (Math.random()-.5)*0.3; p.vy = -0.6-Math.random()*0.8;
      p.decay = 0.008; p.size = 3+Math.random()*6;
      p.color = 'rgba(135,206,250,0.6)'; break;
  }
  particles.push(p);
}

function updateParticles() {
  for (var i = particles.length - 1; i >= 0; i--) {
    var p = particles[i];
    p.x += p.vx; p.y += p.vy; p.life -= p.decay;
    if (p.type === 'confetti') { p.vy += 0.08; p.rot += p.rv; }
    if (p.type === 'smoke')    { p.size += 0.1; p.vx *= 0.99; }
    if (p.life <= 0) {
      // Swap-with-last for O(1) removal
      particles[i] = particles[particles.length - 1];
      particles.pop();
    }
  }
}

function drawHeart(x, y, s) {
  ctx.beginPath();
  ctx.moveTo(x, y + s*0.3);
  ctx.bezierCurveTo(x - s*0.5, y - s*0.3, x - s, y + s*0.1, x, y + s*0.8);
  ctx.bezierCurveTo(x + s, y + s*0.1, x + s*0.5, y - s*0.3, x, y + s*0.3);
  ctx.fill();
}

function drawStar(x, y, r) {
  ctx.beginPath();
  var DEG = Math.PI / 180;
  for (var i = 0; i < 5; i++) {
    var a1 = (i*72-90)*DEG, a2 = ((i*72+36)-90)*DEG;
    if (i === 0) ctx.moveTo(x + Math.cos(a1)*r, y + Math.sin(a1)*r);
    else ctx.lineTo(x + Math.cos(a1)*r, y + Math.sin(a1)*r);
    ctx.lineTo(x + Math.cos(a2)*r*0.4, y + Math.sin(a2)*r*0.4);
  }
  ctx.closePath(); ctx.fill();
}

function drawParticles() {
  for (var i = 0; i < particles.length; i++) {
    var p = particles[i];
    ctx.globalAlpha = Math.max(0, p.life);
    ctx.fillStyle = p.color;
    switch(p.type) {
      case 'heart': drawHeart(p.x, p.y, p.size); break;
      case 'zzz':
        ctx.font = Math.round(p.size*2.5) + 'px sans-serif';
        ctx.fillText('Z', p.x, p.y); break;
      case 'star': drawStar(p.x, p.y, p.size); break;
      case 'confetti':
        ctx.save(); ctx.translate(p.x, p.y); ctx.rotate(p.rot);
        ctx.fillRect(-p.size/2, -p.size/4, p.size, p.size/2);
        ctx.restore(); break;
      case 'bubble':
        ctx.strokeStyle = p.color; ctx.lineWidth = 1;
        ctx.beginPath(); ctx.arc(p.x, p.y, Math.max(0.5, p.size), 0, Math.PI*2); ctx.stroke();
        ctx.fillStyle = 'rgba(255,255,255,0.4)';
        ctx.beginPath(); ctx.arc(p.x - p.size*0.3, p.y - p.size*0.3, p.size*0.25, 0, Math.PI*2); ctx.fill();
        break;
      default:
        ctx.beginPath(); ctx.arc(p.x, p.y, Math.max(0.5, p.size), 0, Math.PI*2); ctx.fill();
    }
  }
  ctx.globalAlpha = 1;
}

// ===== Draw Lobster =====
function drawLobster(cx, cy) {
  lobsterX = cx; lobsterY = cy;

  // Select sprite
  var img;
  var idleFrame = Math.floor(gTime / 5) % 3;   // 15s per loop
  var otherFrame = Math.floor(gTime * 3) % 3;    // ~1s per loop

  if (state === 'idle') {
    var sub = idleSubs[idleIdx];
    if (sub === 'eating')              img = eatingSprites[idleFrame];
    else if (sub === 'napping' || sub === 'bubbling') img = sleepySprites[idleFrame];
    else if (sub === 'dazing')         img = waitingSprites[idleFrame];
  } else if (state === 'working') {
    if (stateTime < 0.4) {
      img = workingSprites.starting;
    } else {
      img = workingLoopFrames[Math.floor((stateTime - 0.4) / 0.2) % 3];
    }
  } else if (state === 'sleeping') {
    img = sleepySprites[otherFrame];
  } else if (state === 'thinking') {
    img = waitingSprites[otherFrame];
  } else {
    img = sprites[state]; // done, error — single frame
  }

  // Draw shadow
  ctx.fillStyle = 'rgba(0,0,0,0.06)';
  ctx.beginPath(); ctx.ellipse(cx, cy + 85, 65, 12, 0, 0, Math.PI*2); ctx.fill();

  // Draw sprite
  if (img && img.complete && img.naturalWidth > 0) {
    var drawSize = 200;
    ctx.drawImage(img, cx - drawSize/2, cy - drawSize*0.7, drawSize, drawSize);
  } else {
    // Loading placeholder
    ctx.fillStyle = '#e53935';
    ctx.beginPath(); ctx.arc(cx, cy, 40, 0, Math.PI*2); ctx.fill();
    ctx.fillStyle = '#fff';
    ctx.font = '14px sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText('加载中...', cx, cy + 5);
  }
}

// ===== State Management =====
function setState(newState, message, emoji) {
  var newEmoji = emoji || (statusInfo[newState] ? statusInfo[newState].emoji : '');
  if (newState === state && newEmoji === (customEmoji || statusInfo[state].emoji) && message === elText.textContent) return;
  state = newState;
  stateTime = 0;
  snd('transition');
  customEmoji = emoji || null;

  if (newState === 'done') flash('done');
  else if (newState === 'error') flash('error');
  else flash('normal');

  setStatus();
  if (message) elText.textContent = message;
  checkAch(); saveAch();

  if (newState === 'done') {
    for (var j = 0; j < 20; j++) addParticle(lobsterX + (Math.random()-.5)*150, lobsterY - 50, 'confetti');
    snd('success');
  }
  if (newState === 'error') {
    for (var j = 0; j < 10; j++) addParticle(lobsterX + (Math.random()-.5)*60, lobsterY + 60, 'smoke');
    snd('error');
  }
}

// ===== Mouse Events =====
function getCanvasPos(e) {
  var rect = canvas.getBoundingClientRect();
  return { x: e.clientX - rect.left, y: e.clientY - rect.top };
}

function isInLobster(mx, my) {
  var dx = mx - lobsterX, dy = my - lobsterY;
  return (dx*dx)/(75*75) + (dy*dy)/(110*110) < 1;
}

// ===== Window Drag =====
var isDragging = false, lastMouseX = 0, lastMouseY = 0;

canvas.addEventListener('mousedown', function(e) {
  isDragging = true;
  lastMouseX = e.screenX;
  lastMouseY = e.screenY;
  canvas.style.cursor = 'grabbing';
});

window.addEventListener('mousemove', function(e) {
  if (isDragging && window.lobsterAPI) {
    window.lobsterAPI.moveWindow(e.screenX - lastMouseX, e.screenY - lastMouseY);
    lastMouseX = e.screenX;
    lastMouseY = e.screenY;
  } else {
    canvas.style.cursor = isInLobster(e.clientX, e.clientY) ? 'pointer' : 'grab';
  }
});

window.addEventListener('mouseup', function() {
  isDragging = false;
  canvas.style.cursor = 'grab';
});

canvas.addEventListener('click', function(e) {
  var p = getCanvasPos(e);
  if (isInLobster(p.x, p.y)) {
    interactCount++;
    snd('pet');
    for (var i = 0; i < 8; i++) addParticle(lobsterX + (Math.random()-.5)*60, lobsterY - 40 + (Math.random()-.5)*40, 'heart');
    if (state === 'done' || state === 'error') setState('idle', null, null);
    checkAch(); saveAch();
  }
});

// ===== Scroll Zoom =====
canvas.addEventListener('wheel', function(e) {
  e.preventDefault();
  if (window.lobsterAPI) window.lobsterAPI.resizeWindow(e.deltaY > 0 ? -20 : 20);
}, { passive: false });

// ===== HTTP API state listener =====
if (window.lobsterAPI) {
  window.lobsterAPI.onStateChange(function(data) {
    setState(data.state, data.message, data.emoji);
  });
}

// ===== Idle Sub-state Rotation =====
function updateIdle(dt) {
  idleTimer += dt;
  if (idleTimer > 4) {
    idleTimer = 0;
    idleIdx = (idleIdx + 1) % idleSubs.length;
    setStatus();
  }
}

// ===== State Particles =====
function stateParticles(dt) {
  if (state === 'sleeping') {
    snoreTimer += dt;
    if (snoreTimer > 1.5) {
      snoreTimer = 0;
      addParticle(lobsterX + 30, lobsterY - 60, 'zzz');
      snd('snore');
    }
  }
  if (state === 'done' && Math.random() < 0.15) {
    addParticle(lobsterX + (Math.random()-.5)*200, lobsterY - 100, 'confetti');
  }
  if (state === 'error' && Math.random() < 0.08) {
    addParticle(lobsterX + (Math.random()-.5)*40, lobsterY + 50, 'smoke');
  }
  if (state === 'thinking' && Math.random() < 0.03) {
    addParticle(lobsterX + (Math.random()-.5)*20, lobsterY - 100, 'star');
  }
  if (state === 'idle' && idleIdx === 3) {
    bubbleTimer += dt;
    if (bubbleTimer > 0.6) {
      bubbleTimer = 0;
      addParticle(lobsterX + (Math.random()-.5)*10, lobsterY - 75, 'bubble');
    }
  }
}

// ===== Thought Timer =====
function updateThought(dt) {
  thoughtTimer += dt;
  if (thoughtTimer > thoughtTarget) {
    thoughtTimer = 0;
    thoughtTarget = 12 + Math.random() * 8;
    randomBubble();
  }
}

// ===== Main Loop =====
var lastT = performance.now();

function loop(now) {
  var dt = Math.min((now - lastT) / 1000, 0.1);
  lastT = now;
  gTime += dt;
  stateTime += dt;

  ctx.clearRect(0, 0, W, H);

  var cx = W / 2, cy = H / 2 + 20;

  if (state === 'idle') updateIdle(dt);
  stateParticles(dt);
  updateParticles();
  updateThought(dt);

  drawLobster(cx, cy);
  drawParticles();

  requestAnimationFrame(loop);
}

requestAnimationFrame(loop);

// Expose setState globally (debug/backward compat)
window.switchState = setState;

})();
</script>
</body>
</html>
```

## File: LICENSE
size: 1087
sha: 51beb7e99b33d9648d1988aaa53f5113439b8a43
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/LICENSE

```text
MIT License

Copyright (c) 2025 Lobster Companion Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

## File: main.js
size: 4770
sha: 03dca5b321e2b3886f86d7291d525f9eaac9e57f
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/main.js

```text
/**
 * 🦞 龙虾悬浮助手 — Electron 主进程
 * 功能：无边框透明悬浮窗 + 系统托盘 + 本地 HTTP API
 */
const { app, BrowserWindow, Tray, Menu, nativeImage, ipcMain, screen } = require('electron');
const express = require('express');
const path = require('path');
const fs = require('fs');

let mainWindow = null;
let tray = null;
const HTTP_PORT = 18182;

// ===== 单例锁 =====
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
  app.quit();
}

// ===== 创建悬浮窗 =====
function createWindow() {
  // 获取屏幕尺寸，计算居中位置
  const { width: screenW, height: screenH } = screen.getPrimaryDisplay().workAreaSize;
  const winW = 320, winH = 400;

  mainWindow = new BrowserWindow({
    width: winW,
    height: winH,
    minWidth: 200,
    minHeight: 250,
    maxWidth: 600,
    maxHeight: 750,
    x: Math.round(screenW - winW - 40),   // 默认右上角
    y: Math.round((screenH - winH) / 2),
    frame: false,           // 无边框
    transparent: true,       // 透明背景
    alwaysOnTop: true,       // 始终置顶
    skipTaskbar: true,       // 不显示在任务栏
    resizable: false,        // 禁止边框调整（用代码控制大小）
    hasShadow: false,        // 无阴影
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    }
  });

  mainWindow.loadFile('index.html');
  mainWindow.setVisibleOnAllWorkspaces(true);

  // 关闭窗口时隐藏而非退出
  mainWindow.on('close', (e) => {
    if (!app.isQuitting) {
      e.preventDefault();
      mainWindow.hide();
    }
  });

  mainWindow.on('closed', () => { mainWindow = null; });
}

// ===== 系统托盘 =====
function createTray() {
  // 尝试加载托盘图标，不存在则创建空图标
  let iconPath = path.join(__dirname, 'tray-icon.png');
  let icon;
  if (fs.existsSync(iconPath)) {
    icon = nativeImage.createFromPath(iconPath);
    // 确保图标尺寸合理
    if (icon.isEmpty()) icon = nativeImage.createEmpty();
  } else {
    icon = nativeImage.createEmpty();
  }

  tray = new Tray(icon);
  const contextMenu = Menu.buildFromTemplate([
    { label: '🦞 显示龙虾', click: () => mainWindow?.show() },
    { type: 'separator' },
    { label: '🚪 退出', click: () => { app.isQuitting = true; app.quit(); } }
  ]);
  tray.setToolTip('🦞 龙虾助手');
  tray.setContextMenu(contextMenu);
  tray.on('click', () => mainWindow?.show());
}

// ===== IPC 处理 =====
// 窗口拖拽
ipcMain.on('window-move', (event, { deltaX, deltaY }) => {
  if (mainWindow) {
    const [x, y] = mainWindow.getPosition();
    mainWindow.setPosition(x + deltaX, y + deltaY);
  }
});

// 窗口缩放
ipcMain.on('window-resize', (event, delta) => {
  if (mainWindow) {
    const [w, h] = mainWindow.getSize();
    const newW = Math.max(200, Math.min(600, w + delta));
    const newH = Math.max(250, Math.min(750, h + delta * 1.25));
    mainWindow.setSize(Math.round(newW), Math.round(newH));
  }
});

// 获取窗口位置（用于拖拽起点）
ipcMain.handle('window-position', () => {
  if (mainWindow) return mainWindow.getPosition();
  return [0, 0];
});

// ===== HTTP API 服务器 =====
function startHttpServer() {
  const expressApp = express();
  expressApp.use(express.json());

  // 接收状态变更（向后兼容：emoji/toolName/priority 均为可选）
  expressApp.post('/api/state', (req, res) => {
    const { state, message, emoji, toolName, priority } = req.body;
    const validStates = ['idle', 'working', 'thinking', 'sleeping', 'done', 'error'];
    if (validStates.includes(state)) {
      // 构建发送给渲染进程的数据，只传有效字段
      const payload = { state, message };
      if (emoji) payload.emoji = emoji;
      if (toolName) payload.toolName = toolName;
      if (priority) payload.priority = priority;
      mainWindow?.webContents.send('state-change', payload);
      res.json({ ok: true, lobsterState: state });
    } else {
      res.status(400).json({ ok: false, error: 'Invalid state' });
    }
  });

  // 健康检查
  expressApp.get('/api/health', (req, res) => {
    res.json({ alive: true, uptime: process.uptime() });
  });

  expressApp.listen(HTTP_PORT, '127.0.0.1', () => {
    console.log(`🦞 Lobster API server on http://localhost:${HTTP_PORT}`);
  });
}

// ===== App 生命周期 =====
app.whenReady().then(() => {
  createWindow();
  createTray();
  startHttpServer();
});

app.on('second-instance', () => {
  if (mainWindow) mainWindow.show();
});

app.on('window-all-closed', () => {
  // 不退出，保持托盘
});

// 他人尝试启动时，聚焦已有窗口
app.on('activate', () => {
  if (mainWindow) mainWindow.show();
});
```

## File: package-lock.json
size: 56845
sha: cb15c29ebf3d1dda7b3c052107cbe9283f22caa7
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/package-lock.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/package-lock.json

## File: package.json
size: 421
sha: b7b098521ca02202eab0c5bbb17c8e7aa617ae7c
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/package.json

```text
{
  "name": "openclaw-companion",
  "version": "1.0.0",
  "description": "🦞 OpenClaw Companion - Canvas 2D desktop pet for OpenClaw, built with Electron",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "dev": "electron ."
  },
  "dependencies": {
    "express": "^5.2.1"
  },
  "devDependencies": {
    "electron": "^33.4.11"
  },
  "author": "Lobster Companion Contributors",
  "license": "MIT"
}
```

## File: plugin-hook/index.js
size: 7780
sha: 6987b6389ee41c772bdde24cd025cec4c42db72e
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/plugin-hook/index.js

```text
/**
 * 🦞 Lobster Companion Hook
 *
 * Automatically pushes OpenClaw agent working status to the
 * Lobster Companion desktop pet via HTTP API.
 *
 * Hooked events:
 *   - after_tool_call  → "working" (with tool-specific emoji & message)
 *   - agent_end        → "done" / "error"
 *   - message_received → "idle"
 *   - subagent_spawned → "working" (subagent dispatched)
 *   - subagent_ended   → "done" / "error" (subagent result)
 */

const { definePluginEntry } = require("/usr/local/lib/node_modules/openclaw/dist/plugin-sdk/plugin-entry.js");

// ─── Tool → State Mapping ────────────────────────────────────────────

const TOOL_STATE_MAP = {
  read:           { state: "working",  emoji: "📖", label: "读取文件" },
  write:          { state: "working",  emoji: "✏️", label: "写入文件" },
  edit:           { state: "working",  emoji: "🔧", label: "修改文件" },
  exec:           { state: "working",  emoji: "⌨️", label: "执行命令" },
  web_fetch:      { state: "working",  emoji: "🔍", label: "访问网页" },
  web_search:     { state: "working",  emoji: "🔎", label: "搜索中" },
  browser:        { state: "working",  emoji: "🌐", label: "浏览网页" },
  tts:            { state: "working",  emoji: "🔊", label: "语音播报" },
  message:        { state: "working",  emoji: "💬", label: "发送消息" },
  sessions_spawn: { state: "working",  emoji: "🦞", label: "派出助手" },
};

const DEFAULT_TOOL_STATE = { state: "working", emoji: "💻", label: "处理中" };

// ─── Throttle & Idle Tracker ─────────────────────────────────────────

let lastPushTime = 0;
let idleTimer = null;

function resolveConfig(pluginConfig) {
  return {
    apiUrl:         (pluginConfig && pluginConfig.apiUrl) || "http://localhost:18182/api/state",
    healthUrl:      (pluginConfig && pluginConfig.healthUrl) || "http://localhost:18182/api/health",
    throttleMs:     (pluginConfig && pluginConfig.throttleMs) || 2000,
    idleTimeoutMs:  (pluginConfig && pluginConfig.idleTimeoutMs) || 300000,
    enabled:        (pluginConfig && pluginConfig.enabled) !== false,
  };
}

function now() { return Date.now(); }

function pushState(config, payload) {
  if (!config.enabled) return;

  const elapsed = now() - lastPushTime;
  if (elapsed < config.throttleMs && payload.priority !== "high") {
    return;
  }

  try {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 3000);

    fetch(config.apiUrl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
      signal: controller.signal,
    }).then(() => {
      clearTimeout(timeout);
      lastPushTime = now();
    }).catch(() => {
      clearTimeout(timeout);
    });
  } catch {
    // Silently ignore
  }
}

function resetIdleTimer(config) {
  if (idleTimer) clearTimeout(idleTimer);
  idleTimer = setTimeout(() => {
    pushState(config, { state: "sleeping", message: "zzZ...", emoji: "💤" });
  }, config.idleTimeoutMs);
}

// ─── Extract short description from tool params ─────────────────────

function extractToolDetail(toolName, params) {
  params = params || {};
  switch (toolName) {
    case "read":
    case "write":
    case "edit": {
      const p = params.path || params.file_path || "";
      return p.split("/").pop() || "";
    }
    case "exec": {
      const cmd = params.command || "";
      return cmd.length > 30 ? cmd.slice(0, 30) + "…" : cmd;
    }
    case "web_fetch": {
      const url = params.url || "";
      try { return new URL(url).hostname; } catch { return url.slice(0, 20); }
    }
    case "web_search": {
      const q = params.query || "";
      return q.length > 20 ? q.slice(0, 20) + "…" : q;
    }
    default:
      return "";
  }
}

// ─── Plugin Entry ────────────────────────────────────────────────────

module.exports = definePluginEntry({
  id: "openclaw-companion-hook",
  name: "Lobster Companion Hook",
  description: "Automatically pushes agent working status to the Lobster Companion desktop pet",

  register(api) {
    const config = resolveConfig(api.pluginConfig);
    const logger = api.logger;

    logger.info("🦞 Lobster Companion Hook registered");

    // ── after_tool_call ──
    api.on("after_tool_call", (event, _ctx) => {
      const toolName = event.toolName;

      // Skip heartbeat-internal tools
      if (toolName === "sessions_list" || toolName === "sessions_history" || toolName === "sessions_send") {
        return;
      }

      const mapping = TOOL_STATE_MAP[toolName] || DEFAULT_TOOL_STATE;
      const detail = extractToolDetail(toolName, event.params);
      const message = detail ? `${mapping.label} ${detail}` : mapping.label;

      pushState(config, {
        state: mapping.state,
        message: message.length > 20 ? message.slice(0, 20) + "…" : message,
        emoji: mapping.emoji,
        toolName,
      });

      resetIdleTimer(config);
    });

    // ── agent_end ──
    api.on("agent_end", (event, _ctx) => {
      if (event.success) {
        pushState(config, { state: "done", message: "搞定啦！", emoji: "✅", priority: "high" });
      } else {
        pushState(config, { state: "error", message: "出了点问题…", emoji: "❌", priority: "high" });
      }
      resetIdleTimer(config);
    });

    // ── message_received ──
    api.on("message_received", (event, _ctx) => {
      const preview = event.content.length > 15
        ? event.content.slice(0, 15) + "…"
        : event.content;

      pushState(config, {
        state: "idle",
        message: preview,
        emoji: "📨",
        priority: "high",
      });

      resetIdleTimer(config);
    });

    // ── subagent_spawned ──
    api.on("subagent_spawned", (event, _ctx) => {
      const label = event.label || event.agentId || "助手";
      pushState(config, {
        state: "working",
        message: `派出${label}~`,
        emoji: "🦞",
        toolName: "sessions_spawn",
      });

      resetIdleTimer(config);
    });

    // ── subagent_ended ──
    api.on("subagent_ended", (event, _ctx) => {
      if (event.outcome === "ok" || event.outcome === "timeout") {
        pushState(config, {
          state: "done",
          message: "助手已完成",
          emoji: "✅",
          priority: "high",
        });
      } else {
        pushState(config, {
          state: "error",
          message: "助手遇到了问题",
          emoji: "❌",
          priority: "high",
        });
      }

      resetIdleTimer(config);
    });

    // ── gateway_start: health check & initial state ──
    api.on("gateway_start", async (_event, _ctx) => {
      try {
        const controller = new AbortController();
        const timeout = setTimeout(() => controller.abort(), 3000);

        const res = await fetch(config.healthUrl, { signal: controller.signal });
        clearTimeout(timeout);

        if (res.ok) {
          logger.info("🦞 Lobster Companion is running — hook active");
          pushState(config, { state: "idle", message: "在线", emoji: "🦞" });
        } else {
          logger.warn("🦞 Lobster Companion health check returned non-OK");
        }
      } catch {
        logger.info("🦞 Lobster Companion not running — will push when available");
      }

      resetIdleTimer(config);
    });
  },
});
```

## File: plugin-hook/openclaw.plugin.json
size: 1192
sha: d6febf4e92b6cce74d5209837d14482631aedb52
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/plugin-hook/openclaw.plugin.json

```text
{
  "id": "openclaw-companion-hook",
  "name": "OpenClaw Companion Hook",
  "description": "Automatically pushes OpenClaw agent working status to the OpenClaw Companion desktop pet via HTTP API",
  "version": "1.0.0",
  "configSchema": {
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "apiUrl": {
        "type": "string",
        "default": "http://localhost:18182/api/state",
        "description": "OpenClaw Companion HTTP API endpoint for status push"
      },
      "healthUrl": {
        "type": "string",
        "default": "http://localhost:18182/api/health",
        "description": "OpenClaw Companion health check URL"
      },
      "throttleMs": {
        "type": "number",
        "default": 2000,
        "description": "Minimum interval (ms) between consecutive pushes to avoid flooding"
      },
      "idleTimeoutMs": {
        "type": "number",
        "default": 300000,
        "description": "After this many ms with no activity, push 'sleeping' state (5 min default)"
      },
      "enabled": {
        "type": "boolean",
        "default": true,
        "description": "Master toggle to enable/disable the hook"
      }
    }
  }
}
```

## File: plugin-hook/package.json
size: 279
sha: 8975051c05d7024e8ecc231aa5cc24643a76dfe6
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/plugin-hook/package.json

```text
{
  "name": "openclaw-companion-hook",
  "version": "1.0.0",
  "type": "module",
  "description": "OpenClaw plugin that automatically pushes agent working status to the OpenClaw Companion desktop pet",
  "main": "index.js",
  "openclaw": {
    "extensions": ["./index.js"]
  }
}
```

## File: preload.js
size: 761
sha: 641fe3bf1c8cd4f0eca04914f982234207187736
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/preload.js

```text
/**
 * 🦞 龙虾悬浮助手 — Preload 脚本
 * 通过 contextBridge 暴露安全 API 给渲染进程
 */
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('lobsterAPI', {
  // 监听状态变更（从 HTTP API 转发过来）
  onStateChange: (callback) => {
    ipcRenderer.on('state-change', (event, data) => callback(data));
  },

  // 窗口拖拽：发送鼠标位移量
  moveWindow: (deltaX, deltaY) => {
    ipcRenderer.send('window-move', { deltaX, deltaY });
  },

  // 窗口缩放：发送缩放增量
  resizeWindow: (delta) => {
    ipcRenderer.send('window-resize', delta);
  },

  // 获取窗口当前位置
  getWindowPosition: () => {
    return ipcRenderer.invoke('window-position');
  }
});
```

## File: sprites/lobster_coding_done.png
size: 3572430
sha: db2cb3ed8ac98a4a895294642e696218d94dc4fb
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_coding_done.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_coding_done.png

## File: sprites/lobster_coding_error_1_1.png
size: 3628851
sha: 024a1511338ea5d4541589f8c616b0e74f69d0e1
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_coding_error_1_1.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_coding_error_1_1.png

## File: sprites/lobster_eating_1_1.png
size: 3011645
sha: e58889da1faaaaedc94e75f8d40b72d61cda6522
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_eating_1_1.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_eating_1_1.png

## File: sprites/lobster_eating_2_1.png
size: 3161800
sha: 72d1ac76487a763942212477cc5f0dfa654e28e7
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_eating_2_1.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_eating_2_1.png

## File: sprites/lobster_eating_3_1.png
size: 3273596
sha: fd1b29f923404262a0d75e67753f465b29a74945
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_eating_3_1.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_eating_3_1.png

## File: sprites/lobster_sleepy_bubbles_1_1.png
size: 2767308
sha: 20aad354e9912eb53857146888dff85ef15d475c
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_sleepy_bubbles_1_1.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_sleepy_bubbles_1_1.png

## File: sprites/lobster_sleepy_bubbles_2_1.png
size: 3039610
sha: c65285e38b3b8c8e84826870b778203b79a4f9eb
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_sleepy_bubbles_2_1.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_sleepy_bubbles_2_1.png

## File: sprites/lobster_sleepy_bubbles_3_1.png
size: 2826055
sha: 80fd6011b087b7b89b277833c6d2e9b2f1b9b247
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_sleepy_bubbles_3_1.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_sleepy_bubbles_3_1.png

## File: sprites/lobster_waiting_1_1.png
size: 2493193
sha: 37e25a5034f289ce62669e9e277b51ff1d66c313
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_waiting_1_1.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_waiting_1_1.png

## File: sprites/lobster_waiting_2_1.png
size: 2566544
sha: 74e76adce45401270ea58dbb1cb93e5b69a8f1f8
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_waiting_2_1.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_waiting_2_1.png

## File: sprites/lobster_waiting_3_1.png
size: 2840205
sha: 81951a5e9b6bc731ca8878b624052c4d9cd7d4ac
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_waiting_3_1.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_waiting_3_1.png

## File: sprites/lobster_working_claws_up_1.png
size: 2440814
sha: d93a332ee6917ae1cb1eb6ef771f6c632aeafb58
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_working_claws_up_1.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_working_claws_up_1.png

## File: sprites/lobster_working_mixed_action_1.png
size: 2612662
sha: c5eb2eb811e8c1bae4dcb766b4fa1a0daacf50a4
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_working_mixed_action_1.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_working_mixed_action_1.png

## File: sprites/lobster_working_starting_1.png
size: 2686946
sha: 2201d20a90da425daeb25a1dc3b52ba3f504f904
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_working_starting_1.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_working_starting_1.png

## File: sprites/lobster_working_typing_down_1.png
size: 2580327
sha: 0642cd220b21411cb394c2b494a219c8d16ba930
upstream: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_working_typing_down_1.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/l-lesteryu/openclaw-companion/blob/HEAD/sprites/lobster_working_typing_down_1.png
