agent-office 0.2.0: real 3D office, workbench, incremental session scan
Agent Office 0.2.0 (QingJ01, #551): a real 3D office, the workbench, and the earlier review's fixes. The session scanner now reads growing JSONL logs incrementally. It keeps a saved offset with 128 guard bytes, carries UTF-8 and partial JSON across ticks, applies a record complete at EOF once, and resets on truncation, inode or birthtime change and same-size rewrites. Readers update per kind (Claude response usage replaced, Grok sidecar daily totals replaced, metadata refreshed apart from logs).
Run at the reviewed head 3bf522f, merged on main 622f950, on mote under HOME=$(mktemp -d):
- agent-office bun test: 163 pass, 0 fail. Full bun test: 4310 pass, 9 skip, 0 fail. check.mjs agent-office and stamp-page --check: exit 0.
- 100MB log: append scan ~50ms -> 0.04-0.2ms (4x100MB: ~240ms -> 0.13-0.29ms). Through office.hooks: first scan 82ms, then 0.11-0.24ms per append.
- Fuzz with real Claude, Codex and Grok logs in random appends vs a fresh scanner: 0 mismatches.
- Broken by hand: 9 mutations of the cursor and readers go red. Gaps left as follow-ups: the inode check alone, ExtendedTail, the Codex title cursor and summary.json re-reads. Also follow-up: the first scan of an image-heavy log (336ms vs 42ms, framePart).
The package is new on npm: the owner publishes 0.2.0 by hand the first time.
This commit is contained in:
@@ -117,7 +117,7 @@ These add a page to magpie's window, in the app and in `magpie web`, under Plugi
|
||||
| [usage](packages/usage) | Usage glance: calls, errors, tokens and cost for today, 7 or 30 days, and the models behind them | `usage:summary` |
|
||||
| [powercontext](packages/powercontext) | Connection settings for an independently deployed PowerContext service | None |
|
||||
| [nowledge-mem](packages/nowledge-mem) | Connection settings, recall and capture switches, a real connection test, and the scope of what is sent | None |
|
||||
| [agent-office](packages/agent-office) | What are my agents doing: live sessions as workers in a voxel office (3D/2D) or a list, with status, current step and resume commands | no `magpie.read`; its host part reads the local session files of Claude Code, Codex, dsh, Gemini CLI, Qwen Code, Pi, omp, Qoder, WorkBuddy and CodeBuddy, including prompts, replies and tool commands (`text:false` keeps statuses and tool names only) |
|
||||
| [agent-office](packages/agent-office) | What are my agents doing: a real WebGL 3D office with six scenes, an isometric/2D office, grouped workbench, Today usage and recent conversations | no `magpie.read`; its host part reads local session files of Claude Code, Codex, Copilot CLI, Kimi Code, dsh, Gemini CLI, Qwen Code, Pi, omp, Qoder, WorkBuddy, CodeBuddy and Grok Build, including prompts, replies and tool commands (`text:false` keeps statuses and tool names only) |
|
||||
| [fingerprint](packages/fingerprint) | Numeric response fingerprints to investigate suspected model substitution across providers, with shared challenges, candidate rankings, local evidence and JSON export | none (its local service calls magpie’s gateway; sampling uses provider quota) |
|
||||
| [chat](packages/chat) | Chat with magpie's models, your MCP servers, instructions and skills, by Magic_zero ([Magiczerowxy](https://github.com/Magiczerowxy)). Has a host part: a local service the page goes to | none (its service calls magpie's gateway) |
|
||||
|
||||
|
||||
@@ -1,11 +1,44 @@
|
||||
# Changelog
|
||||
|
||||
## 0.1.1 · 2026-10-31
|
||||
## 0.2.0 · 2026-10-31
|
||||
|
||||
功能对齐 [whatsmyagentdoing](https://github.com/Charonyuu/whatsmyagentdoing),并加入真正的 3D 与独立运行方式。
|
||||
|
||||
### Added
|
||||
|
||||
- Real WebGL 3D office (`page/scene3d.js`, bundled three.js r169): orthographic orbit camera, wheel zoom, lighting, shadows, six procedural scenes (office, station, cafe, castle, pirate, graveyard), animated workers and DOM name-tag anchors.
|
||||
- ISO canvas view between 2D and 3D: five activity venues (reading, arcade, huddle, ping-pong, coffee), an office cat, day/night window light, drag-pan and wheel/pinch zoom.
|
||||
- Copilot CLI, Kimi Code and Grok Build readers, Claude Code subagents, OMP profiles, and parent/subagent metadata.
|
||||
- Workbench: Needs you → Working → Finished groups, agent-mix / subagent / idle filters, grouped side rail.
|
||||
- Today panel: turns, tokens, top folders and context bars (60% warn, 85% full).
|
||||
- Recent conversation in the agent panel (last 8 messages), with privacy redaction.
|
||||
- No-progress badges at 8 minutes thinking and 10 minutes running; completed agents wander the venues and sofa.
|
||||
- In-page toast for new waiting/error sessions; tab-title need-you count.
|
||||
- Claude process-liveness check: a session mid-turn with no live process (for example `claude -p` killed from another agent) is **stopped**, not stuck.
|
||||
- **Clear** removes a finished/stopped/waiting/stuck agent until its session moves again.
|
||||
- Nine-language UI: English, 简体中文, 繁體中文, 日本語, 한국어, Español, Français, Deutsch, Português, with prompt-script, theme and browser fallback.
|
||||
- Standalone `bin/agent-office.mjs` (`--json`, `--private`, `--hours`, local page server) and `SKILL.md` for Claude Code / Codex skills.
|
||||
|
||||
### Fixed
|
||||
|
||||
- An agent another agent ran and then interrupted from the shell (`claude -p` or `codex exec` killed by SIGTERM or SIGKILL) no longer stays in the office as at work, then stuck, until its session is deleted in magpie. A Claude Code session with no running process in Claude Code's `sessions/<pid>.json` files is stopped (also Qoder, WorkBuddy and CodeBuddy when their folder keeps such files).
|
||||
- **Clear** (清除) in an agent's panel takes a stuck, failed, stopped, finished or waiting agent out of the office until its session moves again. Before, nothing could take one out but `hideAfter`, and a waiting one never left.
|
||||
- Secure the standalone server with per-run capability URLs, validated Host and same-origin JSON writes; reject cross-site data/script access.
|
||||
- Scrub hidden rail, list, conversation and closed-panel DOM when text is disabled.
|
||||
- Keep stopped 3D renderers stopped across visibility and context restoration; avoid hidden-canvas DPR growth.
|
||||
- Execute bundled THREE in renderer tests; batch articulated worker meshes with InstancedMesh, preserve crowd capacity and keep six-scene props clear of seating routes.
|
||||
- Refresh Today usage at local midnight and read Grok's vendor-documented usage sidecar. JSONL now retains per-file byte cursors and reader state; normal polls parse only appended records instead of replaying growing history every 1.5 s.
|
||||
- Handle partial UTF-8/JSON writes and delayed newlines, reset on truncation/inode replacement/same-size rewrites, and check at most 128 old bytes for truncate-and-regrow. Codex titles use the same incremental framing; unchanged sidecars are not re-parsed or retained as full usage snapshots.
|
||||
- Preserve incremental tool/stream/usage state, Claude response corrections and metadata removal/fallback precedence; incomplete quoted braces do not trigger repeated full-record parsing. Byte-count regression tests cover 100 MiB logs and fragmented image/text writes.
|
||||
- Recompute time-based states without new log writes; allow clearing No progress sessions, unify rail/list labels and retain alert history across filters.
|
||||
- Bound menus and panels to the current CSS viewport; fingerprint static assets to prevent mixing old resources after a same-version update.
|
||||
- Translate scene/quality/fallback/venue labels and scope camera shortcuts to a focused canvas.
|
||||
|
||||
- Inactive canvas is hidden explicitly, so switching between 3D, ISO and 2D never leaves the previous renderer visible.
|
||||
- The grouped rail and menus no longer sit under the agent detail panel.
|
||||
- The security test distinguishes the vendored three.js bundle from our own page code; `scene3d.js` still has no network calls.
|
||||
- Toolbar controls are grouped, so Settings never wraps alone on a second row.
|
||||
- The page fills the plugin frame without an outer scrollbar; the stage shrinks instead of overflowing.
|
||||
- Name tags use their laid-out position for collision stacking, stay inside the stage, and are capped by priority so they cannot cover the office.
|
||||
- The grouped side rail now defaults to **closed** (previous default: open), leaving more space for the office. Open it with **Panel**; an old saved `side:true` is ignored once unless it carries the current preference version.
|
||||
|
||||
## 0.1.0 · 2026-10-29
|
||||
|
||||
|
||||
+147
-86
@@ -2,140 +2,169 @@
|
||||
|
||||
[](https://github.com/QingJ01/magpie-agent-office/releases)
|
||||
[](https://usemagpie.ai)
|
||||
[](#test)
|
||||
[](#test)
|
||||
[](LICENSE)
|
||||
|
||||
**一个住在 magpie 窗口里的实时 Agent 办公室。** 直接读取各 Agent 自己的会话记录,把正在思考、执行工具、等待批准或已经完成的工作,变成太空站里的小人。支持等距 3D、俯视 2D、实时列表和可拖动的悬浮小窗。
|
||||
**一个住在 magpie 窗口里的实时 Agent 办公室。** 直接读取各 Agent 自己的会话记录,把正在思考、执行工具、等待批准或已经完成的工作,变成真 3D 办公室里的小人;也可以切到等距画布、俯视 2D 或分组列表。
|
||||
|
||||
A live activity dashboard for your coding agents inside [magpie](https://usemagpie.ai): every session becomes a little worker in a voxel space-station office, driven by the agent's own session files rather than guesses from network traffic.
|
||||
A live activity dashboard for your coding agents inside [magpie](https://usemagpie.ai). Every session becomes a worker in a real WebGL office, an isometric canvas room, or a grouped workbench — driven by the agent's own session files, not guesses from network traffic.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## 快速开始 · Quick start
|
||||
|
||||
**magpie 插件(推荐)**
|
||||
|
||||
```sh
|
||||
magpie plugin add @magpie-community/page-agent-office
|
||||
```
|
||||
|
||||
安装后打开 **插件 › Agent 办公室**。默认显示真实会话,不是演示数据;第一次没有会话时会看到空办公室。想预览完整效果,可在 **设置 › 示例 Agent** 临时打开示例。
|
||||
安装后打开 **插件 › Agent 办公室**。第一次没有会话时会看到空办公室;想预览完整效果,可在 **设置 › 示例 Agent** 临时打开示例。
|
||||
|
||||
- **3D / 2D**:等距太空站或俯视图。
|
||||
- **办公室 / 列表**:实时状态、当前步骤、目录、模型和最近活动时间。
|
||||
- **点击小人或列表行**:查看任务、最近提问、工具步骤、回复摘要和续接命令。
|
||||
- **画中画**:可拖动、可缩放的悬浮小窗,✕ 或 Esc 放回。
|
||||
**独立运行(没有 magpie 时)**
|
||||
|
||||
支持直接读取会话文件的 Agent:Claude Code、Codex、DeepSeek Harness、Gemini CLI、Qwen Code、Pi、omp、Qoder、WorkBuddy、CodeBuddy。其他 Agent(Cursor、OpenCode、Copilot、Kimi 等)在通过 magpie 的模型工作时也会显示。
|
||||
```sh
|
||||
bun bin/agent-office.mjs # 本地页面,默认 127.0.0.1:4545
|
||||
bun bin/agent-office.mjs --json # 一次性快照,适合让 Agent 在聊天里汇报
|
||||
```
|
||||
|
||||
**它会读取什么:** 这些 Agent 写在本机的会话文件,包括提问、回复和工具命令,并在插件自己的目录里生成 `page/live.js` 供页面显示。设置里关闭「显示提问和回复」后只保留状态与工具名,不再写入提问、回复或命令参数。
|
||||
独立服务会打印带随机访问令牌的完整 URL,请用该 URL 打开;固定的 `/live.js` 和数据 API 不公开。服务拒绝不匹配的 Host、跨站请求和缺少同源 Origin 的写入。端口占用时会报错,可用 `--port 0` 自动选择空闲端口。
|
||||
|
||||
仓库带有 `magpie-plugin` topic,因此也会出现在 **插件 › 发现 › 非官方插件 · GitHub**。插件市场的收录进展见 [magpie-community/plugins](https://github.com/magpie-community/plugins)。
|
||||
仓库也带 `SKILL.md`,可放进 Claude Code / Codex 的 skills 目录,用 `/agent-office` 启动。
|
||||
|
||||
[功能与状态](#where-a-worker-is-is-what-it-is-doing) · [数据来源](#how-it-knows) · [隐私](#privacy) · [设置](#options) · [限制](#what-it-cannot-know) · [开发测试](#test)
|
||||
### 主要功能
|
||||
|
||||
## Where a worker is, is what it is doing
|
||||
- **真 3D(WebGL)**:等距相机、拖拽旋转、滚轮缩放、实时光照与阴影;办公室、空间站、咖啡店、城堡、海盗湾、幽灵谷六种程序化场景。
|
||||
- **ISO / 2D**:不依赖 WebGL 的等距画布与俯视图;相机拖拽、滚轮缩放、昼夜窗光、办公室猫和五个活动点。
|
||||
|
||||
| Status | Where | Sign |
|
||||
|---|---|---|
|
||||
| Thinking · 思考中 | at a desk | … |
|
||||
| Running tools · 执行中 | at a desk, typing, its screen lit | spinner, how long it has run |
|
||||
| Replying · 回复中 | at a desk | lines |
|
||||
| Waiting for you · 等你回应 | in the purple square, waving | **!** |
|
||||
| Done · 已完成 | on the sofa, asleep after 20 minutes | z |
|
||||
| Error · 错误 | at the broken console | × |
|
||||

|
||||
- **分组工作台**:按 **需要你 → 工作中 → 已结束** 分组;可按 Agent、子 Agent、摸鱼 Agent 过滤。
|
||||
- **今日面板**:今天的轮次、tokens、按 Agent 与目录汇总,以及上下文使用率条(60% 黄、85% 红)。
|
||||
|
||||
The counts at the top are how many need you (waiting for an approval or an answer, failed, or stuck), how many are working and how many are done. Below, real sessions: DeepSeek Harness running a tool, Codex done on the sofa, the panel of the first opened by a click:
|
||||

|
||||
- **最近对话**:点击 Agent 查看任务、当前步骤、最近消息、模型、目录、上下文和续接命令。
|
||||
- **页内提醒**:新出现的「需要你」或错误会在页面右下角弹出提示;标题栏显示需要你的数量。magpie 的 iframe 没有系统通知权限,所以不调用浏览器通知。
|
||||
- **9 种语言**:English、简体中文、繁體中文、日本語、한국어、Español、Français、Deutsch、Português。自动按最近提问的语言选择,也可手动指定。
|
||||
- **画中画**:可拖动、可缩放的页内悬浮小窗,✕ 或 Esc 放回。
|
||||
|
||||

|
||||
## 支持哪些 Agent
|
||||
|
||||
## Which way each worker faces
|
||||
直接读取会话文件:
|
||||
|
||||
A seat says which way its owner looks: at a desk the sitter faces the desk, so the monitor stands on the desk's far edge with its lit side toward them and the chair's back behind; on the left wall's sofa they look east and on the front sofa north, away from the backrest. The head shows a face when that side is toward the camera, a profile when it is east, and the back of the head when it is away.
|
||||
|
||||
## Movement and idle gestures
|
||||
|
||||
Completed agents occasionally stretch, glance sideways, swing their legs or nod off. Their schedules differ, and these gestures pause while walking or working. The new gestures respect the system's reduced-motion preference; name tags remain steady.
|
||||
|
||||
Sofas are blocked to normal foot traffic, including the space behind their backrests. Each seat has a front approach: walk through the aisle, board from the front, then leave by that same approach. Rerouting midway through boarding first returns to the aisle. Path smoothing checks every crossed grid cell, and an unreachable destination never falls back to walking straight through furniture.
|
||||
|
||||
## How it knows
|
||||
|
||||
From each agent's **own session file**, as the agent writes it — not a guess from traffic. The plugin's host part (it runs in magpie's plugin host while magpie is open) reads them every 1.5 seconds, only what changed:
|
||||
|
||||
| Agent | File it reads |
|
||||
| Agent | 文件 |
|
||||
|---|---|
|
||||
| Claude Code | `~/.claude/projects/*/*.jsonl` |
|
||||
| Codex | `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl` (+ `session_index.jsonl` for titles) |
|
||||
| DeepSeek Harness | `~/.dsh/sessions/*/*/session.v4.jsonl.zstd` |
|
||||
| Claude Code | `~/.claude/projects/*/*.jsonl`(以及 `subagents/*.jsonl`;`sessions/*.json` 只用来判断进程是否还在) |
|
||||
| Codex | `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`(+ `session_index.jsonl`) |
|
||||
| Copilot CLI | `~/.copilot/session-state/*/events.jsonl` |
|
||||
| Kimi Code | `~/.kimi-code/sessions/*/*/agents/*/wire.jsonl` |
|
||||
| DeepSeek Harness | `~/.dsh/sessions/*/*/session.v4.jsonl[.zstd]` |
|
||||
| Gemini CLI · Qwen Code | `~/.gemini/tmp/*/chats/session-*`, `~/.qwen/tmp/*/chats/session-*` |
|
||||
| Pi · omp | `~/.pi/agent/sessions/*/*.jsonl`, `~/.omp/agent/sessions/*/*.jsonl` |
|
||||
| Qoder · WorkBuddy · CodeBuddy | their `projects/*/*.jsonl` (Claude Code's format) |
|
||||
| Pi · omp | `~/.pi/agent/sessions/*/*.jsonl`, `~/.omp/agent/sessions/*/*.jsonl`,以及 `~/.omp/profiles/*/agent/sessions` |
|
||||
| Grok Build | `~/.grok/sessions/*/*/updates.jsonl` + `summary.json` |
|
||||
| Qoder · WorkBuddy · CodeBuddy | 各自的 `projects/*/*.jsonl`(Claude Code 格式) |
|
||||
|
||||
The `*_HOME` / `*_CONFIG_DIR` variables those agents honour are honoured here too. What each file says decides the status outright: a tool call with no result yet is **running**, an approval asked (Codex's `exec_approval_request`, DeepSeek Harness's `approval/asked`, Gemini's `awaiting_approval`) is **waiting for you**, a question tool is **asked you something**, the turn's end is **done**, an interruption is **stopped**, an error turn is **error**. A turn whose file hasn't moved for ten minutes is shown as stuck.
|
||||
`*_HOME` / `*_CONFIG_DIR` 覆盖变量都支持。Claude 子 Agent、Kimi 子 Agent、Grok 子 Agent 会标为子 Agent,并带父会话;OMP profiles 带 profile 名。其他 Agent(Cursor、OpenCode、Copilot 等)在通过 magpie 的模型工作时,仍会由异步网关钩子看到。
|
||||
|
||||
An agent killed mid-turn writes no end at all: one agent running another (`claude -p` or `codex exec` from a Bash tool) and interrupting it leaves the other's file mid-turn. Claude Code keeps a file per running process (`sessions/<pid>.json`), so a Claude Code session with no running process is **stopped**, at once. Codex and the other agents keep nothing a reader can check, so such a session shows as stuck. Any agent not at work — stuck, failed, stopped, done or waiting — can be taken out of the office with **Clear** (清除) in its panel; it comes back when its session moves again.
|
||||
## 状态与办公室
|
||||
|
||||
Every other agent (Cursor, OpenCode, Copilot, Kimi…) shows while it works through magpie: the module is also an [asynchronous gateway hook](https://usemagpie.ai/docs/plugins#gateway-request) that sees its requests. The hook returns no body, so no request changes.
|
||||
| 状态 | 在哪里 | 标记 |
|
||||
|---|---|---|
|
||||
| Thinking · 思考中 | 工位 | … |
|
||||
| Running tools · 执行中 | 工位,屏幕亮着 | 工具名、已运行时间 |
|
||||
| Replying · 回复中 | 工位 | 正在写入的回复 |
|
||||
| Waiting for you · 等你回应 | 紫色区域,挥手 | **!** |
|
||||
| Done · 已完成 | 沙发、书架、咖啡台、乒乓球、街机、白板或电话亭 | ✓ / 摸鱼 |
|
||||
| Error · 错误 | 故障终端 | × |
|
||||
|
||||
Both write `page/live.js` beside the page, which the page loads every second (a plugin page has no network; its own files it may load). The green **live** dot by the title turns grey if the host stops writing.
|
||||
工作 8 分钟没有新动静标 **No progress**,工具运行 10 分钟标 **No progress · 10m**,仍留在「工作中」;20 分钟后的完成会话进入摸鱼状态。办公室有五个活动点、可撸的猫、随本地时间变化的窗光,以及可拖拽缩放的相机。
|
||||
|
||||
All 60 agents magpie knows are named with their own icons, the files magpie itself shows (`page/icons`, from magpie's assets, MIT).
|
||||
## 怎么知道
|
||||
|
||||
## Using it
|
||||
每个 Agent 自己写在本机的会话文件是唯一事实来源。host 每 1.5 秒读取变化,页面每秒加载一次 `page/live.js`:
|
||||
|
||||
Hovering only highlights a worker. **Click** a worker, its name tag or a row in the list to open its panel — the task, the last thing you asked, the step it's on, how its answer begins, its model and folder, and **Resume command**, shown selected so ⌘C / Ctrl+C copies it — which stays at the side until you close it (✕ or Esc) or click another agent.
|
||||
- 工具有调用没结果 → **执行中**
|
||||
- 请求批准 / 提问(Codex、DSH、Gemini、Kimi 等)→ **需要你**
|
||||
- 本轮结束 → **完成**;中断 → **已结束**;错误 → **错误**
|
||||
- 会话文件 8 / 10 分钟没动 → **No progress**
|
||||
|
||||
## Privacy
|
||||
通过网关看到、没有本地文件的 Agent,按请求推断;它不会因为一次请求结束就冒充「完成」。hook 返回空 body,不修改任何请求。
|
||||
|
||||
- It reads the agents' session files on this computer, only reads them, and only the last two days'. Through the gateway it records only requests made on this computer (magpie's `origin: local`) unless you set `"remote": true`.
|
||||
- `live.js` holds the agent, the session id, the folder name and path, the model, the last prompt (200 characters), the first 280 characters of the last answer, and the names and targets of the last tool calls. It never holds a key, a header or a whole conversation. With `"text": false` (Settings › Show prompts and replies, off) it keeps statuses and tool names only.
|
||||
- `live.js` stays in the plugin's folder and is never sent anywhere. The page asks magpie for no data at all: its `permissions` list is empty.
|
||||
**它会读取什么:** 本机的会话文件,包括提问、回复、工具命令、最近 8 条消息和用量字段,并在插件目录生成 `page/live.js`。设置里关闭「显示提问和回复」后只保留状态与工具名,不写入提问、回复、消息或命令参数;配置读不到时默认关闭文本(fail closed)。
|
||||
|
||||
## Picture in picture
|
||||
## 隐私
|
||||
|
||||
**Picture in picture** (画中画) lifts the office into a small window of the page's own, over the rest of it: drag its bar to move it, drag its corner to reshape it, click ✕ or press Esc to put it back. Only the agents that need you keep their name tags there; hover any of them for the card.
|
||||
- 只读本机 Agent 会话;默认只看最近两天、最多 40 个会话,CLI 可放到 200 个。
|
||||
- `live.js` 保存在插件自己的目录,不发送到任何地方;页面 `permissions` 为空,不读 magpie 的会话 API。
|
||||
- `text:false` 同时由 host 和页面执行:标题回退到目录名,步骤只留工具名,最近对话整段清空。即使 `live.js` 是旧的,页面也不会把被关闭的文本画出来。
|
||||
- 独立 CLI 只监听 `127.0.0.1`;`--private` 与插件里的开关等价。
|
||||
|
||||

|
||||
|
||||
magpie frames a plugin's page with `allow=""` and `sandbox="allow-scripts"`, so the browser's own floating window (a `<video>`'s picture-in-picture, or `documentPictureInPicture`) is refused a page inside it — that was tried first, and it left nothing on screen. A window drawn in the page is not.
|
||||
|
||||

|
||||

|
||||
|
||||
## Options
|
||||
## 设置
|
||||
|
||||
```json
|
||||
{ "mode": "office", "dim": "3d", "demo": false, "showDone": true, "hideAfter": "6h", "text": true, "remote": false }
|
||||
{
|
||||
"mode": "office",
|
||||
"dim": "3d",
|
||||
"scene": "office",
|
||||
"quality": "medium",
|
||||
"demo": false,
|
||||
"showDone": true,
|
||||
"hideAfter": "6h",
|
||||
"text": true,
|
||||
"agents": [],
|
||||
"showSub": true,
|
||||
"showIdle": true,
|
||||
"side": true,
|
||||
"lang": "auto",
|
||||
"remote": false
|
||||
}
|
||||
```
|
||||
|
||||
| Key | |
|
||||
|---|---|
|
||||
| `mode` | `office` or `list` |
|
||||
| `dim` | `3d` or `2d` |
|
||||
| `demo` | show sample agents (Settings › Sample agents) |
|
||||
| `showDone` | keep finished agents on the sofa |
|
||||
| `hideAfter` | when a finished or failed agent leaves: `1h`, `6h`, `24h`, `never` |
|
||||
| `text` | keep prompts and replies (`false`: statuses and tool names only) |
|
||||
| `remote` | the gateway part also records requests from other computers and gateway keys |
|
||||
| `approvalAfterSec` | for an agent seen only through the gateway: how long its tools run before it counts as waiting for you (90) |
|
||||
| `mode` | `office` 或 `list` |
|
||||
| `dim` | `3d`(WebGL)、`iso`(等距画布)或 `2d`(俯视) |
|
||||
| `scene` | `office`、`station`、`cafe`、`castle`、`pirate`、`graveyard` |
|
||||
| `quality` | `low`、`medium`、`high`(3D 阴影与 DPR) |
|
||||
| `showDone` | 保留已完成的 Agent |
|
||||
| `hideAfter` | 完成后多久离开:`1h`、`6h`、`24h`、`never` |
|
||||
| `text` | 保留提问、回复和最近对话(`false`:只留状态与工具名) |
|
||||
| `agents` | 只显示这些 Agent;空数组为全部 |
|
||||
| `showSub` / `showIdle` | 显示子 Agent / 摸鱼 Agent |
|
||||
| `side` | 显示分组侧栏 |
|
||||
| `lang` | `auto` 或九种语言代码 |
|
||||
| `cleared` | { 会话 key: 时间 }:被「清除」的会话,文件再动就回来 |
|
||||
| `remote` | 网关部分也记录其他电脑的请求 |
|
||||
| `approvalAfterSec` | 只有网关记录时,工具运行多久算等你批准(90) |
|
||||
|
||||
The page saves the first five as you change them; a change restarts the plugin's host (magpie's options do), so it waits until it has been left alone a moment.
|
||||
## 独立 CLI
|
||||
|
||||
```sh
|
||||
bun bin/agent-office.mjs [--port 4545] [--hours 48] [--private] [--json] [--no-open]
|
||||
```
|
||||
|
||||
`--json` 输出与页面相同的快照,方便 Agent 在聊天里总结;不带 `--json` 时启动同一个页面,数据来自同一个扫描器。需要 Bun(DSH 的 zstd 解码用到 `Bun.zstdDecompressSync`)。
|
||||
|
||||
## What it cannot know
|
||||
|
||||
- **An agent whose files it doesn't read and that doesn't use magpie's models.** It has no record here at all.
|
||||
- **The model's word-by-word progress.** A file is written per message, so "replying" means the session's file is moving and the model has begun its answer.
|
||||
- **Sessions older than two days**, or more than the latest 40: they are left out to keep each read cheap.
|
||||
- **完全不读文件、也不经过 magpie 的 Agent**:没有任何记录。
|
||||
- **逐 token 的模型进度**:会话文件按消息写入,回复中只表示文件在动。
|
||||
- **系统通知**:magpie 的页面 iframe 没有通知权限,本插件用页内提示取代。
|
||||
- **超过 40 个会话 / 两天**:默认不进入页面;CLI 可调大。
|
||||
- **3D 需要 WebGL**:不可用时自动退回 ISO 画布,功能不丢。
|
||||
|
||||
## Files
|
||||
|
||||
- `lib/readers.mjs` — each agent's session format turned into its phase, step, prompt and answer. No I/O.
|
||||
- `lib/scan.mjs` — finds the files in each agent's folder and rereads only the ones that changed.
|
||||
- `lib/track.mjs` — what the gateway hook keeps, from requests and replies in each API (Anthropic Messages, Chat Completions, Responses, Gemini). No I/O, so the tests drive it directly.
|
||||
- `office.hooks.mjs` — the host part: scans every 1.5 s, sees the gateway's requests, writes `page/live.js`.
|
||||
- `page/agents.js`, `page/icons/` — every agent magpie knows, with its own icon.
|
||||
- `page/model.js` — statuses, counts, words (English and Chinese), agent marks, resume commands and sample agents, with no DOM.
|
||||
- `page/scene.js` — the office, drawn on a canvas in isometric 3D or top-down 2D.
|
||||
- `page/icons.js`, `page/app.js`, `page/index.html`, `page/style.css` — the page.
|
||||
- `lib/readers.mjs` — 各 Agent 会话格式转成状态、步骤、消息、用量;无 I/O。
|
||||
- `lib/scan.mjs` — 找到会话文件,只重读变化;支持子 Agent、OMP profiles、DSH zstd 节流。
|
||||
- `lib/track.mjs` — 网关请求 / 回复的推断;无 I/O。
|
||||
- `office.hooks.mjs` — 插件 host:每 1.5 秒扫描、看网关请求、写 `page/live.js`。
|
||||
- `page/model.js` — 状态、分组、过滤、Today、九语言、续接命令、隐私裁剪。
|
||||
- `page/scene.js` — Canvas 等距 / 2D 办公室、五个活动点、猫、相机、昼夜。
|
||||
- `page/scene3d.js`, `page/three.min.js` — WebGL 真 3D、六场景、光照阴影;three.js r169,MIT。
|
||||
- `page/app.js`, `page/index.html`, `page/style.css`, `page/icons.js`, `page/icons/` — 页面、面板、侧栏、提醒和图标。
|
||||
- `bin/agent-office.mjs`, `SKILL.md` — 没有 magpie 时的独立页面、`--json` 和 skill 包装。
|
||||
|
||||
## Test
|
||||
|
||||
@@ -143,8 +172,40 @@ The page saves the first five as you change them; a change restarts the plugin's
|
||||
bun test
|
||||
```
|
||||
|
||||
Checked in magpie 0.1.1318's own window (`magpie web`), in every view: 3D, 2D, list, and the window of its own.
|
||||
163 项测试覆盖会话解析(含新客户端)、隐私、路径与朝向、沙发合成、2D 活动点、相机、昼夜、3D API、CLI 与独立服务。3D 回归测试执行随包 THREE 的真实场景、几何、动画和矩阵路径,仅替换 GPU 边界;另有真实 magpie 页面宿主的浏览器回归脚本 `test/browser.mjs`,覆盖 Retina 窄视口、菜单边界、标签碰撞、切换与关闭文本后的 DOM。
|
||||
|
||||
```sh
|
||||
# 可选浏览器测试(另行安装 Playwright 与浏览器,先启动 magpie web)
|
||||
OFFICE_PLAYWRIGHT=/path/to/playwright/index.mjs \
|
||||
OFFICE_HOST_URL="http://127.0.0.1:4571/?k=YOUR_LOCAL_KEY" bun test/browser.mjs
|
||||
```
|
||||
|
||||
magpie 0.1.2305 的 Web 宿主在 CSP 源地址中省略协议;WebKit 会拒绝加载资源,Chromium 则接受。WebKit 集成检查需显式设置 `OFFICE_NORMALIZE_WEBKIT_CSP=1`,仅在测试响应中补全现有地址的协议,不改变域名、目录白名单或 sandbox。未修改宿主的 WebKit 集成仍受此问题阻塞,不能视为已通过。
|
||||
|
||||
JSONL 首次打开会重放一次,后续轮询保留字节偏移、UTF-8/JSON 分帧和各 reader 的解析状态,只解析追加的完整记录。截断、替换和同尺寸重写会重建状态;每次增长额外检查最多 128 字节的前缀/旧末尾,识别常见的两次轮询间截断再增长。未变化时不读取日志。metadata/usage sidecar 仅在其版本变化时重读;Codex 标题索引也采用追加游标。
|
||||
|
||||
可用合成数据复现实测(不会读取真实会话或调用模型):
|
||||
|
||||
```sh
|
||||
bun scripts/bench-scan.mjs 100 1 # 一份 100 MiB 日志
|
||||
bun scripts/bench-scan.mjs 100 4 # 四份并发日志
|
||||
```
|
||||
|
||||
普通 JSONL 按追加日志处理;任意修改中部、同时保留 inode 与两处检查片段又增长的非追加编辑无法在不重读整个文件的前提下完整识别。初次读取或重建仍有 O(文件大小) 成本。完整 JSON 文档、压缩 DSH 和发生变化的 usage sidecar 仍按各自快照格式读取。
|
||||
|
||||
修改页面资源后运行 `bun scripts/stamp-page.mjs` 更新内容指纹;`--check` 可验证没有旧指纹。画质切换调整像素比和阴影,抗锯齿在 WebGL 上下文创建时固定。人物使用 InstancedMesh 批量绘制,保留四肢动画与各 Agent 颜色。
|
||||
|
||||
## Prior art
|
||||
|
||||
The office metaphor and several interaction ideas were inspired by
|
||||
[**whatsmyagentdoing**](https://github.com/Charonyuu/whatsmyagentdoing) by
|
||||
[Charonyuu](https://github.com/Charonyuu) — a standalone Claude Code / Codex
|
||||
skill that renders a live 3D office in the browser. It is an independent
|
||||
project under the MIT license; this plugin is a magpie-native implementation
|
||||
with its own renderer, session readers and privacy model. Thanks to its author
|
||||
for showing how much life a small office can have.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
MIT. The bundled three.js is MIT; see the notice in `page/three.min.js` and
|
||||
`page/scene3d.js`.
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
name: agent-office
|
||||
description: Open a live office view of every coding agent on this machine — Claude Code, Codex, Copilot CLI, Kimi Code, Grok Build, DeepSeek Harness, Gemini CLI, Qwen Code, Pi, omp, Qoder, WorkBuddy and CodeBuddy — and show who is thinking, running a tool, waiting for you, done or stuck. Use when the user types /agent-office, asks what their agents are doing, or wants a machine-readable snapshot.
|
||||
---
|
||||
|
||||
# agent-office
|
||||
|
||||
The normal install is the magpie plugin. This skill runs the same page without
|
||||
magpie, using Bun 1.2+.
|
||||
|
||||
Start the office in the background so it keeps running:
|
||||
|
||||
```bash
|
||||
bun "<base directory>/bin/agent-office.mjs" --no-open
|
||||
```
|
||||
|
||||
Then open the full URL it prints, including its random per-run path. Treat that
|
||||
URL as private: it grants access to local session data. Keep using that URL
|
||||
while the process is running. A second run on the same port exits with an
|
||||
address-in-use error; it does not reuse the server. Use `--port 0` to start a
|
||||
separate server on an available port, or choose a different `--port`.
|
||||
|
||||
For a one-off answer in chat, print a snapshot instead of opening a page:
|
||||
|
||||
```bash
|
||||
bun "<base directory>/bin/agent-office.mjs" --json --hours 2
|
||||
```
|
||||
|
||||
Summarize by status and project; do not paste prompts or replies unless the
|
||||
user asks for them. Use `--private` for screen sharing or when the user wants
|
||||
status only.
|
||||
|
||||
Options:
|
||||
|
||||
- `--hours 6` — sessions active in the last 6 hours
|
||||
- `--private` — hide prompts, replies and titles; status and tool names only
|
||||
- `--json` — one snapshot, then exit
|
||||
- `--port 5000` — a different local port
|
||||
- `--no-open` — don't open a browser
|
||||
|
||||
It reads the agents' own local session files, binds to `127.0.0.1` only, and
|
||||
writes nothing back. Requires Bun 1.2+ for the local server and compressed DSH
|
||||
reader; Node alone is not supported.
|
||||
@@ -55,10 +55,12 @@ test("a page magpie serves, with a host part and no reads", () => {
|
||||
}
|
||||
for (const m of html.matchAll(/(?:src|href)="([^"]+)"/g)) {
|
||||
if (m[1].startsWith("_magpie/")) continue
|
||||
expect(readdirSync(page)).toContain(m[1])
|
||||
expect(readdirSync(page)).toContain(m[1].split("?")[0])
|
||||
}
|
||||
for (const f of ["index.html", "style.css", "agents.js", "model.js", "icons.js", "scene.js", "app.js", "icon.svg"]) expect(pkg.files).toContain(`page/${f}`)
|
||||
for (const f of ["page/icons", "lib", "office.hooks.mjs"]) expect(pkg.files).toContain(f)
|
||||
for (const f of ["page/icons", "lib", "office.hooks.mjs", "page/scene3d.js", "page/three.min.js", "bin", "SKILL.md"]) expect(pkg.files).toContain(f)
|
||||
expect(html).toMatch(/<script src="three\.min\.js\?v=[a-f0-9]+"><\/script>/)
|
||||
expect(html).toMatch(/<script src="scene3d\.js\?v=[a-f0-9]+"><\/script>/)
|
||||
// screenshots are linked from GitHub: an install needs none of them
|
||||
expect(pkg.files).not.toContain("docs")
|
||||
expect(new Set(pkg.files).size).toBe(pkg.files.length)
|
||||
@@ -86,11 +88,14 @@ test("the page reaches no clipboard API it cannot have", () => {
|
||||
})
|
||||
|
||||
test("the page reads nothing of magpie's and reaches no network", () => {
|
||||
for (const f of readdirSync(page).filter((f) => f.endsWith(".js") && f !== "live.js")) {
|
||||
// three.min.js is a vendored renderer with dormant loader strings; the
|
||||
// scene3d.js we wrote must itself never reach out. Both are checked apart.
|
||||
for (const f of readdirSync(page).filter((f) => f.endsWith(".js") && !["live.js", "scene3d.js", "three.min.js"].includes(f))) {
|
||||
const src = read(f)
|
||||
expect(src).not.toMatch(/magpie\.read\(/)
|
||||
expect(src).not.toMatch(/\bfetch\(|XMLHttpRequest|WebSocket|sendBeacon|EventSource|importScripts|new Worker/)
|
||||
}
|
||||
expect(read("scene3d.js")).not.toMatch(/\bfetch\(|XMLHttpRequest|WebSocket|sendBeacon|EventSource|importScripts|new Worker/)
|
||||
})
|
||||
|
||||
test("every agent magpie knows, each with its own icon file", () => {
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
#!/usr/bin/env bun
|
||||
// Agent Office without magpie: one Bun process reads the same session files,
|
||||
// serves the same page on 127.0.0.1, and prints the same snapshot as JSON.
|
||||
//
|
||||
// bun bin/agent-office.mjs open the office
|
||||
// bun bin/agent-office.mjs --json one snapshot, then exit
|
||||
// bun bin/agent-office.mjs --private statuses and tool names only
|
||||
// bun bin/agent-office.mjs --hours 6 only the last 6 hours
|
||||
//
|
||||
// The magpie plugin is still the main path: no port, no server. This is for a
|
||||
// terminal, a skill, or a machine where magpie is not open.
|
||||
import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs"
|
||||
import { randomBytes } from "node:crypto"
|
||||
import { spawn } from "node:child_process"
|
||||
import { tmpdir } from "node:os"
|
||||
import { dirname, extname, join, normalize, resolve, sep } from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
const here = dirname(dirname(fileURLToPath(import.meta.url)))
|
||||
const PAGE = join(here, "page")
|
||||
const VERSION = JSON.parse(readFileSync(join(here, "package.json"), "utf8")).version
|
||||
|
||||
const HELP = `Agent Office ${VERSION}
|
||||
A live office for the coding agents on this computer.
|
||||
|
||||
Usage: bun bin/agent-office.mjs [options]
|
||||
|
||||
-p, --port <n> port (default 4545; 0 chooses an available port)
|
||||
--hours <n> sessions active in the last n hours (default 48)
|
||||
--private hide prompts, replies and titles; status only
|
||||
--json print one snapshot as JSON and exit
|
||||
--no-open don't open the browser
|
||||
-h, --help
|
||||
-v, --version
|
||||
|
||||
The magpie plugin is the normal install. This CLI serves the same page when
|
||||
magpie is not running. Requires Bun 1.2+; Node alone is not supported.
|
||||
It binds to 127.0.0.1 only and never writes a session. An occupied port exits
|
||||
with an error; use --port 0 for a separate server on an available port.
|
||||
`
|
||||
|
||||
function usage(msg) {
|
||||
if (msg) console.error(msg + "\n")
|
||||
console.error(HELP)
|
||||
process.exit(msg ? 1 : 0)
|
||||
}
|
||||
|
||||
function args(argv) {
|
||||
const o = { port: 4545, hours: 48, private: false, json: false, open: true }
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i]
|
||||
if (a === "-h" || a === "--help") usage()
|
||||
else if (a === "-v" || a === "--version") { console.log(VERSION); process.exit(0) }
|
||||
else if (a === "-p" || a === "--port") o.port = Number(argv[++i])
|
||||
else if (a.startsWith("--port=")) o.port = Number(a.slice(7))
|
||||
else if (a === "--hours") o.hours = Number(argv[++i])
|
||||
else if (a.startsWith("--hours=")) o.hours = Number(a.slice(8))
|
||||
else if (a === "--private") o.private = true
|
||||
else if (a === "--json") o.json = true
|
||||
else if (a === "--no-open") o.open = false
|
||||
else usage(`Unknown option: ${a}`)
|
||||
}
|
||||
if (!Number.isInteger(o.port) || o.port < 0 || o.port > 65535) usage("--port must be an integer from 0 to 65535")
|
||||
if (!Number.isFinite(o.hours) || o.hours <= 0) usage("--hours must be positive")
|
||||
return o
|
||||
}
|
||||
|
||||
const o = args(process.argv.slice(2))
|
||||
if (typeof Bun === "undefined") {
|
||||
console.error("Agent Office requires Bun 1.2+. Run: bun bin/agent-office.mjs")
|
||||
process.exit(1)
|
||||
}
|
||||
// the scanner takes days; keep an hour window exact instead of rounding up
|
||||
const days = Math.max(1 / 24, o.hours / 24)
|
||||
// the plugin writes live.js beside the page; in CLI mode it goes to a temp
|
||||
// folder and the server answers /live.js from the snapshot instead
|
||||
const scratch = mkdtempSync(join(tmpdir(), "agent-office-cli-"))
|
||||
process.env.MAGPIE_AGENT_OFFICE_PAGE = scratch
|
||||
|
||||
const hook = await import("../office.hooks.mjs")
|
||||
const startOpts = { text: !o.private, scanner: { days, max: 200 } }
|
||||
hook.start(startOpts)
|
||||
await new Promise((r) => setTimeout(r, 250))
|
||||
const first = hook.snapshot()
|
||||
|
||||
if (o.json) {
|
||||
hook.stop()
|
||||
rmSync(scratch, { recursive: true, force: true })
|
||||
console.log(JSON.stringify(first, null, 2))
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const types = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".svg": "image/svg+xml",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".webp": "image/webp",
|
||||
".woff2": "font/woff2",
|
||||
}
|
||||
|
||||
const options = { ...startOpts, remote: false }
|
||||
// Keep the capability out of public routes: scripts loaded by another origin
|
||||
// cannot discover it. All page-relative assets stay under this same prefix.
|
||||
const prefix = "/" + randomBytes(32).toString("hex") + "/"
|
||||
|
||||
function json(v, status = 200) {
|
||||
return new Response(JSON.stringify(v), { status, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } })
|
||||
}
|
||||
|
||||
function bridge() {
|
||||
return `(() => {
|
||||
const options = ${JSON.stringify(options)}
|
||||
const theme = { dark: true, lang: ${JSON.stringify("en")}, tokens: { bg: "#0b0c10", fg: "#f4f4f5", card: "#14151b", line: "#2a2c35", muted: "#9ca3af" } }
|
||||
globalThis.magpie = { ready: Promise.resolve(theme), theme, context: {}, onTheme() {}, onAction() {},
|
||||
options: {
|
||||
get: async () => options,
|
||||
set: async (next) => { const r = await fetch(${JSON.stringify(prefix + "api/options")}, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(next) }); if (!r.ok) throw new Error("Options update failed"); return r.json(); },
|
||||
},
|
||||
read: async (n) => { throw new Error("no read " + n) } }
|
||||
})()`
|
||||
}
|
||||
|
||||
function pagePolicy() {
|
||||
return [
|
||||
"default-src 'none'",
|
||||
"script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; media-src 'self'",
|
||||
"connect-src 'self'",
|
||||
"frame-ancestors 'none'; frame-src 'none'; worker-src 'none'; object-src 'none'; form-action 'none'; base-uri 'none'",
|
||||
].join("; ")
|
||||
}
|
||||
|
||||
function live() {
|
||||
return "globalThis.AgentOfficeLive = " + JSON.stringify(hook.snapshot()) + ";\n"
|
||||
}
|
||||
|
||||
function safePath(rel) {
|
||||
const p = normalize(join(PAGE, rel))
|
||||
return p === PAGE || p.startsWith(PAGE + sep) ? p : ""
|
||||
}
|
||||
|
||||
function serveStatic(pathname) {
|
||||
let rel
|
||||
try { rel = decodeURIComponent(pathname).replace(/^\/+/, "") || "index.html" }
|
||||
catch { return new Response("bad path", { status: 400 }) }
|
||||
if (rel === "live.js") {
|
||||
return new Response(live(), { headers: { "content-type": "text/javascript; charset=utf-8", "cache-control": "no-store" } })
|
||||
}
|
||||
if (rel === "_magpie/bridge.js") {
|
||||
return new Response(bridge(), { headers: { "content-type": "text/javascript; charset=utf-8", "cache-control": "no-store" } })
|
||||
}
|
||||
const file = safePath(rel)
|
||||
if (!file) return new Response("forbidden", { status: 403 })
|
||||
try {
|
||||
if (!statSync(file).isFile()) return new Response("not found", { status: 404 })
|
||||
return new Response(readFileSync(file), {
|
||||
headers: { "content-type": types[extname(file).toLowerCase()] || "application/octet-stream", "cache-control": "no-cache" },
|
||||
})
|
||||
} catch {
|
||||
return new Response("not found", { status: 404 })
|
||||
}
|
||||
}
|
||||
|
||||
async function route(req) {
|
||||
const url = new URL(req.url)
|
||||
const host = req.headers.get("host")
|
||||
const allowed = [`127.0.0.1:${server.port}`, `localhost:${server.port}`]
|
||||
if (!allowed.includes(host) || url.host !== host) return json({ error: "invalid host" }, 403)
|
||||
// Also reject cross-site script loads even if a capability URL was shared.
|
||||
if (req.headers.get("sec-fetch-site") === "cross-site") return json({ error: "cross-site request" }, 403)
|
||||
if (!url.pathname.startsWith(prefix)) return json({ error: "not found" }, 404)
|
||||
const path = url.pathname.slice(prefix.length)
|
||||
if (req.method === "POST") {
|
||||
if (req.headers.get("origin") !== `http://${host}`) return json({ error: "invalid origin" }, 403)
|
||||
if (req.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase() !== "application/json") {
|
||||
return json({ error: "application/json required" }, 415)
|
||||
}
|
||||
if (path !== "api/options") return json({ error: "not found" }, 404)
|
||||
let next
|
||||
try { next = await req.json() } catch { return json({ error: "bad json" }, 400) }
|
||||
if (!next || typeof next !== "object" || Array.isArray(next)) return json({ error: "expected options object" }, 400)
|
||||
if (("text" in next && typeof next.text !== "boolean") || ("remote" in next && typeof next.remote !== "boolean")) {
|
||||
return json({ error: "text and remote must be booleans" }, 400)
|
||||
}
|
||||
// UI preferences remain local to this bridge; never accept scanner paths or
|
||||
// other hook internals from a request body.
|
||||
for (const key of ["text", "remote", "mode", "dim", "demo", "showDone", "hideAfter", "scene", "quality", "agents", "showSub", "showIdle", "side", "sideV", "cleared", "approvalAfterSec", "lang"]) {
|
||||
if (Object.hasOwn(next, key)) options[key] = next[key]
|
||||
}
|
||||
hook.start({ text: options.text !== false, remote: options.remote === true })
|
||||
return json(options)
|
||||
}
|
||||
if (req.method !== "GET" && req.method !== "HEAD") return json({ error: "method not allowed" }, 405)
|
||||
if (path === "api/ping") return json({ name: "agent-office", version: VERSION })
|
||||
if (path === "api/sessions") return json(hook.snapshot())
|
||||
if (path === "api/options") return json(options)
|
||||
return serveStatic(path)
|
||||
}
|
||||
|
||||
let server
|
||||
try {
|
||||
server = Bun.serve({
|
||||
hostname: "127.0.0.1",
|
||||
port: o.port,
|
||||
async fetch(req) {
|
||||
const res = await route(req)
|
||||
res.headers.set("content-security-policy", pagePolicy())
|
||||
res.headers.set("x-content-type-options", "nosniff")
|
||||
res.headers.set("cross-origin-resource-policy", "same-origin")
|
||||
res.headers.set("referrer-policy", "no-referrer")
|
||||
res.headers.set("cache-control", "no-store")
|
||||
return res
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
hook.stop()
|
||||
rmSync(scratch, { recursive: true, force: true })
|
||||
console.error(`Could not start Agent Office on port ${o.port}: ${err.code || err.message}. Use --port 0 or another port.`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const address = `http://127.0.0.1:${server.port}${prefix}`
|
||||
console.log(`Agent Office ${VERSION} — ${first.sessions.length} session${first.sessions.length === 1 ? "" : "s"} — ${address}`)
|
||||
if (o.open) {
|
||||
const [cmd, argv2] =
|
||||
process.platform === "darwin" ? ["open", [address]]
|
||||
: process.platform === "win32" ? ["cmd", ["/c", "start", "", address]]
|
||||
: ["xdg-open", [address]]
|
||||
try { spawn(cmd, argv2, { stdio: "ignore", detached: true }).on("error", () => {}).unref() } catch {}
|
||||
}
|
||||
|
||||
const close = () => {
|
||||
try { server.stop(true) } catch {}
|
||||
hook.stop()
|
||||
rmSync(scratch, { recursive: true, force: true })
|
||||
process.exit(0)
|
||||
}
|
||||
process.on("SIGINT", close)
|
||||
process.on("SIGTERM", close)
|
||||
@@ -0,0 +1,226 @@
|
||||
import { afterAll, expect, test } from "bun:test"
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { request } from "node:http"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
|
||||
const dir = import.meta.dir
|
||||
const script = join(dir, "bin", "agent-office.mjs")
|
||||
// Other marketplace tests temporarily remove node from PATH. Resolve once
|
||||
// and use an absolute executable; Bun-only machines still test the CLI.
|
||||
const nodeExecutable = Bun.which("node") || ["/usr/local/bin/node", "/opt/homebrew/bin/node", "/usr/bin/node"].find(existsSync)
|
||||
const tmps = []
|
||||
const tmp = () => { const d = mkdtempSync(join(tmpdir(), "agent-office-cli-")); tmps.push(d); return d }
|
||||
afterAll(() => { for (const d of tmps) rmSync(d, { recursive: true, force: true }) })
|
||||
|
||||
const SECRET = "SECRET-CLI-PROMPT"
|
||||
function homeWithSession() {
|
||||
const h = tmp()
|
||||
const project = join(h, ".claude", "projects", "-tmp-cli-project")
|
||||
mkdirSync(project, { recursive: true })
|
||||
const timestamp = new Date().toISOString()
|
||||
writeFileSync(join(project, "s1.jsonl"), [
|
||||
JSON.stringify({ type: "user", sessionId: "s1", cwd: "/tmp/cli-project", timestamp, message: { role: "user", content: SECRET } }),
|
||||
JSON.stringify({ type: "assistant", sessionId: "s1", cwd: "/tmp/cli-project", timestamp, message: { role: "assistant", stop_reason: "end_turn", content: [{ type: "text", text: "done" }] } }),
|
||||
].join("\n"))
|
||||
return h
|
||||
}
|
||||
|
||||
function envFor(home) {
|
||||
const cfg = tmp()
|
||||
const env = { ...process.env, HOME: home, XDG_CONFIG_HOME: cfg, XDG_CACHE_HOME: join(home, ".cache") }
|
||||
for (const k of ["CLAUDE_CONFIG_DIR", "CODEX_HOME", "DSH_HOME", "PI_CODING_AGENT_DIR", "OMP_HOME", "OMP_CONFIG_DIR", "KIMI_CODE_HOME", "KIMI_CONFIG_DIR", "GROK_HOME", "GROK_CONFIG_DIR", "COPILOT_HOME", "COPILOT_CONFIG_DIR", "QODER_CONFIG_DIR", "QODERCN_CONFIG_DIR", "WORKBUDDY_CONFIG_DIR", "CODEBUDDY_CONFIG_DIR", "MAGPIE_AGENT_OFFICE_PAGE", "WMAD_OMP_SESSIONS_DIR"]) delete env[k]
|
||||
return env
|
||||
}
|
||||
|
||||
function run(args, home) {
|
||||
const r = Bun.spawnSync({ cmd: [process.execPath, script, ...args], cwd: dir, env: envFor(home), stdout: "pipe", stderr: "pipe" })
|
||||
expect(r.exitCode).toBe(0)
|
||||
return new TextDecoder().decode(r.stdout)
|
||||
}
|
||||
|
||||
async function startServer(extra = []) {
|
||||
const proc = Bun.spawn({ cmd: [process.execPath, script, "--no-open", "--port", "0", "--hours", "1", ...extra], cwd: dir, env: envFor(homeWithSession()), stdout: "pipe", stderr: "pipe" })
|
||||
const reader = proc.stdout.getReader()
|
||||
let out = ""
|
||||
let timeout
|
||||
try {
|
||||
const url = await Promise.race([
|
||||
(async () => {
|
||||
while (true) {
|
||||
const r = await reader.read()
|
||||
if (r.done) throw new Error("CLI exited before printing URL: " + out + await new Response(proc.stderr).text())
|
||||
out += new TextDecoder().decode(r.value)
|
||||
const match = out.match(/http:\/\/127\.0\.0\.1:\d+\/[a-f0-9]{64}\//)
|
||||
if (match) return match[0]
|
||||
}
|
||||
})(),
|
||||
new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error("CLI startup timed out: " + out)), 8000) }),
|
||||
])
|
||||
return { url, origin: new URL(url).origin, proc, stop: async () => { proc.kill(); await proc.exited; reader.releaseLock() } }
|
||||
} catch (err) {
|
||||
proc.kill()
|
||||
await proc.exited
|
||||
throw err
|
||||
} finally { clearTimeout(timeout) }
|
||||
}
|
||||
|
||||
function post(server, value, headers = {}) {
|
||||
return fetch(server.url + "api/options", { method: "POST", headers: { origin: server.origin, "content-type": "application/json", ...headers }, body: JSON.stringify(value) })
|
||||
}
|
||||
|
||||
// Use raw HTTP so the client cannot normalize a forged Host into a safe one.
|
||||
function rawGet(server, host, path = new URL(server.url).pathname + "api/sessions") {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = request({ hostname: "127.0.0.1", port: new URL(server.url).port, path, headers: { Host: host } }, (res) => {
|
||||
let body = ""
|
||||
res.setEncoding("utf8")
|
||||
res.on("data", (chunk) => { body += chunk })
|
||||
res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body }))
|
||||
})
|
||||
req.on("error", reject)
|
||||
req.end()
|
||||
})
|
||||
}
|
||||
|
||||
test("--json prints the same snapshot and honours --private", () => {
|
||||
const h = homeWithSession()
|
||||
const snap = JSON.parse(run(["--json", "--hours", "1"], h))
|
||||
expect(snap.text).toBe(true)
|
||||
expect(snap.sessions.length).toBe(1)
|
||||
expect(snap.sessions[0].project).toBe("cli-project")
|
||||
expect(snap.sessions[0].title).toBe(SECRET)
|
||||
expect(snap.sessions[0].query).toBe(SECRET)
|
||||
|
||||
const priv = JSON.parse(run(["--json", "--hours", "1", "--private"], h))
|
||||
expect(priv.text).toBe(false)
|
||||
expect(priv.sessions[0].query).toBe("")
|
||||
expect(priv.sessions[0].messages).toEqual([])
|
||||
expect(JSON.stringify(priv)).not.toContain(SECRET)
|
||||
})
|
||||
|
||||
test("the authenticated standalone page, bridge, live data and JSON options work", async () => {
|
||||
const s = await startServer()
|
||||
try {
|
||||
const ping = await (await fetch(s.url + "api/ping")).json()
|
||||
expect(ping.name).toBe("agent-office")
|
||||
expect(ping.version).toBe("0.2.0")
|
||||
const page = await fetch(s.url)
|
||||
expect(page.status).toBe(200)
|
||||
expect(await page.text()).toContain('src="_magpie/bridge.js"')
|
||||
expect(page.headers.get("content-security-policy")).toContain("script-src 'self'")
|
||||
expect(page.headers.get("content-security-policy")).toContain("frame-ancestors 'none'")
|
||||
expect(page.headers.get("referrer-policy")).toBe("no-referrer")
|
||||
expect(await (await fetch(s.url + "app.js")).text()).toContain("live.js?t=")
|
||||
const bridge = await (await fetch(s.url + "_magpie/bridge.js")).text()
|
||||
expect(bridge).toContain(new URL(s.url).pathname + "api/options")
|
||||
expect(bridge).toContain('"Content-Type": "application/json"')
|
||||
const live = await fetch(s.url + "live.js?t=123")
|
||||
expect(live.headers.get("cross-origin-resource-policy")).toBe("same-origin")
|
||||
expect(live.headers.get("cache-control")).toBe("no-store")
|
||||
expect(await live.text()).toContain(SECRET)
|
||||
expect((await (await fetch(s.url + "api/sessions")).json()).sessions[0].query).toBe(SECRET)
|
||||
const updated = await post(s, { text: false, scanner: { days: 0 }, __proto__: null })
|
||||
expect(updated.status).toBe(200)
|
||||
expect((await updated.json()).text).toBe(false)
|
||||
expect((await (await fetch(s.url + "api/options")).json()).scanner.days).toBe(1 / 24)
|
||||
expect(await (await fetch(s.url + "live.js")).text()).not.toContain(SECRET)
|
||||
expect(JSON.stringify(await (await fetch(s.url + "api/sessions")).json())).not.toContain(SECRET)
|
||||
} finally { await s.stop() }
|
||||
})
|
||||
|
||||
test("fixed public URLs and guessed tokens cannot expose sessions or the bridge", async () => {
|
||||
const s = await startServer()
|
||||
try {
|
||||
for (const path of ["/", "/live.js", "/api/sessions", "/api/options", "/_magpie/bridge.js", "/" + "0".repeat(64) + "/live.js"]) {
|
||||
const res = await fetch(s.origin + path)
|
||||
expect(res.status).toBe(404)
|
||||
const body = await res.text()
|
||||
expect(body).not.toContain(SECRET)
|
||||
expect(body).not.toContain(new URL(s.url).pathname)
|
||||
}
|
||||
const other = await startServer()
|
||||
try {
|
||||
expect(new URL(other.url).pathname).not.toBe(new URL(s.url).pathname)
|
||||
expect((await fetch(other.origin + new URL(s.url).pathname + "live.js")).status).toBe(404)
|
||||
} finally { await other.stop() }
|
||||
} finally { await s.stop() }
|
||||
})
|
||||
|
||||
test("hostile no-cors POST cannot enable text before a cross-origin live script load", async () => {
|
||||
const s = await startServer(["--private"])
|
||||
try {
|
||||
// The original exploit targets fixed URLs, without a JSON content type.
|
||||
expect((await fetch(s.origin + "/api/options", { method: "POST", headers: { origin: "https://evil.example", "content-type": "text/plain" }, body: '{"text":true}' })).status).toBe(404)
|
||||
// Defense in depth: even knowledge of the capability cannot bypass Origin.
|
||||
for (const origin of ["https://evil.example", "null", "http://127.0.0.1:1", s.origin + ".evil.example"]) {
|
||||
expect((await post(s, { text: true }, { origin })).status).toBe(403)
|
||||
}
|
||||
expect((await fetch(s.url + "api/options", { method: "POST", headers: { "content-type": "application/json" }, body: '{"text":true}' })).status).toBe(403)
|
||||
const script = await fetch(s.url + "live.js", { headers: { "sec-fetch-site": "cross-site" } })
|
||||
expect(script.status).toBe(403)
|
||||
expect(await script.text()).not.toContain(SECRET)
|
||||
expect((await fetch(s.origin + "/live.js")).status).toBe(404)
|
||||
const snap = await (await fetch(s.url + "api/sessions")).json()
|
||||
expect(snap.text).toBe(false)
|
||||
expect(JSON.stringify(snap)).not.toContain(SECRET)
|
||||
// A legitimate same-origin request still enables text.
|
||||
expect((await post(s, { text: true })).status).toBe(200)
|
||||
expect(await (await fetch(s.url + "live.js")).text()).toContain(SECRET)
|
||||
} finally { await s.stop() }
|
||||
})
|
||||
|
||||
test("options POST requires JSON and validates payloads without changing privacy", async () => {
|
||||
const s = await startServer(["--private"])
|
||||
try {
|
||||
for (const type of ["text/plain", "application/x-www-form-urlencoded", "multipart/form-data"]) {
|
||||
expect((await post(s, { text: true }, { "content-type": type })).status).toBe(415)
|
||||
}
|
||||
expect((await fetch(s.url + "api/options", { method: "POST", headers: { origin: s.origin }, body: '{"text":true}' })).status).toBe(415)
|
||||
expect((await fetch(s.url + "api/options", { method: "POST", headers: { origin: s.origin, "content-type": "application/json" }, body: "{" })).status).toBe(400)
|
||||
for (const payload of [null, [], "text", { text: "true" }, { remote: 1 }]) expect((await post(s, payload)).status).toBe(400)
|
||||
expect((await fetch(s.url + "api/options", { method: "PUT" })).status).toBe(405)
|
||||
expect((await (await fetch(s.url + "api/options")).json()).text).toBe(false)
|
||||
expect(await (await fetch(s.url + "live.js")).text()).not.toContain(SECRET)
|
||||
expect((await post(s, { text: true }, { "content-type": "application/json; charset=utf-8" })).status).toBe(200)
|
||||
} finally { await s.stop() }
|
||||
})
|
||||
|
||||
test("DNS rebinding Host headers are rejected and never enter CSP", async () => {
|
||||
const s = await startServer()
|
||||
try {
|
||||
const port = new URL(s.url).port
|
||||
for (const host of ["evil.example", `evil.example:${port}`, `127.0.0.1:${Number(port) + 1}`, `localhost:${Number(port) + 1}`, `127.0.0.1.evil.example:${port}`, `127.0.0.2:${port}`]) {
|
||||
const res = await rawGet(s, host)
|
||||
expect(res.status).toBe(403)
|
||||
expect(res.body).not.toContain(SECRET)
|
||||
expect(res.headers["content-security-policy"]).toContain("script-src 'self'")
|
||||
expect(res.headers["content-security-policy"]).not.toContain(host)
|
||||
}
|
||||
for (const host of [`127.0.0.1:${port}`, `localhost:${port}`]) {
|
||||
const res = await rawGet(s, host)
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.body).toContain(SECRET)
|
||||
}
|
||||
} finally { await s.stop() }
|
||||
})
|
||||
|
||||
test("an occupied port fails clearly; help and executable require Bun", async () => {
|
||||
const s = await startServer()
|
||||
try {
|
||||
const second = Bun.spawn({ cmd: [process.execPath, script, "--no-open", "--port", new URL(s.url).port], cwd: dir, env: envFor(homeWithSession()), stdout: "pipe", stderr: "pipe" })
|
||||
expect(await second.exited).toBe(1)
|
||||
expect(await new Response(second.stderr).text()).toContain("Use --port 0 or another port")
|
||||
expect((await fetch(s.url + "api/ping")).status).toBe(200)
|
||||
expect(readFileSync(script, "utf8").split("\n")[0]).toBe("#!/usr/bin/env bun")
|
||||
const help = Bun.spawnSync({ cmd: [process.execPath, script, "--help"], cwd: dir })
|
||||
expect(new TextDecoder().decode(help.stderr)).toContain("Requires Bun 1.2+")
|
||||
expect(new TextDecoder().decode(help.stderr)).not.toContain("next free one")
|
||||
if (nodeExecutable) {
|
||||
const node = Bun.spawnSync({ cmd: [nodeExecutable, script, "--no-open"], cwd: dir, env: envFor(homeWithSession()) })
|
||||
expect(node.exitCode).toBe(1)
|
||||
expect(new TextDecoder().decode(node.stderr)).toContain("requires Bun 1.2+")
|
||||
expect(new TextDecoder().decode(node.stderr)).not.toContain("ReferenceError")
|
||||
}
|
||||
} finally { await s.stop() }
|
||||
})
|
||||
@@ -0,0 +1,444 @@
|
||||
// Copilot CLI, Kimi Code, Grok Build, Claude Code subagents and omp profiles:
|
||||
// each agent's own file format, as whatsmyagentdoing describes it (MIT) for
|
||||
// the three clients, and the session facts the office's page needs.
|
||||
//
|
||||
// Every fixture lives in a fresh temporary HOME; no test reads a real agent's
|
||||
// folder.
|
||||
import { afterAll, expect, test } from "bun:test"
|
||||
import { mkdirSync, mkdtempSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { createScanner, sources } from "./lib/scan.mjs"
|
||||
import { readClaude, readCodex, readGemini, readGrok, readKimi, MESSAGES_MAX, MESSAGE_TEXT_MAX } from "./lib/readers.mjs"
|
||||
|
||||
const dir = import.meta.dir
|
||||
const tmps = []
|
||||
const tmp = () => { const d = mkdtempSync(join(tmpdir(), "agent-office-clients-")); tmps.push(d); return d }
|
||||
afterAll(() => { for (const d of tmps) rmSync(d, { recursive: true, force: true }) })
|
||||
|
||||
const ENV_KEYS = [
|
||||
"HOME", "CLAUDE_CONFIG_DIR", "CODEX_HOME", "DSH_HOME", "PI_CODING_AGENT_DIR",
|
||||
"OMP_HOME", "OMP_CONFIG_DIR", "KIMI_CODE_HOME", "KIMI_CONFIG_DIR",
|
||||
"GROK_HOME", "GROK_CONFIG_DIR", "COPILOT_HOME", "COPILOT_CONFIG_DIR",
|
||||
"QODER_CONFIG_DIR", "QODERCN_CONFIG_DIR", "WORKBUDDY_CONFIG_DIR", "CODEBUDDY_CONFIG_DIR",
|
||||
]
|
||||
|
||||
// run fn with exactly the environment given; every agent home is explicit so
|
||||
// a developer's own sessions can never be discovered
|
||||
function withEnv(vars, fn) {
|
||||
const saved = new Map()
|
||||
for (const k of ENV_KEYS) { saved.set(k, process.env[k]); delete process.env[k] }
|
||||
Object.assign(process.env, vars)
|
||||
try { return fn() } finally {
|
||||
for (const [k, v] of saved) { if (v === undefined) delete process.env[k]; else process.env[k] = v }
|
||||
}
|
||||
}
|
||||
|
||||
const j = (o) => JSON.stringify(o)
|
||||
const T = (base, n) => new Date(base + n * 1000).toISOString()
|
||||
const write = (root, rel, body) => {
|
||||
const p = join(root, rel)
|
||||
mkdirSync(join(p, ".."), { recursive: true })
|
||||
writeFileSync(p, Array.isArray(body) ? body.map(j).join("\n") + "\n" : typeof body === "string" ? body : j(body))
|
||||
return p
|
||||
}
|
||||
|
||||
// ---- where the files are -------------------------------------------------
|
||||
|
||||
test("new clients are found under HOME and honour their own overrides", () => {
|
||||
const h = tmp()
|
||||
write(h, ".omp/profiles/work/agent/sessions/notes/empty.jsonl", "")
|
||||
withEnv({ HOME: h }, () => {
|
||||
const srcs = sources()
|
||||
expect(srcs.find((s) => s.kind === "kimi").root).toBe(join(h, ".kimi-code", "sessions"))
|
||||
expect(srcs.find((s) => s.kind === "grok").root).toBe(join(h, ".grok", "sessions"))
|
||||
expect(srcs.find((s) => s.kind === "copilot").root).toBe(join(h, ".copilot", "session-state"))
|
||||
expect(srcs.find((s) => s.agent === "omp" && s.kind === "pi" && !s.profile).root).toBe(join(h, ".omp", "agent", "sessions"))
|
||||
expect(srcs.find((s) => s.agent === "omp" && s.profile === "work").root).toBe(join(h, ".omp", "profiles", "work", "agent", "sessions"))
|
||||
// Claude's subagent files sit one level below the session file
|
||||
const sub = srcs.find((s) => s.agent === "claude" && s.subagent)
|
||||
expect(sub.depth).toBe(3)
|
||||
expect(sub.match("agent-x.jsonl", join(h, ".claude", "projects", "-p", "s", "subagents", "agent-x.jsonl"))).toBe(true)
|
||||
expect(sub.match("agent-x.jsonl", join(h, ".claude", "projects", "-p", "s", "other", "agent-x.jsonl"))).toBe(false)
|
||||
})
|
||||
|
||||
const alt = tmp()
|
||||
withEnv({
|
||||
HOME: h,
|
||||
KIMI_CODE_HOME: join(alt, "kimi"),
|
||||
GROK_HOME: join(alt, "grok"),
|
||||
COPILOT_HOME: join(alt, "copilot"),
|
||||
OMP_HOME: join(alt, "omp"),
|
||||
PI_CODING_AGENT_DIR: join(alt, "pi", "agent"),
|
||||
}, () => {
|
||||
const srcs = sources()
|
||||
expect(srcs.find((s) => s.kind === "kimi").root).toBe(join(alt, "kimi", "sessions"))
|
||||
expect(srcs.find((s) => s.kind === "grok").root).toBe(join(alt, "grok", "sessions"))
|
||||
expect(srcs.find((s) => s.kind === "copilot").root).toBe(join(alt, "copilot", "session-state"))
|
||||
expect(srcs.find((s) => s.agent === "omp" && !s.profile).root).toBe(join(alt, "omp", "agent", "sessions"))
|
||||
expect(srcs.find((s) => s.agent === "pi").root).toBe(join(alt, "pi", "agent", "sessions"))
|
||||
})
|
||||
})
|
||||
|
||||
// ---- the new readers, through the scanner --------------------------------
|
||||
|
||||
test("Copilot, Kimi, Grok, Claude subagents and omp profiles: status, lineage, messages", () => {
|
||||
const h = tmp()
|
||||
const base = Date.now() - 60_000
|
||||
const t = (n) => T(base, n)
|
||||
|
||||
// GitHub Copilot CLI: ~/.copilot/session-state/<session>/events.jsonl
|
||||
const SECRET_COPILOT_ARGS = "SECRET-COPILOT-ARGS ls -la"
|
||||
write(h, ".copilot/session-state/cop-1/events.jsonl", [
|
||||
{ type: "session.start", timestamp: t(0), data: { sessionId: "cop-1", context: { cwd: "/Users/me/cop" }, selectedModel: "gpt-5" } },
|
||||
{ type: "user.message", timestamp: t(1), data: { content: "list the files" } },
|
||||
{ type: "tool.execution_start", timestamp: t(2), data: { toolName: "bash", arguments: { command: SECRET_COPILOT_ARGS } } },
|
||||
{ type: "tool.execution_complete", timestamp: t(3), data: {} },
|
||||
{ type: "assistant.message", timestamp: t(4), data: { content: "Here are the files." } },
|
||||
{ type: "session.end", timestamp: t(5), data: {} },
|
||||
])
|
||||
|
||||
// Kimi Code: a main agent and a child agent, one state.json for the session
|
||||
const kimi = ".kimi-code/sessions/proj/kimi-session"
|
||||
write(h, `${kimi}/state.json`, { cwd: "/Users/me/kimi", title: "Kimi job", createdAt: base })
|
||||
write(h, `${kimi}/agents/main/wire.jsonl`, [
|
||||
{ type: "turn.prompt", time: base, input: [{ type: "text", text: "hello kimi" }] },
|
||||
{ type: "llm.request", time: base + 1000, modelAlias: "kimi-k2" },
|
||||
{ type: "context.append_loop_event", time: base + 2000, event: { type: "step.begin" } },
|
||||
{ type: "context.append_loop_event", time: base + 3000, event: { type: "tool.call", toolCallId: "k1", name: "Read", arguments: { path: "SECRET-KIMI-ARGS" } } },
|
||||
{ type: "context.append_loop_event", time: base + 4000, event: { type: "tool.result", toolCallId: "k1" } },
|
||||
{ type: "context.append_loop_event", time: base + 5000, event: { type: "content.part", part: { type: "text", text: "kimi done" } } },
|
||||
{ type: "turn.ended", time: base + 6000, reason: "completed" },
|
||||
])
|
||||
write(h, `${kimi}/agents/researcher/wire.jsonl`, [
|
||||
{ type: "turn.prompt", time: base + 7000, input: [{ type: "text", text: "research this" }] },
|
||||
{ type: "llm.request", time: base + 8000, modelAlias: "kimi-k2" },
|
||||
])
|
||||
|
||||
// Grok Build: explicit subagent kind and its parent
|
||||
write(h, ".grok/sessions/proj/grok-one/updates.jsonl", [
|
||||
{ timestamp: (base + 1000) / 1000, params: { update: { sessionUpdate: "user_message_chunk", content: { text: "build it" } } } },
|
||||
{ timestamp: (base + 2000) / 1000, params: { update: { sessionUpdate: "agent_message_chunk", content: { text: "built" } } } },
|
||||
{ timestamp: (base + 3000) / 1000, params: { update: { sessionUpdate: "turn_completed", stop_reason: "end_turn" } } },
|
||||
])
|
||||
write(h, ".grok/sessions/proj/grok-one/summary.json", {
|
||||
info: { cwd: "/Users/me/grok" }, generated_title: "Grok job", current_model_id: "grok-4",
|
||||
session_kind: "subagent-worker", parent_session_id: "grok-parent", created_at: t(0),
|
||||
})
|
||||
|
||||
// Claude Code: a subagent's own file below project/<session>/subagents/
|
||||
const SECRET_CLAUDE_ARGS = "SECRET-CLAUDE-ARGS rm -rf /"
|
||||
write(h, ".claude/projects/-Users-me-app/main.jsonl", [
|
||||
{ type: "user", sessionId: "main", cwd: "/Users/me/app", timestamp: t(1), message: { role: "user", content: "main task" } },
|
||||
{ type: "assistant", sessionId: "main", cwd: "/Users/me/app", timestamp: t(2), message: { role: "assistant", model: "claude-opus-5", stop_reason: "end_turn", content: [{ type: "text", text: "main done" }] } },
|
||||
])
|
||||
write(h, ".claude/projects/-Users-me-app/main/subagents/agent-x.jsonl", [
|
||||
{ type: "user", sessionId: "main", isSidechain: true, cwd: "/Users/me/app", timestamp: t(3), message: { role: "user", content: "sub task" } },
|
||||
{ type: "assistant", sessionId: "main", isSidechain: true, timestamp: t(4), message: { role: "assistant", model: "claude-opus-5", stop_reason: "tool_use", content: [{ type: "tool_use", id: "t1", name: "Bash", input: { command: SECRET_CLAUDE_ARGS } }] } },
|
||||
{ type: "user", sessionId: "main", isSidechain: true, timestamp: t(5), message: { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "ok" }] } },
|
||||
{ type: "assistant", sessionId: "main", isSidechain: true, timestamp: t(6), message: { role: "assistant", model: "claude-opus-5", stop_reason: "end_turn", content: [{ type: "text", text: "sub done" }] } },
|
||||
])
|
||||
|
||||
// omp: the default agent folder and two named profiles
|
||||
write(h, ".omp/agent/sessions/-Users-me-omp/2026-01-01T00-00-00_default.jsonl", [
|
||||
{ type: "session", id: "omp-base", cwd: "/Users/me/omp", timestamp: t(1) },
|
||||
{ type: "message", timestamp: t(2), message: { role: "user", content: [{ type: "text", text: "base task" }] } },
|
||||
{ type: "message", timestamp: t(3), message: { role: "assistant", content: [{ type: "text", text: "base done" }], stopReason: "stop" } },
|
||||
])
|
||||
for (const name of ["work", "play"]) {
|
||||
write(h, `.omp/profiles/${name}/agent/sessions/-Users-me-omp/2026-01-01T00-00-00_${name}.jsonl`, [
|
||||
{ type: "session", id: `omp-${name}`, cwd: "/Users/me/omp", timestamp: t(1) },
|
||||
{ type: "message", timestamp: t(2), message: { role: "user", content: [{ type: "text", text: `${name} task` }] } },
|
||||
{ type: "message", timestamp: t(3), message: { role: "assistant", content: [{ type: "text", text: `${name} done` }], stopReason: "stop" } },
|
||||
])
|
||||
}
|
||||
|
||||
withEnv({ HOME: h }, () => {
|
||||
const sc = createScanner({ sources: sources(), days: 2, max: 40 })
|
||||
const got = sc.scan(Date.now())
|
||||
const by = (agent, id) => got.find((s) => s.agent === agent && s.id === id)
|
||||
|
||||
// Copilot
|
||||
const cop = by("copilot", "cop-1")
|
||||
expect(cop).toMatchObject({ phase: "done", model: "gpt-5", cwd: "/Users/me/cop", project: "cop" })
|
||||
expect(cop.messages.map((m) => m.role)).toEqual(["user", "tool", "assistant"])
|
||||
const copTool = cop.messages.find((m) => m.role === "tool")
|
||||
expect(copTool.text).toBe("bash")
|
||||
expect(copTool.name).toBe("bash")
|
||||
|
||||
// Kimi main and child
|
||||
const main = by("kimi", "kimi-session")
|
||||
expect(main).toMatchObject({ phase: "done", title: "Kimi job", model: "kimi-k2", cwd: "/Users/me/kimi", project: "kimi", subagent: false, parent: "" })
|
||||
expect(main.messages.some((m) => m.role === "assistant" && m.text === "kimi done")).toBe(true)
|
||||
const kid = by("kimi", "kimi-session/researcher")
|
||||
expect(kid).toMatchObject({ phase: "thinking", subagent: true, parent: "kimi-session", title: "Kimi job" })
|
||||
|
||||
// Grok
|
||||
const grok = by("grok", "grok-one")
|
||||
expect(grok).toMatchObject({ phase: "done", title: "Grok job", model: "grok-4", cwd: "/Users/me/grok", subagent: true, parent: "grok-parent" })
|
||||
expect(grok.messages.some((m) => m.role === "assistant" && m.text === "built")).toBe(true)
|
||||
|
||||
// Claude subagent: its sidechain records are kept, and it has a parent
|
||||
const sub = by("claude", "agent-x")
|
||||
expect(sub).toMatchObject({ phase: "done", subagent: true, parent: "main", cwd: "/Users/me/app" })
|
||||
expect(sub.messages.some((m) => m.role === "tool" && m.text === "Bash")).toBe(true)
|
||||
expect(by("claude", "main")).toMatchObject({ phase: "done", subagent: false })
|
||||
|
||||
// omp profiles
|
||||
expect(by("omp", "omp-work")).toMatchObject({ profile: "work", agent: "omp" })
|
||||
expect(by("omp", "omp-play")).toMatchObject({ profile: "play" })
|
||||
expect(by("omp", "omp-base")).toMatchObject({ profile: "" })
|
||||
|
||||
// tool arguments never travel inside messages (they may appear in `step`,
|
||||
// which the page hides when text is off; a message is text-only)
|
||||
const msgWire = JSON.stringify(got.map((s) => s.messages))
|
||||
expect(msgWire).not.toContain("SECRET-COPILOT-ARGS")
|
||||
expect(msgWire).not.toContain("SECRET-KIMI-ARGS")
|
||||
expect(msgWire).not.toContain("SECRET-CLAUDE-ARGS")
|
||||
expect(msgWire).not.toContain("hunter2")
|
||||
for (const s of got) expect(s.messages.length).toBeLessThanOrEqual(MESSAGES_MAX)
|
||||
})
|
||||
})
|
||||
|
||||
// ---- usage and message limits -------------------------------------------
|
||||
|
||||
const DAY = "2026-10-28" // timestamps are pinned; today is passed explicitly
|
||||
const at = (n) => `2026-10-28T10:${String(n).padStart(2, "0")}:00.000Z`
|
||||
const NOW = Date.parse("2026-10-28T12:00:00.000Z")
|
||||
|
||||
test("Claude usage: today's tokens, context window, one turn", () => {
|
||||
const usage = { input_tokens: 1000, cache_creation_input_tokens: 200, cache_read_input_tokens: 300, output_tokens: 50 }
|
||||
const text = [
|
||||
j({ type: "user", sessionId: "c1", timestamp: at(1), message: { role: "user", content: "fix it" } }),
|
||||
// one API response is logged once per content block: the same id must not count twice
|
||||
j({ type: "assistant", sessionId: "c1", timestamp: at(2), message: { id: "msg_1", role: "assistant", model: "claude-opus-5", stop_reason: "tool_use", usage, content: [{ type: "text", text: "working" }] } }),
|
||||
j({ type: "assistant", sessionId: "c1", timestamp: at(3), message: { id: "msg_1", role: "assistant", model: "claude-opus-5", stop_reason: "end_turn", usage, content: [{ type: "text", text: "done" }] } }),
|
||||
].join("\n")
|
||||
const r = readClaude(text, "claude", "c1", { now: NOW })
|
||||
expect(r).toMatchObject({ phase: "done", context: 1550, contextWindow: 200000, tokensToday: 1250, turnsToday: 1, turns: 1 })
|
||||
expect(r.messages.filter((m) => m.role === "user")).toHaveLength(1)
|
||||
expect(DAY).toBe(new Date(NOW).toISOString().slice(0, 10))
|
||||
})
|
||||
|
||||
test("Codex usage: token_count feeds today's tokens and the context window", () => {
|
||||
const text = [
|
||||
j({ timestamp: at(1), type: "session_meta", payload: { id: "cx", cwd: "/Users/me/blog" } }),
|
||||
j({ timestamp: at(1), type: "event_msg", payload: { type: "task_started", turn_id: "u1" } }),
|
||||
j({ timestamp: at(2), type: "event_msg", payload: { type: "item_completed", item: { type: "UserMessage", content: [{ type: "text", text: "export it" }] } } }),
|
||||
j({ timestamp: at(3), type: "event_msg", payload: { type: "token_count", info: { model_context_window: 200000, last_token_usage: { input_tokens: 1000, cached_input_tokens: 400, output_tokens: 80 } } } }),
|
||||
j({ timestamp: at(4), type: "event_msg", payload: { type: "task_complete", last_agent_message: "Exported." } }),
|
||||
].join("\n")
|
||||
const r = readCodex(text, "cx", { now: NOW })
|
||||
expect(r).toMatchObject({ phase: "done", context: 1080, contextWindow: 200000, tokensToday: 680, turnsToday: 1 })
|
||||
})
|
||||
|
||||
test("messages keep text, clip it, and never carry a tool's arguments", () => {
|
||||
const long = "x".repeat(900)
|
||||
const text = [
|
||||
j({ type: "user", sessionId: "m1", timestamp: at(1), message: { role: "user", content: long } }),
|
||||
...Array.from({ length: 10 }, (_, i) => j({ type: "assistant", sessionId: "m1", timestamp: at(2 + i), message: { role: "assistant", stop_reason: "end_turn", content: [{ type: "text", text: `reply ${i}` }] } })),
|
||||
j({ type: "assistant", sessionId: "m1", timestamp: at(20), message: { role: "assistant", stop_reason: "tool_use", content: [{ type: "tool_use", id: "t1", name: "Bash", input: { command: "SECRET-ARGS curl -u admin:hunter2" } }] } }),
|
||||
].join("\n")
|
||||
const r = readClaude(text, "claude", "m1", { now: NOW })
|
||||
expect(r.messages.length).toBe(MESSAGES_MAX)
|
||||
for (const m of r.messages) expect(m.text.length).toBeLessThanOrEqual(MESSAGE_TEXT_MAX)
|
||||
expect(JSON.stringify(r.messages)).not.toContain("SECRET-ARGS")
|
||||
expect(JSON.stringify(r.messages)).not.toContain("hunter2")
|
||||
expect(r.messages.some((m) => m.role === "tool" && m.text === "Bash" && m.name === "Bash")).toBe(true)
|
||||
expect(r.messages.every((m) => Number.isFinite(m.at))).toBe(true)
|
||||
})
|
||||
|
||||
const source = (root, kind, extra = {}) => ({ root, kind, agent: kind, depth: 0, match: (n) => n.endsWith(".jsonl"), ...extra })
|
||||
const claudeTurn = (time, prompt = "work", tokens = 100) => [
|
||||
{ type: "user", timestamp: new Date(time).toISOString(), message: { role: "user", content: prompt } },
|
||||
{ type: "assistant", timestamp: new Date(time + 1000).toISOString(), message: { id: `msg-${time}`, role: "assistant", usage: { input_tokens: tokens, output_tokens: 10 }, stop_reason: "end_turn", content: [{ type: "text", text: "done" }] } },
|
||||
]
|
||||
|
||||
test("cached Today counts roll over at local midnight without rereading the file", () => {
|
||||
const h = tmp()
|
||||
const before = new Date(2026, 9, 28, 23, 59, 30).getTime()
|
||||
const after = new Date(2026, 9, 29, 0, 0, 30).getTime()
|
||||
const p = write(h, "cached.jsonl", claudeTurn(before))
|
||||
utimesSync(p, before / 1000, before / 1000)
|
||||
const sc = createScanner({ sources: [source(h, "claude")] })
|
||||
expect(sc.scan(before)[0]).toMatchObject({ tokensToday: 110, turnsToday: 1 })
|
||||
const cached = sc.files.get(p)
|
||||
expect(sc.scan(after)[0]).toMatchObject({ tokensToday: 0, turnsToday: 0, turns: 1 })
|
||||
expect(sc.files.get(p)).toBe(cached)
|
||||
// Buckets remain private, and scanning another day does not discard history.
|
||||
expect(sc.scan(before)[0]).toMatchObject({ tokensToday: 110, turnsToday: 1 })
|
||||
expect(JSON.stringify(sc.scan(after))).not.toContain("buckets")
|
||||
})
|
||||
|
||||
test("large JSONL replays usage and turns in the omitted middle, across updates and rewrites", () => {
|
||||
const h = tmp()
|
||||
const now = Date.now()
|
||||
// Today's only events sit between >64 KiB of head and >512 KiB of tail.
|
||||
const padding = { type: "padding", text: "x".repeat(1024) }
|
||||
const rows = [
|
||||
{ type: "user", timestamp: new Date(now - 3 * 86400e3).toISOString(), cwd: "/old/project", message: { role: "user", content: "old prompt" } },
|
||||
...Array.from({ length: 100 }, () => padding),
|
||||
...claudeTurn(now - 10000, "middle prompt", 6000),
|
||||
...Array.from({ length: 600 }, () => padding),
|
||||
]
|
||||
const p = write(h, "large.jsonl", rows)
|
||||
const sc = createScanner({ sources: [source(h, "claude")] })
|
||||
expect(statSync(p).size).toBeGreaterThan(576 * 1024)
|
||||
expect(sc.scan(now)[0]).toMatchObject({ tokensToday: 6010, turnsToday: 1, turns: 2, cwd: "/old/project", query: "middle prompt", phase: "done" })
|
||||
write(h, "large.jsonl", [...rows, ...claudeTurn(now - 5000, "new prompt", 200)])
|
||||
expect(sc.scan(now)[0]).toMatchObject({ tokensToday: 6220, turnsToday: 2, turns: 3, query: "new prompt" })
|
||||
rows[0].cwd = "/new/project"
|
||||
write(h, "large.jsonl", rows)
|
||||
expect(sc.scan(now)[0]).toMatchObject({ cwd: "/new/project", tokensToday: 6010, turnsToday: 1 })
|
||||
})
|
||||
|
||||
test("chunked JSONL preserves UTF-8 characters split across a read boundary", () => {
|
||||
const h = tmp()
|
||||
const prefix = j({ type: "padding", text: "x".repeat(65500) }) + "\n"
|
||||
const user = j({ type: "user", timestamp: new Date().toISOString(), message: { role: "user", content: "hello 世界 🌍" } })
|
||||
// Put the first Chinese character's first byte at the end of a read chunk.
|
||||
const marker = Buffer.byteLength(prefix + user.slice(0, user.indexOf("世")))
|
||||
const target = Math.ceil(marker / 65536) * 65536 - 1
|
||||
const adjusted = prefix.replace("x", "x".repeat(target - marker + 1))
|
||||
write(h, "utf8.jsonl", adjusted + user + "\n")
|
||||
const sc = createScanner({ sources: [source(h, "claude")] })
|
||||
expect(sc.scan()[0].query).toBe("hello 世界 🌍")
|
||||
})
|
||||
|
||||
test("undocumented CONFIG_DIR aliases are ignored while Claude's documented override works", () => {
|
||||
const h = tmp()
|
||||
const aliases = ["OMP_CONFIG_DIR", "KIMI_CONFIG_DIR", "GROK_CONFIG_DIR", "COPILOT_CONFIG_DIR", "QODER_CONFIG_DIR", "QODERCN_CONFIG_DIR", "WORKBUDDY_CONFIG_DIR", "CODEBUDDY_CONFIG_DIR"]
|
||||
withEnv({ HOME: h, CLAUDE_CONFIG_DIR: join(h, "claude-custom"), ...Object.fromEntries(aliases.map((k) => [k, join(h, "ignored", k)])) }, () => {
|
||||
const roots = sources().map((s) => s.root)
|
||||
expect(roots.every((p) => !p.includes("/ignored/"))).toBe(true)
|
||||
expect(roots).toContain(join(h, "claude-custom", "projects"))
|
||||
expect(roots).toContain(join(h, ".qoder", "projects"))
|
||||
expect(roots).toContain(join(h, ".workbuddy", "projects"))
|
||||
})
|
||||
})
|
||||
|
||||
const grokEvent = (time, type, text = "", extra = {}) => ({ timestamp: time / 1000, params: { update: { sessionUpdate: type, content: { text }, ...extra } } })
|
||||
|
||||
test("Grok uses timestamped usage.json deltas, refreshes sidecars and resets at midnight", () => {
|
||||
const h = tmp()
|
||||
const now = new Date(2026, 9, 28, 12).getTime()
|
||||
const yesterday = new Date(2026, 9, 27, 12).getTime()
|
||||
const nextDay = new Date(2026, 9, 29, 12).getTime()
|
||||
write(h, ".grok/sessions/proj/session/updates.jsonl", [grokEvent(now, "user_message_chunk", "test"), grokEvent(now + 1000, "turn_completed")])
|
||||
const summary = { generated_title: "old title", info: { cwd: "/old" } }
|
||||
const rel = ".grok/sessions/proj/session"
|
||||
write(h, `${rel}/summary.json`, summary)
|
||||
// Schema taken from xai-org/grok-build's SessionUsageFile / TurnUsage.
|
||||
const usage = { padding: "x".repeat(300 * 1024), sessionId: "session", updatedAt: new Date(now).toISOString(), session: { inputTokens: 999999, outputTokens: 999999 }, turns: [
|
||||
{ turnNumber: 1, endedAt: new Date(yesterday).toISOString(), inputTokens: 5000, outputTokens: 1000 },
|
||||
{ turnNumber: 2, endedAt: new Date(now).toISOString(), inputTokens: 1000, cachedReadTokens: 400, cacheCreationTokens: 50, outputTokens: 80, reasoningTokens: 20, totalTokens: 1080, modelUsage: { grok: { inputTokens: 1000, outputTokens: 80 } } },
|
||||
] }
|
||||
write(h, `${rel}/usage.json`, usage)
|
||||
withEnv({ HOME: h }, () => {
|
||||
const sc = createScanner({ sources: sources().filter((s) => s.kind === "grok"), days: 10000 })
|
||||
expect(sc.scan(now)[0]).toMatchObject({ title: "old title", tokensToday: 680, turnsToday: 1, context: 0 })
|
||||
write(h, `${rel}/summary.json`, { ...summary, generated_title: "updated title", info: { cwd: "/new" } })
|
||||
usage.turns[1].outputTokens = 120
|
||||
write(h, `${rel}/usage.json`, usage)
|
||||
expect(sc.scan(now)[0]).toMatchObject({ title: "updated title", cwd: "/new", tokensToday: 720, turnsToday: 1 })
|
||||
expect(sc.scan(nextDay)[0]).toMatchObject({ tokensToday: 0, turnsToday: 0 })
|
||||
// A malformed or missing sidecar must not keep its stale usage or hide the session.
|
||||
write(h, `${rel}/usage.json`, "{")
|
||||
expect(sc.scan(now)[0]).toMatchObject({ phase: "done", tokensToday: 0, turnsToday: 1 })
|
||||
rmSync(join(h, rel, "usage.json"))
|
||||
expect(sc.scan(now)[0].tokensToday).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
test("Grok does not invent a usage day from lifetime totals or malformed turn values", () => {
|
||||
const now = Date.now()
|
||||
const text = [grokEvent(now, "user_message_chunk", "hi"), grokEvent(now + 1000, "turn_completed")].map(j).join("\n")
|
||||
expect(readGrok(text, "g", {}, { now, usage: { session: { totalTokens: 5000 }, updatedAt: new Date(now).toISOString() } }).tokensToday).toBe(0)
|
||||
expect(readGrok(text, "g", {}, { now, usage: { turns: [null, { endedAt: "bad date", inputTokens: 200 }, { endedAt: new Date(now).toISOString(), inputTokens: "100", outputTokens: -2 }] } }).tokensToday).toBe(0)
|
||||
})
|
||||
|
||||
test("Grok and Kimi streamed whitespace survives chunk boundaries and clipping", () => {
|
||||
const now = Date.now()
|
||||
for (const chunks of [["hello ", "world"], ["hello", " ", "world"], ["hel", "lo", " world"], ["hello\n", "world"], ["x".repeat(499), " ", "tail"], ["x".repeat(500), " ".repeat(1000), "tail"], [" ".repeat(1000), "hello ", "world"]]) {
|
||||
const expected = chunks.join("").replace(/\s+/g, " ").trim()
|
||||
const kimi = readKimi(chunks.map((text) => j({ type: "context.append_loop_event", time: now, event: { type: "content.part", part: { type: "text", text } } })).join("\n"))
|
||||
const grok = readGrok(chunks.map((text) => j(grokEvent(now, "agent_message_chunk", text))).join("\n"))
|
||||
const clipped = expected.length > MESSAGE_TEXT_MAX ? expected.slice(0, MESSAGE_TEXT_MAX - 1).trimEnd() + "…" : expected
|
||||
for (const s of [kimi, grok]) {
|
||||
expect(s.messages).toHaveLength(1)
|
||||
expect(s.messages[0].text).toBe(clipped)
|
||||
expect(s.reply).toBe(expected.length > 280 ? expected.slice(0, 279).trimEnd() + "…" : expected)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test("Grok streamed user messages retain message length beyond the query limit", () => {
|
||||
const now = Date.now()
|
||||
const chunks = ["hello ", "world ", "x".repeat(250)]
|
||||
const s = readGrok(chunks.map((text) => j(grokEvent(now, "user_message_chunk", text))).join("\n"))
|
||||
expect(s.turns).toBe(1)
|
||||
expect(s.messages[0].text).toBe(chunks.join(""))
|
||||
expect(s.query.length).toBe(200)
|
||||
expect(s.query.startsWith("hello world ")).toBe(true)
|
||||
})
|
||||
|
||||
test("Gemini approval clears when a tool resolves or the assistant finishes", () => {
|
||||
for (const final of [
|
||||
{ type: "gemini", content: "", toolCalls: [{ id: "t1", name: "shell", status: "success" }] },
|
||||
{ type: "gemini", content: "done" },
|
||||
]) {
|
||||
const s = readGemini(j({ messages: [
|
||||
{ type: "user", content: "run it" },
|
||||
{ type: "gemini", content: "", toolCalls: [{ id: "t1", name: "shell", status: "awaiting_approval" }] },
|
||||
final,
|
||||
] }))
|
||||
expect(s.phase).toBe(final.toolCalls ? "thinking" : "done")
|
||||
expect(s.pending).toHaveLength(0)
|
||||
}
|
||||
})
|
||||
|
||||
test("compressed scan eventually decodes a final write skipped by the throttle", () => {
|
||||
const h = tmp()
|
||||
const now = Date.now()
|
||||
const header = { type: "session", id: "compressed", createdAt: new Date(now).toISOString() }
|
||||
const p = join(h, "session.v4.jsonl.zstd")
|
||||
const compressed = (events) => writeFileSync(p, Bun.zstdCompressSync(Buffer.from(events.map(j).join("\n") + "\n")))
|
||||
compressed([header, { type: "turn/start", time: new Date(now).toISOString(), data: {} }])
|
||||
const sc = createScanner({ sources: [source(h, "dsh", { match: (n) => n.endsWith(".zstd") })], zstdEvery: 4000 })
|
||||
expect(sc.scan(now)[0].phase).toBe("thinking")
|
||||
compressed([header, { type: "turn/end", time: new Date(now + 1000).toISOString(), data: { reason: { kind: "completed" } } }])
|
||||
expect(sc.scan(now + 1000)[0].phase).toBe("thinking")
|
||||
expect(sc.scan(now + 4001)[0].phase).toBe("done")
|
||||
})
|
||||
|
||||
test("Grok logs beyond the old 32 MiB cap retain middle turns and open tools", () => {
|
||||
const h = tmp()
|
||||
const now = Date.now()
|
||||
const padding = j({ type: "padding", text: "x".repeat(1024 * 1024) }) + "\n"
|
||||
const events = [grokEvent(now, "user_message_chunk", "middle prompt"), grokEvent(now + 1000, "tool_call", "", { toolCallId: "still-open", title: "Read", status: "in_progress" })]
|
||||
write(h, "updates.jsonl", padding + events.map(j).join("\n") + "\n" + padding.repeat(32))
|
||||
const sc = createScanner({ sources: [source(h, "grok")] })
|
||||
const s = sc.scan(now + 2000)[0]
|
||||
expect(s).toMatchObject({ query: "middle prompt", turnsToday: 1, phase: "tool" })
|
||||
expect(s.pending.map((p) => p.id)).toEqual(["still-open"])
|
||||
})
|
||||
|
||||
test("Grok empty prompt chunks wait for text and turn metadata separates adjacent turns", () => {
|
||||
const now = Date.now()
|
||||
const chunks = ["", " ", "hello ", "world"]
|
||||
const rows = chunks.map((text) => grokEvent(now, "user_message_chunk", text))
|
||||
for (const row of rows) row.params._meta = { turnStartMs: now }
|
||||
let s = readGrok(rows.map(j).join("\n"), "g", {}, { now })
|
||||
expect(s).toMatchObject({ query: "hello world", title: "hello world", turns: 1, turnsToday: 1 })
|
||||
expect(s.messages.map((m) => m.text)).toEqual(["hello world"])
|
||||
const next = grokEvent(now + 1000, "user_message_chunk", "second turn")
|
||||
next.params._meta = { turnStartMs: now + 1000 }
|
||||
s = readGrok([...rows, next].map(j).join("\n"), "g", { title: "named" }, { now })
|
||||
expect(s).toMatchObject({ query: "second turn", title: "named", turns: 2, turnsToday: 2 })
|
||||
})
|
||||
|
||||
test("Claude counts final usage once for interleaved blocks of the same response", () => {
|
||||
const row = (id, output, time) => ({ type: "assistant", timestamp: at(time), message: { id, role: "assistant", usage: { input_tokens: 100, cache_creation_input_tokens: 20, cache_read_input_tokens: 400, output_tokens: output }, content: [] } })
|
||||
const s = readClaude([row("a", 0, 1), row("b", 5, 2), row("a", 10, 3), row("b", 5, 4)].map(j).join("\n"), "claude", "c", { now: NOW })
|
||||
expect(s).toMatchObject({ tokensToday: 255, context: 525 })
|
||||
})
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 392 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 396 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 279 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 287 KiB |
@@ -0,0 +1,59 @@
|
||||
# 0.2.0 review validation
|
||||
|
||||
This is the 0.2.0 repair for [PR #551](https://github.com/magpie-community/plugins/pull/551). No release/tag is created or moved for this repair. CI success is not maintainer approval; the requested-changes review still needs re-review.
|
||||
|
||||
## Review blockers
|
||||
|
||||
1. **CLI cross-site access**: pages/data/bridge require a per-run 256-bit capability URL. Host must match the actual loopback listener; writes require matching Origin and JSON. CSP does not interpolate Host. Tests exercise the original private-mode POST + script attack, forged Host/DNS rebinding, missing/guessed tokens and legitimate access.
|
||||
2. **Text-off DOM residue**: rail signatures include titles/privacy state; hidden rail/list content refreshes; message nodes are removed; closed details are scrubbed. Browser tests switch text off with a panel open and assert no synthetic marker remains in DOM text or attributes.
|
||||
3. **Hidden 3D resumes**: enabled state is separate from visibility; stale rAF generations are rejected; the app accepts anchors only from its active renderer. Tests cover mode switches, visibility and context restoration.
|
||||
4. **DPR growth**: hidden canvases retain CSS dimensions and never reuse their buffer as CSS input. DPR-2 tests repeat hidden resizes.
|
||||
5. **Early-return 3D tests**: tests now execute the bundled THREE scene, geometry, matrices, workers and animation; only GPU/DOM scheduling boundaries are stubbed.
|
||||
|
||||
## Other findings
|
||||
|
||||
- Today refreshes from private daily buckets at local midnight. Changed JSONL logs replay fully with a UTF-8-safe chunk iterator. Grok usage.json uses the published vendor per-turn schema; sidecar-only edits invalidate cache.
|
||||
- No-progress/idle labels update without new writes. No-progress sessions can be cleared until their next write. Rail/list labels agree; filters do not replay old error toasts.
|
||||
- Bun requirement, occupied-port behavior, --port 0, Grok skill support and capability URL documentation are accurate.
|
||||
- Nine-language scene/quality/fallback/role/venue text; focused camera shortcuts; wheel handling only consumes a zoom change; notification dots.
|
||||
- Six-scene prop fitting avoids seating/walking routes. Overflow workers get distinct destinations; context loss, bounded orbit and touch pinch are covered.
|
||||
- Shared InstancedMesh batches preserve articulated poses, colors and shadows. In the renderer fixture, 32 workers across seven statuses use 9 groups instead of 608 individual worker meshes. This is structural evidence, not a GPU benchmark.
|
||||
- Quality adjusts DPR/shadows; context antialiasing is fixed. The three.js header documents the reproducible esbuild command.
|
||||
- Undocumented CONFIG_DIR aliases removed; stream word boundaries preserved; redaction validates tool-name prefixes.
|
||||
|
||||
## Validation
|
||||
|
||||
`bun test`: **163 passed, 0 failed**, 13 files. Marketplace package tests also pass 163 tests; the marketplace check script passes.
|
||||
|
||||
Browser tests use actual magpie Web UI navigation, options bridge, theme and sandbox. Only live.js is replaced by synthetic data. No model calls or user prompt screenshots are needed.
|
||||
|
||||
DPR-2 window sizes 600×620, 820×650 and 1440×1000 give plugin CSS viewports 576×500, 788×594 and 1196×944. Checks cover menus, tag collisions, modes, hidden buffers, the No-progress clock, alert history and text-off scrubbing. The largest size also exercises six scenes and three quality settings.
|
||||
|
||||
**Chromium passes unchanged. WebKit limitation:** magpie 0.1.2305's Web host emits scheme-less numeric-host CSP sources, which WebKit rejects. WebKit UI checks pass only with explicit `OFFICE_NORMALIZE_WEBKIT_CSP=1`, adding the existing URL scheme while preserving the same host/path allowlist and sandbox. Unmodified WebKit Web-host integration remains blocked by that host CSP behavior. Native WKWebView was not automated.
|
||||
|
||||
Synthetic narrow-frame evidence: [settings](qa-retina-settings.png), [text disabled](qa-retina-privacy.png).
|
||||
|
||||
## Practical limits
|
||||
|
||||
The first read and a reset/replacement replay are O(file size). Normal JSONL polling parses only appended complete records and performs at most 128 bytes of old-prefix/end checks; an unfinished record still requires buffering until complete. Arbitrary non-append middle edits preserving inode and both witnesses while growing are outside the append-only log contract. Compressed DSH retains its 8 MiB input limit and four-second throttle. Grok sidecars are capped at 32 MiB and usage is assigned to the recorded turn-end date. Stub-GPU tests do not replace device-specific performance testing.
|
||||
|
||||
|
||||
## Follow-up review: incremental JSONL
|
||||
|
||||
[Follow-up review](https://github.com/magpie-community/plugins/pull/551#pullrequestreview-5722086970) confirmed the previous blockers fixed and identified growing-log replay as the remaining blocker.
|
||||
|
||||
The scanner now keeps the file identity, byte offset, UTF-8 decoder, JSON framing and resumable reader state. Normal ticks never replay historical events. No-change ticks do not read the log; metadata-only updates refresh sidecars without reading JSONL. Codex thread titles also retain a cursor. First reads, truncation/replacement and detected rewrites rebuild state. Prefix/end guards add at most 128 old bytes per growing file, catching common truncate-and-regrow without scanning history.
|
||||
|
||||
New regressions cover actual bytes read after appending to a 100 MiB file; every reader's batch/full equivalence and parse-call counts; midnight; usage corrections; pending tools; metadata replacement/removal and precedence; partial UTF-8; delayed newline; large image fragments; quoted braces; interrupted reads; and resets/source changes. An incomplete quoted string ending in `}` is never speculatively re-parsed each tick. A complete EOF record may be parsed twice when first completed (validation then reader), but not on later ticks or when its newline arrives.
|
||||
|
||||
Reproducible synthetic benchmark: `bun scripts/bench-scan.mjs 100 1` and `bun scripts/bench-scan.mjs 100 4`. One local run:
|
||||
|
||||
| Workload | First read | No-change read | Five append scans | Bytes per append scan |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| One ~100 MiB log | 130.695 ms | 0.172 ms / 0 B | 0.097–0.388 ms | 4,003 new + 128 guard |
|
||||
| Four ~100 MiB logs | 514.631 ms | 0.216 ms / 0 B | 0.257–0.656 ms | 16,012 new + 512 guards |
|
||||
|
||||
These are measurements on this machine, not CI speed thresholds. Deterministic tests assert byte and parse counts instead. Complete usage sidecars are not retained or re-aggregated on each append; only current day totals are retained by the reader. Gemini JSON documents and compressed DSH snapshots remain full-document reads when changed.
|
||||
|
||||
|
||||
Follow-up validation at the incremental repair: full marketplace `HOME=$(mktemp -d) bun test` completed with **4115 passed, 4 skipped, 0 failed**, across 327 files. Package tests pass 163 tests across 13 files. The installed 0.2.0 scanner/readers were checked against the source SHA-256 hashes. CI passed for the incremental code commit; maintainer re-review is still required.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 502 KiB |
@@ -0,0 +1,234 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { readFileSync, readdirSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
|
||||
// Model-level tests for the workbench features: groups, filters, Today,
|
||||
// no-progress, transcript redaction and the nine languages. The DOM parts
|
||||
// are checked for their hooks; the model is loaded exactly as the page does.
|
||||
const dir = import.meta.dir
|
||||
const page = join(dir, "page")
|
||||
const read = (f) => readFileSync(join(page, f), "utf8")
|
||||
const scope = {}
|
||||
new Function("globalThis", read("agents.js"))(scope)
|
||||
new Function("globalThis", read("model.js"))(scope)
|
||||
const M = scope.AgentOfficeModel
|
||||
|
||||
const now = 10_000_000
|
||||
const S = (phase, extra = {}) => ({
|
||||
key: "claude|x", source: "files", agent: "claude", session: "x", phase, touched: now, updated: now, ...extra,
|
||||
})
|
||||
|
||||
test("nine languages, one key set, and every label the page asks for", () => {
|
||||
expect(M.LANGS).toEqual(["en", "zh-CN", "zh-TW", "ja", "ko", "es", "fr", "de", "pt"])
|
||||
const en = Object.keys(M.TEXT.en).sort()
|
||||
for (const code of M.LANGS) {
|
||||
expect(Object.keys(M.TEXT[code]).sort()).toEqual(en)
|
||||
for (const key of en) {
|
||||
expect(typeof M.TEXT[code][key]).toBe("string")
|
||||
expect(M.TEXT[code][key].length).toBeGreaterThan(0)
|
||||
}
|
||||
// the group headings the workbench draws exist in every language
|
||||
for (const group of ["needYou", "working", "finished"]) expect(M.TEXT[code][group]).toBeTruthy()
|
||||
}
|
||||
// zh stays an alias of zh-CN for the older page/tests
|
||||
expect(M.TEXT.zh).toBe(M.TEXT["zh-CN"])
|
||||
expect(M.text("zh-CN").title).toBe("我的 Agent 在干嘛")
|
||||
expect(M.text("zh-Hant").title).toBe(M.TEXT["zh-TW"].title)
|
||||
expect(M.text("pt-BR").settings).toBe(M.TEXT.pt.settings)
|
||||
expect(M.text("xx").settings).toBe(M.TEXT.en.settings)
|
||||
// every data-t the page carries is translated in every language
|
||||
const html = read("index.html")
|
||||
const keys = [...html.matchAll(/data-t="([^"]+)"/g)].map((m) => m[1])
|
||||
expect(keys.length).toBeGreaterThan(20)
|
||||
for (const code of M.LANGS) for (const key of keys) expect(M.TEXT[code][key]).toBeDefined()
|
||||
})
|
||||
|
||||
test("the language follows the prompt, the theme, the browser, then English", () => {
|
||||
expect(M.normalizeLang("zh-HK")).toBe("zh-TW")
|
||||
expect(M.normalizeLang("zh-Hans")).toBe("zh-CN")
|
||||
expect(M.normalizeLang("pt-BR")).toBe("pt")
|
||||
expect(M.normalizeLang("xx-YY")).toBe("")
|
||||
// a manual pick wins over everything
|
||||
expect(M.detectLang({ manual: "ja", sample: "请修一下", theme: "en" })).toBe("ja")
|
||||
// a CJK prompt is the strongest automatic hint
|
||||
expect(M.detectLang({ manual: "auto", sample: "请帮我修一下这个 bug", theme: "en", nav: ["en-US"] })).toBe("zh-CN")
|
||||
expect(M.detectLang({ sample: "これはテストです" })).toBe("ja")
|
||||
expect(M.detectLang({ sample: "이 버그를 고쳐줘" })).toBe("ko")
|
||||
expect(M.detectLang({ sample: "這是傳統中文的問題" })).toBe("zh-TW")
|
||||
// a Latin prompt says nothing: the theme, then the browser, decide
|
||||
expect(M.detectLang({ sample: "fix the bug", theme: "de", nav: ["fr-FR"] })).toBe("de")
|
||||
expect(M.detectLang({ nav: ["fr-CA"] })).toBe("fr")
|
||||
expect(M.detectLang({})).toBe("en")
|
||||
// the newest prompt is the sample
|
||||
expect(M.sample({ sessions: [{ updated: 1, query: "old" }, { updated: 9, title: "新しい" }, { updated: 5, query: "" }] })).toBe("新しい")
|
||||
expect(M.sample(null)).toBe("")
|
||||
})
|
||||
|
||||
test("the workbench groups into Needs you, Working and Finished", () => {
|
||||
const list = M.agents(M.demo(now), now)
|
||||
const groups = M.groups(list)
|
||||
expect(groups.map((g) => g.key)).toEqual(["needYou", "working", "finished"])
|
||||
expect(groups.reduce((n, g) => n + g.list.length, 0)).toBe(list.length)
|
||||
expect(groups[0].list.every((a) => a.status === "waiting" || a.status === "error")).toBe(true)
|
||||
expect(groups[1].list.every((a) => a.status === "thinking" || a.status === "executing" || a.status === "replying")).toBe(true)
|
||||
expect(groups[2].list.every((a) => a.status === "done")).toBe(true)
|
||||
// newest first within a group
|
||||
for (const g of groups) {
|
||||
for (let i = 1; i < g.list.length; i++) expect(g.list[i - 1].at).toBeGreaterThanOrEqual(g.list[i].at)
|
||||
}
|
||||
})
|
||||
|
||||
test("agent mix, subagent and idle filters are applied in the model", () => {
|
||||
const snap = { sessions: [
|
||||
S("tool", { key: "a", agent: "claude", project: "p1", touched: now - 1000 }),
|
||||
S("tool", { key: "b", agent: "codex", project: "p2", touched: now - 2000 }),
|
||||
S("done", { key: "c", agent: "claude", project: "p1", touched: now - 30 * 60e3, updated: now - 30 * 60e3 }),
|
||||
S("tool", { key: "d", agent: "claude", project: "p3", touched: now - 1000, subagent: true, parent: "a" }),
|
||||
] }
|
||||
const ids = (opts) => M.agents(snap, now, { progress: true, ...opts }).map((a) => a.key)
|
||||
expect(ids({}).sort()).toEqual(["a", "b", "c", "d"])
|
||||
expect(ids({ agents: ["codex"] })).toEqual(["b"])
|
||||
expect(ids({ agents: [] }).length).toBe(4) // none selected means all
|
||||
expect(ids({ showSub: false })).toEqual(["a", "b", "c"])
|
||||
expect(ids({ showIdle: false })).toEqual(["a", "b", "d"])
|
||||
const c = M.agents(snap, now, { progress: true }).find((a) => a.key === "c")
|
||||
expect(c.idle).toBe(true)
|
||||
expect(c.subagent).toBe(false)
|
||||
expect(M.agents(snap, now, { progress: true }).find((a) => a.key === "d").subagent).toBe(true)
|
||||
})
|
||||
|
||||
test("no progress keeps a stalled turn in Working, with a badge", () => {
|
||||
const thinking = S("thinking", { key: "t", touched: now - 9 * 60e3, updated: now - 9 * 60e3 })
|
||||
const tool = S("tool", { key: "u", touched: now - 11 * 60e3, updated: now - 11 * 60e3 })
|
||||
expect(M.state(thinking, now, { progress: true })).toEqual({ status: "thinking", sub: "noprog" })
|
||||
expect(M.state(tool, now, { progress: true })).toEqual({ status: "executing", sub: "stuck" })
|
||||
const list = M.agents({ sessions: [thinking, tool] }, now, { progress: true })
|
||||
expect(M.counts(list)).toEqual({ needYou: 0, working: 2, done: 0 })
|
||||
expect(M.groups(list).map((g) => [g.key, g.list.length])).toEqual([["needYou", 0], ["working", 2], ["finished", 0]])
|
||||
expect(list.every((a) => a.noProgress)).toBe(true)
|
||||
// the thresholds are 8 min for thinking and 10 min for a tool
|
||||
expect(M.state(S("thinking", { touched: now - 7 * 60e3 }), now, { progress: true })).toEqual({ status: "thinking", sub: "" })
|
||||
expect(M.state(S("tool", { touched: now - 9 * 60e3 }), now, { progress: true })).toEqual({ status: "executing", sub: "" })
|
||||
// the older, un-opted reading is unchanged for callers that still use it
|
||||
expect(M.state(tool, now)).toEqual({ status: "error", sub: "stuck" })
|
||||
expect(M.state(S("thinking", { touched: now - 11 * 60e3 }), now)).toEqual({ status: "error", sub: "stuck" })
|
||||
})
|
||||
|
||||
test("Today totals turns and tokens by agent and folder, and reads context", () => {
|
||||
const snap = { sessions: [
|
||||
S("tool", { key: "a", agent: "claude", project: "blog", touched: now - 1000, turnsToday: 2, tokensToday: 1200, context: 50000, contextWindow: 200000 }),
|
||||
S("tool", { key: "b", agent: "claude", project: "blog", touched: now - 1000, turnsToday: 1, tokensToday: 800, context: 120000, contextWindow: 200000 }),
|
||||
S("tool", { key: "c", agent: "codex", project: "app", touched: now - 1000, turnsToday: 2, tokensToday: 40000, context: 170000, contextWindow: 200000 }),
|
||||
S("tool", { key: "d", agent: "gemini", project: "app", touched: now - 1000 }), // no usage fields
|
||||
] }
|
||||
const list = M.agents(snap, now, { progress: true })
|
||||
const a = list.find((x) => x.key === "a")
|
||||
expect(a).toMatchObject({ turnsToday: 2, tokensToday: 1200, context: 50000, contextWindow: 200000 })
|
||||
expect(a.ctx).toEqual({ used: 50000, window: 200000, pct: 25, level: "ok" })
|
||||
|
||||
const day = M.today(list)
|
||||
expect(day.hasUsage).toBe(true)
|
||||
expect(day.turns).toBe(5)
|
||||
expect(day.tokens).toBe(42000)
|
||||
expect(day.agentCount).toBe(2)
|
||||
expect(day.byAgent.claude).toEqual({ agent: "claude", name: "Claude Code", turns: 3, tokens: 2000 })
|
||||
expect(day.byAgent.codex).toMatchObject({ turns: 2, tokens: 40000 })
|
||||
expect(day.projects.map((p) => p.project)).toEqual(["blog", "app"])
|
||||
expect(day.projects[0]).toEqual({ project: "blog", turns: 3, tokens: 2000 })
|
||||
// context bars: 85% is full, 60% warns, below is fine
|
||||
expect(day.contexts.map((c) => c.pct)).toEqual([85, 60, 25])
|
||||
expect(day.contexts.map((c) => c.level)).toEqual(["full", "warn", "ok"])
|
||||
|
||||
// context may arrive as {used, window} and contextWindow is the override
|
||||
expect(M.context({ context: { used: 7000, window: 10000 } })).toMatchObject({ pct: 70, level: "warn" })
|
||||
expect(M.context({ context: { used: 1, window: 10 }, contextWindow: 10000 })).toMatchObject({ used: 1, window: 10000, pct: 0 })
|
||||
|
||||
expect(M.fmtTokens(999)).toBe("999")
|
||||
expect(M.fmtTokens(1234)).toBe("1.2k")
|
||||
expect(M.fmtTokens(42000)).toBe("42k")
|
||||
expect(M.fmtTokens(2_500_000)).toBe("2.50M")
|
||||
|
||||
// no usage anywhere is shown as such, not as zeroes pretending to be data
|
||||
expect(M.today([])).toEqual({ hasUsage: false, turns: 0, tokens: 0, agentCount: 0, byAgent: {}, projects: [], contexts: [] })
|
||||
const bare = M.agents({ sessions: [S("tool", { key: "e", agent: "gemini", turnsToday: 0, tokensToday: 0, context: 0, contextWindow: 0 })] }, now, { progress: true })
|
||||
expect(M.today(bare).hasUsage).toBe(false)
|
||||
expect(M.today(bare).contexts).toEqual([])
|
||||
})
|
||||
|
||||
test("resume commands cover the newer readers and their extra fields", () => {
|
||||
expect(M.resume({ agent: "copilot", session: "c1", cwd: "/x" })).toBe("cd /x && copilot --resume c1")
|
||||
expect(M.resume({ agent: "kimi", session: "k1", cwd: "/x" })).toBe("cd /x && kimi --session k1")
|
||||
expect(M.resume({ agent: "grok", session: "g1", cwd: "/x" })).toBe("cd /x && grok --resume g1")
|
||||
expect(M.resume({ agent: "omp", session: "o1", cwd: "/x" })).toBe("cd /x && omp --resume o1")
|
||||
// a reader that knows the agent's own syntax wins
|
||||
expect(M.resume({ agent: "omp", session: "o1", cwd: "/x", resumeCommand: "omp profile resume o1" })).toBe("omp profile resume o1")
|
||||
const [a] = M.agents({ sessions: [{ ...S("tool", { key: "s" }), subagent: true, parent: "p", profile: "work", messages: [{ role: "tool", text: "Bash", name: "Bash", at: now }] }] }, now, { progress: true })
|
||||
expect(a).toMatchObject({ subagent: true, parent: "p", profile: "work" })
|
||||
expect(a.messages).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("conversations are redacted with the rest of the text", () => {
|
||||
const secret = {
|
||||
key: "claude|x", agent: "claude", brand: { name: "Claude Code" }, project: "safe", title: "SAFE",
|
||||
query: "SECRET-QUERY", reply: "SECRET-REPLY", error: "SECRET-ERROR", step: "Bash · SECRET-CMD",
|
||||
messages: [{ role: "user", text: "SECRET-MESSAGE", at: now }],
|
||||
}
|
||||
const [r] = M.redact([secret])
|
||||
expect(r.messages).toEqual([])
|
||||
expect(r.private).toBe(true)
|
||||
expect(r).toMatchObject({ title: "safe", query: "", reply: "", error: "", step: "Bash" })
|
||||
// a plain tool name may survive; an argument may not
|
||||
expect(M.redact([{ ...secret, step: "Bash" }])[0].step).toBe("Bash")
|
||||
expect(M.redact([{ ...secret, step: "SECRET-CMD curl x" }])[0].step).toBe("")
|
||||
})
|
||||
|
||||
test("the page carries the workbench hooks and still reaches no network", () => {
|
||||
const html = read("index.html")
|
||||
const app = read("app.js")
|
||||
for (const id of ["toasts", "rail", "railGroups", "todayMenu", "todayTokens", "todayBtn", "sideBtn", "optAgents", "optLang", "optSub", "optIdle"]) {
|
||||
expect(html).toContain(`id="${id}"`)
|
||||
}
|
||||
for (const token of ["M.groups", "M.today", "M.detectLang", "M.redact", "showToast", "document.title"]) expect(app).toContain(token)
|
||||
// desktop notifications are unavailable in magpie's allow="" frame: never called
|
||||
expect(app).not.toMatch(/Notification|requestPermission/)
|
||||
expect(app).not.toMatch(/\bfetch\(|XMLHttpRequest|WebSocket|sendBeacon|EventSource|importScripts|new Worker/)
|
||||
expect(app).not.toContain("navigator.clipboard")
|
||||
// the page serves only its own files
|
||||
for (const f of readdirSync(page).filter((f) => f.endsWith(".js") && f !== "live.js")) expect(read(f)).toBeTruthy()
|
||||
})
|
||||
|
||||
test("crowded labels remain disjoint after edge clamping at Retina CSS widths", () => {
|
||||
for (const [width,height] of [[280,180],[520,260],[1100,700]]) {
|
||||
const items=Array.from({length:12},(_,i)=>({key:String(i),x:i%2?2:width-2,y:30+i,w:190,h:22}))
|
||||
const labels=M.layoutTags(items,width,height,12)
|
||||
expect(labels.length).toBeGreaterThan(1)
|
||||
for (let i=0;i<labels.length;i++) {
|
||||
const a=labels[i]
|
||||
expect(a.x-a.w/2).toBeGreaterThanOrEqual(6)
|
||||
expect(a.x+a.w/2).toBeLessThanOrEqual(width-6)
|
||||
expect(a.y-a.h).toBeGreaterThanOrEqual(6)
|
||||
expect(a.y).toBeLessThanOrEqual(height-6)
|
||||
for (const b of labels.slice(i+1)) expect(a.x+a.w/2<=b.x-b.w/2 || b.x+b.w/2<=a.x-a.w/2 || a.y<=b.y-b.h || b.y<=a.y-a.h).toBe(true)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test("No progress sessions can be cleared in the default working state until another write", () => {
|
||||
const snap={sessions:[S("tool",{updated:now-11*60e3,touched:now-11*60e3})]}
|
||||
const [a]=M.agents(snap,now,{})
|
||||
expect(a.status).toBe("executing")
|
||||
expect(a.sub).toBe("stuck")
|
||||
expect(M.clearable(a)).toBe(true)
|
||||
expect(M.agents(snap,now,{cleared:{[a.key]:a.at}})).toEqual([])
|
||||
snap.sessions[0].touched=now
|
||||
expect(M.agents(snap,now,{cleared:{[a.key]:a.at}})).toHaveLength(1)
|
||||
})
|
||||
|
||||
|
||||
test("redaction rejects command-like tool prefixes instead of retaining arbitrary text", () => {
|
||||
const list=[{title:"private",query:"secret",step:"private command with spaces · --token secret"},{title:"private",step:"functions.exec_command · secret"}]
|
||||
const got=M.redact(list)
|
||||
expect(got[0].step).toBe("")
|
||||
expect(got[1].step).toBe("functions.exec_command")
|
||||
expect(JSON.stringify(got)).not.toContain("secret")
|
||||
})
|
||||
@@ -0,0 +1,368 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { createSessionReader, finalizeUsage, readClaude, readCodex, readDsh, readGemini, readPi, readCopilot, readKimi, readGrok, MESSAGES_MAX, MESSAGE_TEXT_MAX, TEXT_MAX } from "./lib/readers.mjs"
|
||||
|
||||
const now = new Date(2026, 9, 30, 12).getTime()
|
||||
const nextDay = new Date(2026, 9, 31, 12).getTime()
|
||||
const iso = (t = now) => new Date(t).toISOString()
|
||||
const j = JSON.stringify
|
||||
const claude = (role, content, extra = {}, t = now) => ({ type: role, timestamp: iso(t), message: { role, content, ...extra } })
|
||||
const codex = (type, payload, t = now) => ({ type, timestamp: iso(t), payload })
|
||||
const dsh = (type, data = {}) => ({ type, time: iso(), data })
|
||||
const pi = (role, content, extra = {}) => ({ type: "message", timestamp: iso(), message: { role, content, ...extra } })
|
||||
const copilot = (type, data = {}) => ({ type, timestamp: iso(), data })
|
||||
const kimi = (type, extra = {}) => ({ type, time: iso(), ...extra })
|
||||
const grok = (type, text = "", extra = {}, meta = {}) => ({ timestamp: now / 1000, params: { update: { sessionUpdate: type, content: { text }, ...extra }, _meta: meta } })
|
||||
const fullReaders = {
|
||||
claude: (text) => readClaude(text, "claude", "id", { now }),
|
||||
codex: (text) => readCodex(text, "id", { now }),
|
||||
dsh: (text) => readDsh(text, "id", { now }),
|
||||
gemini: (text) => readGemini(text, "gemini", "id", { now }),
|
||||
pi: (text) => readPi(text, "pi", "id", { now }),
|
||||
copilot: (text) => readCopilot(text, "id", { now }),
|
||||
kimi: (text) => readKimi(text, "id", {}, { now }),
|
||||
grok: (text) => readGrok(text, "id", {}, { now }),
|
||||
}
|
||||
const fixtures = {
|
||||
claude: [
|
||||
claude("user", "first"),
|
||||
claude("assistant", [{ type: "tool_use", id: "t", name: "Bash", input: { command: "echo secret" } }], { id: "r", usage: { input_tokens: 100, output_tokens: 2 } }),
|
||||
claude("user", [{ type: "tool_result", tool_use_id: "t", content: "result" }]),
|
||||
claude("assistant", [{ type: "text", text: "done" }], { id: "r", usage: { input_tokens: 100, output_tokens: 8 }, stop_reason: "end_turn" }),
|
||||
claude("user", "second"),
|
||||
claude("assistant", [{ type: "text", text: "second reply" }], { id: "r2", usage: { input_tokens: 50, output_tokens: 3 }, stop_reason: "end_turn" }),
|
||||
],
|
||||
codex: [
|
||||
codex("event_msg", { type: "user_message", message: "first" }),
|
||||
codex("response_item", { type: "function_call", call_id: "t", name: "shell", arguments: { command: "echo secret" } }),
|
||||
codex("event_msg", { type: "exec_approval_request", command: "echo secret" }),
|
||||
codex("response_item", { type: "function_call_output", call_id: "t", output: "result" }),
|
||||
codex("event_msg", { type: "token_count", info: { last_token_usage: { input_tokens: 100, cached_input_tokens: 40, output_tokens: 8 }, model_context_window: 200000 } }),
|
||||
codex("event_msg", { type: "task_complete", last_agent_message: "done" }),
|
||||
codex("event_msg", { type: "user_message", message: "second" }),
|
||||
codex("event_msg", { type: "turn_aborted" }),
|
||||
],
|
||||
dsh: [
|
||||
dsh("user/message", { source: { kind: "user" }, content: "first" }),
|
||||
dsh("turn/start"),
|
||||
dsh("tool/call", { callId: "t", name: "shell", arguments: {} }),
|
||||
dsh("approval/asked"),
|
||||
dsh("approval/decided"),
|
||||
dsh("tool/result", { message: { toolCallId: "t" } }),
|
||||
dsh("assistant/message", { message: { content: [{ type: "text", text: "done" }] } }),
|
||||
dsh("turn/end", { reason: { kind: "completed" } }),
|
||||
dsh("user/message", { source: { kind: "user" }, content: "second" }),
|
||||
],
|
||||
gemini: [
|
||||
{ type: "user", timestamp: iso(), content: "first" },
|
||||
{ type: "gemini", timestamp: iso(), toolCalls: [{ id: "t", name: "shell", status: "awaiting_approval" }] },
|
||||
{ type: "gemini", timestamp: iso(), toolCalls: [{ id: "t", name: "shell", status: "executing" }] },
|
||||
{ type: "gemini", timestamp: iso(), toolCalls: [{ id: "t", name: "shell", status: "success" }] },
|
||||
{ type: "gemini", timestamp: iso(), content: "done" },
|
||||
{ type: "user", timestamp: iso(), content: "second" },
|
||||
{ type: "gemini", timestamp: iso(), toolCalls: [{ id: "t2", name: "shell", status: "executing" }] },
|
||||
],
|
||||
pi: [
|
||||
pi("user", "first"),
|
||||
pi("assistant", [{ type: "toolCall", id: "t", name: "shell", arguments: {} }], { stopReason: "toolUse" }),
|
||||
pi("toolResult", "result", { toolCallId: "t" }),
|
||||
pi("assistant", [{ type: "text", text: "done" }], { stopReason: "stop" }),
|
||||
pi("user", "second"),
|
||||
pi("assistant", [], { stopReason: "aborted" }),
|
||||
],
|
||||
copilot: [
|
||||
copilot("session.start", { context: { cwd: "/project" }, selectedModel: "model" }),
|
||||
copilot("user.message", { content: "first" }),
|
||||
copilot("tool.execution_start", { toolCallId: "t", toolName: "shell" }),
|
||||
copilot("tool.execution_complete", { toolCallId: "t" }),
|
||||
copilot("assistant.message", { content: "done" }),
|
||||
copilot("session.end"),
|
||||
copilot("user.message", { content: "second" }),
|
||||
],
|
||||
kimi: [
|
||||
kimi("turn.prompt", { input: "first" }),
|
||||
kimi("context.append_loop_event", { event: { type: "content.part", part: { type: "text", text: "hello " } } }),
|
||||
kimi("context.append_loop_event", { event: { type: "content.part", part: { type: "text", text: "world" } } }),
|
||||
kimi("context.append_loop_event", { event: { type: "tool.call", toolCallId: "t", name: "shell", arguments: {} } }),
|
||||
kimi("interaction.request", { id: "a", kind: "approval" }),
|
||||
kimi("context.append_loop_event", { event: { type: "tool.result", toolCallId: "t" } }),
|
||||
kimi("interaction.resolved", { id: "a" }),
|
||||
kimi("usage.record", { usage: { inputTokens: 100, outputTokens: 8 } }),
|
||||
kimi("turn.ended", { reason: "completed" }),
|
||||
kimi("turn.prompt", { input: "second" }),
|
||||
kimi("context.append_loop_event", { event: { type: "content.part", part: { type: "text", text: "second reply" } } }),
|
||||
],
|
||||
grok: [
|
||||
grok("user_message_chunk", "first ", {}, { turnStartMs: now }),
|
||||
grok("user_message_chunk", "prompt", {}, { turnStartMs: now }),
|
||||
grok("agent_message_chunk", "hello ", {}, { streamStartMs: now + 1 }),
|
||||
grok("agent_message_chunk", "world", {}, { streamStartMs: now + 1 }),
|
||||
grok("tool_call", "", { toolCallId: "t", title: "shell", status: "in_progress" }),
|
||||
grok("tool_call_update", "", { toolCallId: "t", title: "shell renamed", status: "in_progress" }),
|
||||
grok("tool_call_update", "", { toolCallId: "t", status: "completed" }),
|
||||
grok("turn_completed"),
|
||||
grok("user_message_chunk", "second", {}, { turnStartMs: now + 2 }),
|
||||
grok("agent_message_chunk", "second reply", {}, { streamStartMs: now + 3 }),
|
||||
],
|
||||
}
|
||||
|
||||
for (const [kind, events] of Object.entries(fixtures)) {
|
||||
test(`${kind}: appended batches match one-shot parsing at every boundary`, () => {
|
||||
const rows = events.map(j)
|
||||
for (const width of [1, 2, 3, 5]) {
|
||||
const reader = createSessionReader(kind, kind, "id", { now })
|
||||
const stable = reader.session
|
||||
for (let i = 0; i < rows.length; i += width) {
|
||||
const end = Math.min(i + width, rows.length)
|
||||
expect(reader.update(rows.slice(i, end))).toBe(stable)
|
||||
expect(stable).toEqual(fullReaders[kind](rows.slice(0, end).join("\n")))
|
||||
const snapshot = structuredClone(stable)
|
||||
expect(reader.update([], { now })).toEqual(snapshot)
|
||||
}
|
||||
expect(stable.turns).toBe(2)
|
||||
expect(stable.messages.length).toBeLessThanOrEqual(MESSAGES_MAX)
|
||||
expect(stable.messages.some((m) => m.text.includes("secret"))).toBe(false)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
test("Claude: interleaved response IDs replace their prior usage and move days", () => {
|
||||
const before = new Date(2026, 9, 30, 23, 59, 59).getTime()
|
||||
const after = new Date(2026, 9, 31, 0, 0, 1).getTime()
|
||||
const r = createSessionReader("claude", "claude", "id", { now: before })
|
||||
const usage = (id, output, t) => j(claude("assistant", [], { id, usage: { input_tokens: 100, cache_creation_input_tokens: 5, cache_read_input_tokens: 50, output_tokens: output } }, t))
|
||||
r.update([j(claude("user", "first", {}, before)), usage("a", 1, before), usage("b", 10, before)])
|
||||
expect(r.session).toMatchObject({ tokensToday: 221, turnsToday: 1, context: 165 })
|
||||
r.update([usage("a", 20, after)], { now: after })
|
||||
expect(r.session).toMatchObject({ tokensToday: 125, turnsToday: 0, context: 175 })
|
||||
r.update([usage("a", 20, after)], { now: after })
|
||||
expect(r.session.tokensToday).toBe(125)
|
||||
r.update([], { now: before })
|
||||
expect(r.session).toMatchObject({ tokensToday: 115, turnsToday: 1 })
|
||||
// A later correction may lower an already-accounted response total.
|
||||
r.update([usage("a", 2, before)], { now: before })
|
||||
expect(r.session.tokensToday).toBe(222)
|
||||
r.update([], { now: after })
|
||||
expect(r.session.tokensToday).toBe(0)
|
||||
})
|
||||
|
||||
test("Gemini: tool dedupe survives batches and approval transitions", () => {
|
||||
const r = createSessionReader("gemini")
|
||||
for (const event of fixtures.gemini) r.update([j(event)], { now })
|
||||
expect(r.session.messages.filter((m) => m.role === "tool")).toHaveLength(2)
|
||||
expect(r.session.pending).toMatchObject([{ id: "t2", name: "shell" }])
|
||||
expect(r.session.phase).toBe("tool")
|
||||
r.update([j({ type: "gemini", timestamp: iso(), content: "finished" })], { now })
|
||||
expect(r.session.pending).toHaveLength(0)
|
||||
expect(r.session.phase).toBe("done")
|
||||
})
|
||||
|
||||
test("Grok: metadata and replacement sidecar usage refresh without log input", () => {
|
||||
const r = createSessionReader("grok", "grok", "id", { now })
|
||||
r.update(fixtures.grok.map(j))
|
||||
const messages = structuredClone(r.session.messages)
|
||||
const turns = r.session.turns
|
||||
const usage = { turns: [
|
||||
{ endedAt: iso(), inputTokens: 100, cachedReadTokens: 40, outputTokens: 8 },
|
||||
{ endedAt: iso(nextDay), inputTokens: 20, outputTokens: 3 },
|
||||
] }
|
||||
const meta = { info: { cwd: "/new" }, generated_title: "Renamed", current_model_id: "grok-new", session_kind: "subagent_worker", parent_session_id: "parent" }
|
||||
r.update([], { meta, usage, now })
|
||||
expect(r.session).toMatchObject({ cwd: "/new", project: "new", title: "Renamed", model: "grok-new", tokensToday: 68, turnsToday: 2, subagent: true, parent: "parent" })
|
||||
r.update([], { meta, usage, now })
|
||||
expect(r.session.tokensToday).toBe(68)
|
||||
usage.turns[0].outputTokens = 12
|
||||
r.update([], { usage, now })
|
||||
expect(r.session.tokensToday).toBe(72)
|
||||
r.update([], { now: nextDay })
|
||||
expect(r.session).toMatchObject({ tokensToday: 23, turnsToday: 0 })
|
||||
expect(r.session.messages).toEqual(messages)
|
||||
expect(r.session.turns).toBe(turns)
|
||||
r.update([], { usage: null, now })
|
||||
expect(r.session.tokensToday).toBe(0)
|
||||
expect(r.session.turnsToday).toBe(2)
|
||||
})
|
||||
|
||||
test("Kimi: metadata refresh preserves approval and active reply text", () => {
|
||||
const r = createSessionReader("kimi", "kimi", "parent/child", { now })
|
||||
r.update([j(kimi("turn.prompt", { input: "hello" })), j(kimi("context.append_loop_event", { event: { type: "content.part", part: { type: "text", text: "hello " } } })), j(kimi("interaction.request", { id: "a", kind: "question" }))])
|
||||
r.update([], { meta: { cwd: "/new", title: "new title", modelAlias: "kimi-new" }, now })
|
||||
expect(r.session).toMatchObject({ subagent: true, parent: "parent", phase: "ask", title: "new title", cwd: "/new", model: "kimi-new", turns: 1 })
|
||||
r.update([j(kimi("interaction.resolved", { id: "a" })), j(kimi("context.append_loop_event", { event: { type: "content.part", part: { type: "text", text: "world" } } }))])
|
||||
expect(r.session.reply).toBe("hello world")
|
||||
})
|
||||
|
||||
const sidecars = {
|
||||
kimi: { title: "Named", cwd: "/old", modelAlias: "model", createdAt: iso(now - 10000) },
|
||||
grok: { title: "Named", info: { cwd: "/old" }, current_model_id: "model", session_kind: "subagent_worker", parent_session_id: "parent", created_at: iso(now - 10000) },
|
||||
}
|
||||
const readWithMeta = (kind, rows, meta, usage) => kind === "kimi"
|
||||
? readKimi(rows.join("\n"), "id", meta, { now })
|
||||
: readGrok(rows.join("\n"), "id", meta, { now, usage })
|
||||
|
||||
for (const kind of ["kimi", "grok"]) {
|
||||
test(`${kind}: metadata snapshots replace all fields and restore parsed fallbacks`, () => {
|
||||
const usage = { turns: [{ endedAt: iso(), inputTokens: 100, outputTokens: 8 }] }
|
||||
const rows = fixtures[kind].map(j)
|
||||
for (const meta of [{}, null, undefined, { title: "Replacement" }, kind === "kimi" ? { cwd: "/new" } : { info: { cwd: "/new" } }, kind === "kimi" ? { model: "new-model" } : { current_model_id: "new-model" }, { parent_session_id: "orphan" }]) {
|
||||
const r = createSessionReader(kind, kind, "id", { now, meta: sidecars[kind], usage })
|
||||
const stable = r.session
|
||||
r.update(rows)
|
||||
expect(stable.title).toBe("Named")
|
||||
expect(r.update([], { meta })).toBe(stable)
|
||||
expect(stable).toEqual(readWithMeta(kind, rows, meta, usage))
|
||||
expect(stable.started).toBe(now)
|
||||
expect(stable.subagent).toBe(false)
|
||||
expect(stable.parent).toBe("")
|
||||
if (!meta?.title) expect(stable.title).toBe(kind === "kimi" ? "first" : "first prompt")
|
||||
const snapshot = structuredClone(stable)
|
||||
r.update([]) // omitting meta preserves the latest snapshot
|
||||
expect(stable).toEqual(snapshot)
|
||||
finalizeUsage(stable, nextDay)
|
||||
expect(stable).toMatchObject({ tokensToday: 0, turnsToday: 0 })
|
||||
finalizeUsage(stable, now)
|
||||
expect(stable.tokensToday).toBe(108)
|
||||
expect(stable.turnsToday).toBe(2)
|
||||
}
|
||||
})
|
||||
|
||||
test(`${kind}: removing metadata between stream chunks preserves text, usage and first prompt`, () => {
|
||||
const prompt = (text) => kind === "kimi" ? kimi("turn.prompt", { input: text }) : grok("user_message_chunk", text, {}, { turnStartMs: now })
|
||||
const chunk = (text) => kind === "kimi" ? kimi("context.append_loop_event", { event: { type: "content.part", part: { type: "text", text } } }) : grok("agent_message_chunk", text, {}, { streamStartMs: now + 1 })
|
||||
const usage = { turns: [{ endedAt: iso(), inputTokens: 100, outputTokens: 8 }] }
|
||||
const r = createSessionReader(kind, kind, "id", { now, meta: sidecars[kind], usage })
|
||||
const rows = [j(prompt("first "))]
|
||||
r.update(rows)
|
||||
if (kind === "grok") {
|
||||
r.update([], { meta: null })
|
||||
rows.push(j(prompt("prompt")))
|
||||
r.update(rows.slice(-1))
|
||||
expect(r.session.title).toBe("first prompt")
|
||||
}
|
||||
if (kind === "kimi") {
|
||||
rows.push(j(kimi("usage.record", { usage: { inputTokens: 100, outputTokens: 8 } })))
|
||||
r.update(rows.slice(-1))
|
||||
}
|
||||
rows.push(j(chunk("hello ")))
|
||||
r.update(rows.slice(-1))
|
||||
const messages = structuredClone(r.session.messages)
|
||||
const counts = { turns: r.session.turns, turnsToday: r.session.turnsToday, tokensToday: r.session.tokensToday }
|
||||
for (const meta of [{ title: "Changed" }, {}, null]) {
|
||||
r.update([], { meta })
|
||||
expect(r.session.messages).toEqual(messages)
|
||||
expect(r.session).toMatchObject(counts)
|
||||
}
|
||||
rows.push(j(chunk("world")))
|
||||
r.update(rows.slice(-1))
|
||||
expect(r.session.reply).toBe("hello world")
|
||||
expect(r.session.messages.at(-1).text).toBe("hello world")
|
||||
expect(r.session).toEqual(readWithMeta(kind, rows, {}, usage))
|
||||
finalizeUsage(r.session, now)
|
||||
expect(r.session.tokensToday).toBe(108)
|
||||
})
|
||||
|
||||
test(`${kind}: log model and cwd take precedence while metadata titles override`, () => {
|
||||
const events = kind === "kimi"
|
||||
? [kimi("profile.bind", { modelAlias: "log-model", environmentDisclosure: { cwd: "/log" } }), ...fixtures.kimi.slice(0, 3)]
|
||||
: [grok("user_message_chunk", "first ", {}, { turnStartMs: now, modelId: "log-model" }), ...fixtures.grok.slice(1, 4)]
|
||||
const rows = events.map(j)
|
||||
const r = createSessionReader(kind, kind, "id", { now, meta: sidecars[kind] })
|
||||
r.update(rows)
|
||||
const expected = { model: "log-model", title: "Named" }
|
||||
if (kind === "kimi") Object.assign(expected, { cwd: "/log", project: "log" })
|
||||
expect(r.session).toMatchObject(expected)
|
||||
for (const meta of [sidecars[kind], { ...sidecars[kind], title: "New title" }, {}, null]) {
|
||||
r.update([], { meta })
|
||||
expect(r.session).toEqual(readWithMeta(kind, rows, meta))
|
||||
expect(r.session.model).toBe("log-model")
|
||||
if (kind === "kimi") expect(r.session.cwd).toBe("/log")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
test("Grok: removing individual child metadata fields clears only their own effects", () => {
|
||||
const rows = fixtures.grok.map(j)
|
||||
const r = createSessionReader("grok", "grok", "id", { now, meta: sidecars.grok })
|
||||
r.update(rows)
|
||||
for (const field of Object.keys(sidecars.grok)) {
|
||||
const meta = { ...sidecars.grok }
|
||||
delete meta[field]
|
||||
r.update([], { meta })
|
||||
expect(r.session).toEqual(readWithMeta("grok", rows, meta))
|
||||
if (field === "parent_session_id") expect(r.session).toMatchObject({ subagent: true, parent: "" })
|
||||
if (field === "session_kind") expect(r.session).toMatchObject({ subagent: false, parent: "" })
|
||||
}
|
||||
})
|
||||
|
||||
test("Kimi: removing metadata preserves child identity derived from the session id", () => {
|
||||
const rows = fixtures.kimi.map(j)
|
||||
const r = createSessionReader("kimi", "kimi", "parent/child", { now, meta: sidecars.kimi })
|
||||
r.update(rows)
|
||||
r.update([], { meta: null })
|
||||
expect(r.session).toEqual(readKimi(rows.join("\n"), "parent/child", {}, { now }))
|
||||
expect(r.session).toMatchObject({ subagent: true, parent: "parent", title: "first", cwd: "", model: "" })
|
||||
})
|
||||
|
||||
test("Kimi and Grok: whitespace and bounded reply streams survive updates and reset at turns", () => {
|
||||
for (const kind of ["kimi", "grok"]) {
|
||||
const r = createSessionReader(kind, kind, "id", { now })
|
||||
const prompt = (text) => kind === "kimi" ? kimi("turn.prompt", { input: text }) : grok("user_message_chunk", text)
|
||||
const chunk = (text) => kind === "kimi" ? kimi("context.append_loop_event", { event: { type: "content.part", part: { type: "text", text } } }) : grok("agent_message_chunk", text)
|
||||
r.update([j(prompt("first"))])
|
||||
for (const text of [" ".repeat(5000), "hello", " ", "世界", " ", "x".repeat(10000)]) r.update([j(chunk(text))])
|
||||
expect(r.session.reply.startsWith("hello 世界 ")).toBe(true)
|
||||
expect(r.session.reply.length).toBeLessThanOrEqual(TEXT_MAX)
|
||||
expect(r.session.messages.at(-1).text.length).toBeLessThanOrEqual(MESSAGE_TEXT_MAX)
|
||||
r.update([j(prompt("second"))])
|
||||
r.update([j(chunk("second reply"))])
|
||||
expect(r.session.reply).toBe("second reply")
|
||||
expect(r.session.turns).toBe(2)
|
||||
}
|
||||
})
|
||||
|
||||
test("every reader parses only new input and no lines on an empty update", () => {
|
||||
const parse = JSON.parse
|
||||
const rows = new Set(Object.values(fixtures).flat().map(j))
|
||||
let parsed = 0
|
||||
JSON.parse = function (text, ...args) {
|
||||
if (rows.has(text)) parsed++
|
||||
return parse.call(this, text, ...args)
|
||||
}
|
||||
try {
|
||||
for (const [kind, events] of Object.entries(fixtures)) {
|
||||
const r = createSessionReader(kind, kind, "id", { now })
|
||||
parsed = 0
|
||||
for (const event of events) r.update([j(event)])
|
||||
expect(parsed).toBe(events.length)
|
||||
r.update([], { meta: { title: "changed" }, now: nextDay })
|
||||
expect(parsed).toBe(events.length)
|
||||
expect(r.session).toMatchObject({ tokensToday: 0, turnsToday: 0 })
|
||||
r.update([], { now })
|
||||
expect(r.session.turnsToday).toBe(2)
|
||||
}
|
||||
} finally { JSON.parse = parse }
|
||||
})
|
||||
|
||||
test("one-shot Gemini documents and alternate agent names remain compatible", () => {
|
||||
const document = { sessionId: "document-id", startTime: iso(), messages: fixtures.gemini }
|
||||
const result = readGemini(JSON.stringify(document, null, 2), "qwen", "fallback", { now })
|
||||
expect(result).toMatchObject({ id: "document-id", agent: "qwen", turns: 2, phase: "tool" })
|
||||
const qwen = createSessionReader("gemini", "qwen", "id", { now })
|
||||
qwen.update(fixtures.gemini.map(j))
|
||||
expect(qwen.session.agent).toBe("qwen")
|
||||
const omp = createSessionReader("pi", "omp", "id", { now })
|
||||
omp.update(fixtures.pi.map(j))
|
||||
expect(omp.session).toMatchObject({ agent: "omp", turns: 2, phase: "aborted" })
|
||||
const child = createSessionReader("claude", "claude", "child", { now, subagent: true })
|
||||
child.update([j({ ...fixtures.claude[0], isSidechain: true })])
|
||||
expect(child.session).toMatchObject({ subagent: true, turns: 1 })
|
||||
})
|
||||
|
||||
test("all JSONL readers accept leading whitespace and retain only bounded messages", () => {
|
||||
for (const [kind, events] of Object.entries(fixtures)) {
|
||||
const r = createSessionReader(kind, kind, "id", { now })
|
||||
for (let i = 0; i < 20; i++) r.update(events.map((e) => ` \t${j(e)}`))
|
||||
expect(r.session.turns).toBe(40)
|
||||
expect(r.session.messages.length).toBeLessThanOrEqual(MESSAGES_MAX)
|
||||
expect(r.session.messages.every((m) => m.text.length <= MESSAGE_TEXT_MAX)).toBe(true)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,233 @@
|
||||
import { afterAll, expect, test } from "bun:test"
|
||||
import { appendFileSync, mkdirSync, mkdtempSync, readSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { createScanner } from "./lib/scan.mjs"
|
||||
|
||||
const roots=[]
|
||||
const tmp=()=>{const root=mkdtempSync(join(tmpdir(),"office-incremental-"));roots.push(root);return root}
|
||||
afterAll(()=>{for(const root of roots)rmSync(root,{recursive:true,force:true})})
|
||||
const line=x=>JSON.stringify(x)+"\n"
|
||||
const time=Date.now(), stamp=new Date(time).toISOString()
|
||||
const user=text=>({type:"user",timestamp:stamp,cwd:"/fixture",message:{role:"user",content:text}})
|
||||
const done=(id="r1",output=10)=>({type:"assistant",timestamp:stamp,message:{id,role:"assistant",stop_reason:"end_turn",usage:{input_tokens:100,output_tokens:output},content:[{type:"text",text:"done"}]}})
|
||||
const source=(root,kind="claude",extra={})=>({root,kind,agent:kind,depth:0,match:n=>n.endsWith(".jsonl"),...extra})
|
||||
function tracked(sources) {
|
||||
const reads=[]
|
||||
const scanner=createScanner({sources,readSync(fd,buf,offset,length,position){const n=readSync(fd,buf,offset,length,position);reads.push({position,length,n});return n}})
|
||||
return {scanner,reads,bytes:()=>reads.reduce((sum,r)=>sum+r.n,0),reset:()=>{reads.length=0}}
|
||||
}
|
||||
|
||||
test("a one-line append to a 100 MiB session reads the line plus at most 128 guard bytes",()=>{
|
||||
const root=tmp(),path=join(root,"large.jsonl")
|
||||
const padding=line({type:"padding",text:"x".repeat(4000)})
|
||||
writeFileSync(path,line(user("old"))+padding.repeat(Math.ceil(100*1024*1024/Buffer.byteLength(padding)))+line(done()))
|
||||
const {scanner,reads,bytes,reset}=tracked([source(root)])
|
||||
const size=statSync(path).size
|
||||
expect(size).toBeGreaterThanOrEqual(100*1024*1024)
|
||||
expect(scanner.scan(time)[0]).toMatchObject({turns:1,tokensToday:110,phase:"done"})
|
||||
expect(bytes()).toBe(size)
|
||||
const reader=scanner.files.get(path).reader
|
||||
const appended=line(user("new work"))
|
||||
appendFileSync(path,appended)
|
||||
reset()
|
||||
expect(scanner.scan(time)[0]).toMatchObject({turns:2,query:"new work",tokensToday:110,phase:"thinking"})
|
||||
expect(scanner.files.get(path).reader).toBe(reader)
|
||||
expect(bytes()).toBe(Buffer.byteLength(appended)+128)
|
||||
expect(reads.at(-1).position).toBe(size)
|
||||
reset();scanner.scan(time);expect(bytes()).toBe(0)
|
||||
},15000)
|
||||
|
||||
test("UTF-8 and JSON split between scan ticks are carried without replay or duplicate turns",()=>{
|
||||
const root=tmp(),path=join(root,"partial.jsonl")
|
||||
const record=Buffer.from(line(user("hello 世界 🌍")))
|
||||
const split=record.indexOf(Buffer.from("世"))+1
|
||||
writeFileSync(path,record.subarray(0,split))
|
||||
const {scanner,bytes,reset}=tracked([source(root)])
|
||||
expect(scanner.scan(time)[0].turns).toBe(0)
|
||||
reset();appendFileSync(path,record.subarray(split))
|
||||
expect(scanner.scan(time)[0]).toMatchObject({turns:1,query:"hello 世界 🌍",phase:"thinking"})
|
||||
expect(bytes()).toBe(record.length-split+128)
|
||||
const tool=line({type:"assistant",timestamp:stamp,message:{role:"assistant",stop_reason:"tool_use",content:[{type:"tool_use",id:"tool",name:"Bash",input:{command:"test"}}]}})
|
||||
appendFileSync(path,tool)
|
||||
expect(scanner.scan(time)[0]).toMatchObject({phase:"tool",pending:[{id:"tool"}]})
|
||||
appendFileSync(path,line({type:"user",timestamp:stamp,message:{role:"user",content:[{type:"tool_result",tool_use_id:"tool",content:"ok"}]}}))
|
||||
expect(scanner.scan(time)[0]).toMatchObject({turns:1,phase:"thinking",pending:[]})
|
||||
})
|
||||
|
||||
test("a complete record flushed before its newline is applied exactly once",()=>{
|
||||
const root=tmp(),path=join(root,"eof.jsonl")
|
||||
writeFileSync(path,JSON.stringify(user("once")))
|
||||
const {scanner,bytes,reset}=tracked([source(root)])
|
||||
expect(scanner.scan(time)[0].turns).toBe(1)
|
||||
reset();appendFileSync(path,"\r\n")
|
||||
expect(scanner.scan(time)[0].turns).toBe(1)
|
||||
expect(bytes()).toBe(2+128)
|
||||
appendFileSync(path,JSON.stringify(done("response",10)))
|
||||
expect(scanner.scan(time)[0].tokensToday).toBe(110)
|
||||
appendFileSync(path,"\n"+line(done("response",30)))
|
||||
expect(scanner.scan(time)[0]).toMatchObject({turns:1,tokensToday:130})
|
||||
})
|
||||
|
||||
test("a partially written large image record reads new bytes plus bounded guards",()=>{
|
||||
const root=tmp(),path=join(root,"image.jsonl")
|
||||
writeFileSync(path,line(user("before image")))
|
||||
const record=Buffer.from(line({type:"assistant",timestamp:stamp,message:{role:"assistant",content:[{type:"image",source:{type:"base64",data:"A".repeat(2*1024*1024)}}],stop_reason:"end_turn"}}))
|
||||
const {scanner,bytes,reset}=tracked([source(root)])
|
||||
scanner.scan(time)
|
||||
for(let at=0;at<record.length;at+=131071) {
|
||||
const part=record.subarray(at,at+131071)
|
||||
appendFileSync(path,part);reset();scanner.scan(time)
|
||||
expect(bytes()).toBe(part.length+128)
|
||||
}
|
||||
expect(scanner.scan(time)[0]).toMatchObject({phase:"done",query:"before image",turns:1})
|
||||
})
|
||||
|
||||
test("truncation, inode replacement and same-size edits reset parsing state",()=>{
|
||||
const root=tmp(),path=join(root,"rotate.jsonl")
|
||||
writeFileSync(path,line(user("original long query"))+line(done()))
|
||||
const {scanner,reads,reset}=tracked([source(root)])
|
||||
scanner.scan(time)
|
||||
writeFileSync(path,line(user("AA")))
|
||||
reset();expect(scanner.scan(time)[0]).toMatchObject({query:"AA",turns:1,tokensToday:0})
|
||||
expect(reads[0].position).toBe(0)
|
||||
const original=statSync(path)
|
||||
const replacement=join(root,"replacement.tmp")
|
||||
writeFileSync(replacement,line(user("BB replacement"))+line(done("replacement",20)))
|
||||
renameSync(replacement,path)
|
||||
expect(statSync(path).ino).not.toBe(original.ino)
|
||||
reset();expect(scanner.scan(time)[0]).toMatchObject({query:"BB replacement",turns:1,tokensToday:120})
|
||||
expect(reads[0].position).toBe(0)
|
||||
const size=statSync(path).size
|
||||
writeFileSync(path,line(user("CC replacement"))+line(done("replacement",20)))
|
||||
expect(statSync(path).size).toBe(size)
|
||||
utimesSync(path,(time+1000)/1000,(time+1000)/1000)
|
||||
reset();expect(scanner.scan(time)[0].query).toBe("CC replacement")
|
||||
expect(reads[0].position).toBe(0)
|
||||
})
|
||||
|
||||
test("midnight and metadata-only changes do not read JSONL again",()=>{
|
||||
const root=tmp(),path=join(root,"updates.jsonl"),usage=join(root,"usage.json"),meta=join(root,"summary.json")
|
||||
const before=new Date(2026,9,30,23,59,10).getTime(),after=new Date(2026,9,31,0,1).getTime()
|
||||
writeFileSync(path,line({timestamp:before/1000,params:{update:{sessionUpdate:"user_message_chunk",content:{text:"work"}}}}))
|
||||
utimesSync(path,before/1000,before/1000)
|
||||
const use=tokens=>({turns:[{endedAt:new Date(before).toISOString(),inputTokens:tokens,outputTokens:10}]})
|
||||
writeFileSync(usage,JSON.stringify(use(100)));writeFileSync(meta,JSON.stringify({title:"old title"}))
|
||||
const {scanner,bytes,reset}=tracked([source(root,"grok",{usage:()=>usage,meta:()=>meta})])
|
||||
expect(scanner.scan(before)[0]).toMatchObject({title:"old title",tokensToday:110,turnsToday:1})
|
||||
reset();expect(scanner.scan(after)[0]).toMatchObject({tokensToday:0,turnsToday:0})
|
||||
expect(bytes()).toBe(0)
|
||||
writeFileSync(meta,JSON.stringify({title:"new title"}));writeFileSync(usage,JSON.stringify(use(200)))
|
||||
reset();expect(scanner.scan(before)[0]).toMatchObject({title:"new title",tokensToday:210,turnsToday:1})
|
||||
expect(bytes()).toBe(0)
|
||||
const original=JSON.parse
|
||||
let sidecarParses=0
|
||||
JSON.parse=function(text,...args){if(String(text).includes('"endedAt"'))sidecarParses++;return original.call(this,text,...args)}
|
||||
try {
|
||||
appendFileSync(path,line({timestamp:before/1000,params:{update:{sessionUpdate:"agent_message_chunk",content:{text:"hello"}}}}))
|
||||
expect(scanner.scan(before)[0]).toMatchObject({tokensToday:210,title:"new title"})
|
||||
expect(sidecarParses).toBe(0)
|
||||
expect(scanner.files.get(path)).not.toHaveProperty("usageValue")
|
||||
}finally{JSON.parse=original}
|
||||
rmSync(meta)
|
||||
reset();expect(scanner.scan(before)[0]).toMatchObject({title:"work",cwd:"",model:"",subagent:false,tokensToday:210})
|
||||
expect(bytes()).toBe(0)
|
||||
})
|
||||
|
||||
test("changing sources releases cursors and accumulated sessions",()=>{
|
||||
const root=tmp(),other=tmp(),path=join(root,"one.jsonl")
|
||||
writeFileSync(path,line(user("first")))
|
||||
writeFileSync(join(other,"two.jsonl"),line(user("second")))
|
||||
const {scanner,reads,reset}=tracked([source(root)])
|
||||
scanner.scan(time)
|
||||
scanner.setSources([source(other)]);reset()
|
||||
expect(scanner.scan(time)[0]).toMatchObject({query:"second",turns:1})
|
||||
expect(scanner.files.has(path)).toBe(false)
|
||||
expect(reads[0].position).toBe(0)
|
||||
})
|
||||
|
||||
test("truncate-and-regrow between ticks resets when the prefix or previous end changes",()=>{
|
||||
for(const leading of ["",line({type:"padding",text:"constant".repeat(40)})]) {
|
||||
const root=tmp(),path=join(root,"regrow.jsonl")
|
||||
writeFileSync(path,leading+line(user("OLD")))
|
||||
const {scanner}=tracked([source(root)])
|
||||
scanner.scan(time)
|
||||
const old=scanner.files.get(path).reader,size=statSync(path).size
|
||||
writeFileSync(path,leading+line(user("NEW LONGER QUERY after truncate")))
|
||||
expect(statSync(path).size).toBeGreaterThan(size)
|
||||
expect(scanner.scan(time)[0]).toMatchObject({query:"NEW LONGER QUERY after truncate",turns:1})
|
||||
expect(scanner.files.get(path).reader).not.toBe(old)
|
||||
}
|
||||
})
|
||||
|
||||
test("an unfinished quoted brace never reparses its buffered history",()=>{
|
||||
const root=tmp(),path=join(root,"quoted.jsonl")
|
||||
writeFileSync(path,'{"type":"padding","text":"')
|
||||
const {scanner,bytes,reset}=tracked([source(root)])
|
||||
const original=JSON.parse
|
||||
let parseChars=0,calls=0
|
||||
JSON.parse=function(text,...args){parseChars+=String(text).length;calls++;return original.call(this,text,...args)}
|
||||
try {
|
||||
scanner.scan(time)
|
||||
for(let i=0;i<64;i++) {
|
||||
const part="x".repeat(16383)+"}"
|
||||
appendFileSync(path,part);reset();scanner.scan(time)
|
||||
expect(bytes()).toBeLessThanOrEqual(Buffer.byteLength(part)+128)
|
||||
}
|
||||
expect(calls).toBe(0)
|
||||
expect(parseChars).toBe(0)
|
||||
appendFileSync(path,'"}\n'+line(user("complete")))
|
||||
expect(scanner.scan(time)[0].query).toBe("complete")
|
||||
expect(calls).toBe(2)
|
||||
expect(parseChars).toBeLessThan(2*1024*1024)
|
||||
}finally{JSON.parse=original}
|
||||
})
|
||||
|
||||
test("Codex thread titles also reuse an append cursor",()=>{
|
||||
const root=tmp(),sessions=join(root,"sessions"),index=join(root,"session_index.jsonl")
|
||||
mkdirSync(sessions)
|
||||
const id="019a0000-0000-7000-8000-000000000001",path=join(sessions,`rollout-${id}.jsonl`)
|
||||
writeFileSync(path,line({timestamp:stamp,type:"session_meta",payload:{id,cwd:"/fixture"}}))
|
||||
writeFileSync(index,line({id,thread_name:"old title"}))
|
||||
const previous=process.env.CODEX_HOME;process.env.CODEX_HOME=root
|
||||
try {
|
||||
const {scanner,bytes,reset}=tracked([source(sessions,"codex")])
|
||||
expect(scanner.scan(time)[0].title).toBe("old title")
|
||||
reset();scanner.scan(time);expect(bytes()).toBe(0)
|
||||
const more=line({timestamp:stamp,type:"event_msg",payload:{type:"task_complete"}})
|
||||
const title=line({id,thread_name:"new title"})
|
||||
appendFileSync(path,more);appendFileSync(index,title);reset()
|
||||
expect(scanner.scan(time)[0].title).toBe("new title")
|
||||
expect(bytes()).toBeLessThanOrEqual(Buffer.byteLength(more+title)+256)
|
||||
writeFileSync(index,line({id,thread_name:"alt title"}))
|
||||
utimesSync(index,(time+1000)/1000,(time+1000)/1000)
|
||||
expect(scanner.scan(time)[0].title).toBe("alt title")
|
||||
}finally{if(previous===undefined)delete process.env.CODEX_HOME;else process.env.CODEX_HOME=previous}
|
||||
})
|
||||
|
||||
|
||||
test("a transient read failure resumes completed cursor progress without double counting",()=>{
|
||||
const root=tmp(),path=join(root,"retry.jsonl")
|
||||
writeFileSync(path,line(user("initial")))
|
||||
const start=statSync(path).size
|
||||
let fail=false,failed=false
|
||||
const reads=[]
|
||||
const scanner=createScanner({sources:[source(root)],readSync(fd,buf,offset,length,position){
|
||||
if(fail&&!failed&&position>=start+65536){failed=true;throw new Error("synthetic read interruption")}
|
||||
const n=readSync(fd,buf,offset,length,position);reads.push({position,n});return n
|
||||
}})
|
||||
scanner.scan(time)
|
||||
const rows=Array.from({length:80},(_,i)=>line(user(`task ${i} `+"q".repeat(1800)))).join("")
|
||||
appendFileSync(path,rows);fail=true
|
||||
expect(scanner.scan(time)).toHaveLength(1)
|
||||
expect(failed).toBe(true)
|
||||
const progress=scanner.files.get(path).cursor.offset
|
||||
expect(progress).toBeGreaterThan(start)
|
||||
reads.length=0
|
||||
const result=scanner.scan(time)[0]
|
||||
expect(result.turns).toBe(81)
|
||||
expect(result).toMatchObject({query:(`task 79 `+"q".repeat(1800)).slice(0,199)+"…",phase:"thinking"})
|
||||
expect(reads.some(r=>r.position===progress)).toBe(true)
|
||||
expect(reads.reduce((n,r)=>n+r.n,0)).toBe(statSync(path).size-progress+128)
|
||||
expect(result).toMatchObject(createScanner({sources:[source(root)]}).scan(time)[0])
|
||||
})
|
||||
@@ -115,13 +115,13 @@ test("a stuck session the user clears leaves the office until it moves again", (
|
||||
const c = readCodex(fixture("codex-sigterm.jsonl"))
|
||||
const s = { ...c, key: "codex|" + c.id, source: "files", touched: now - 20 * 60e3, updated: now - 20 * 60e3 }
|
||||
const snap = { sessions: [s] }
|
||||
const [a] = M.agents(snap, now, {})
|
||||
const [a] = M.agents(snap, now, { progress: false })
|
||||
expect([a.status, a.sub]).toEqual(["error", "stuck"])
|
||||
expect(M.clearable(a.status)).toBe(true)
|
||||
expect(M.agents(snap, now, { cleared: { [a.key]: a.at } })).toEqual([])
|
||||
expect(M.agents(snap, now, { progress: false, cleared: { [a.key]: a.at } })).toEqual([])
|
||||
// its file moves: it is back
|
||||
const moved = { sessions: [{ ...s, touched: now }] }
|
||||
expect(M.agents(moved, now, { cleared: { [a.key]: a.at } }).map((x) => x.key)).toEqual([a.key])
|
||||
expect(M.agents(moved, now, { progress: false, cleared: { [a.key]: a.at } }).map((x) => x.key)).toEqual([a.key])
|
||||
})
|
||||
|
||||
test("an agent at work can't be cleared", () => {
|
||||
|
||||
@@ -1,15 +1,30 @@
|
||||
// What each agent is really doing, read from the session files the agents
|
||||
// themselves write, as they write them: Claude Code's, Codex's, DeepSeek
|
||||
// Harness's, Gemini CLI's, Qwen Code's, Pi's and omp's, and any agent that
|
||||
// keeps Claude Code's format (Qoder, WorkBuddy, CodeBuddy). Every agent's
|
||||
// own record, whatever model it talks to: one that never passes magpie's
|
||||
// gateway is seen as well as one that does.
|
||||
// Harness's, Gemini CLI's, Qwen Code's, Pi's and omp's, GitHub Copilot CLI's,
|
||||
// Kimi Code's, Grok Build's, and any agent that keeps Claude Code's format
|
||||
// (Qoder, WorkBuddy, CodeBuddy). Every agent's own record, whatever model it
|
||||
// talks to: one that never passes magpie's gateway is seen as well as one
|
||||
// that does.
|
||||
//
|
||||
// Pure: a reader takes a file's text (its tail) and gives a session's facts.
|
||||
// No clock of its own, no I/O; lib/scan.mjs finds and reads the files.
|
||||
// Pure: a reader takes a file's text or JSONL line iterator and gives a session's facts.
|
||||
// No I/O of its own; lib/scan.mjs finds and reads the files and knows today.
|
||||
//
|
||||
// A session's facts: { agent, id, cwd, title, query, model, started, updated,
|
||||
// phase, step, reply, pending, error, turns }
|
||||
// phase, step, reply, pending, error, turns,
|
||||
// messages, tokensToday, turnsToday, context, contextWindow,
|
||||
// subagent, parent, profile }
|
||||
// messages: the last MESSAGES_MAX things said or done, oldest first, each
|
||||
// { role: "user"|"assistant"|"tool", text, name?, at }. A tool entry's text
|
||||
// is only the tool's name: its arguments may carry secrets.
|
||||
// tokensToday/turnsToday: local-calendar-day counts from what the file records.
|
||||
// context/contextWindow: the latest prompt's size and its model window, 0 when
|
||||
// the agent's file does not say.
|
||||
// subagent/parent/profile: a child session and the session (or agent profile)
|
||||
// it belongs to.
|
||||
//
|
||||
// The Kimi, Grok and Copilot readers adapt the file formats described by
|
||||
// whatsmyagentdoing (https://github.com/Charonyuu/whatsmyagentdoing, MIT);
|
||||
// its parser is the reference for their event shapes.
|
||||
// phase is what its own record last said:
|
||||
// "thinking" a turn is under way, the model has the word
|
||||
// "tool" a tool call it made has no result yet
|
||||
@@ -22,6 +37,8 @@
|
||||
export const TEXT_MAX = 280
|
||||
export const QUERY_MAX = 200
|
||||
export const TITLE_MAX = 48
|
||||
export const MESSAGES_MAX = 8
|
||||
export const MESSAGE_TEXT_MAX = 500
|
||||
|
||||
export function clip(s, n) {
|
||||
s = String(s ?? "").replace(/\s+/g, " ").trim()
|
||||
@@ -48,13 +65,15 @@ export function toolLine(name, args) {
|
||||
return s ? `${name} · ${s}` : String(name)
|
||||
}
|
||||
|
||||
function lines(text) {
|
||||
const out = []
|
||||
for (const l of String(text).split("\n")) {
|
||||
if (!l || l[0] !== "{") continue
|
||||
try { out.push(JSON.parse(l)) } catch {}
|
||||
function* lines(text) {
|
||||
// The scanner supplies complete appended JSONL lines. Consume each batch
|
||||
// immediately without retaining raw text or parsed events between updates.
|
||||
const input = typeof text === "string" ? text.split("\n") : text || []
|
||||
for (const l of input) {
|
||||
const line = typeof l === "string" ? l.trimStart() : ""
|
||||
if (!line || line[0] !== "{") continue
|
||||
try { yield JSON.parse(line) } catch {}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function ms(t) {
|
||||
@@ -63,6 +82,77 @@ function ms(t) {
|
||||
return Number.isFinite(n) ? n : 0
|
||||
}
|
||||
|
||||
// Local calendar day, like the wall clock a person reading the dashboard sees.
|
||||
function dayKey(t) {
|
||||
const d = new Date(t)
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`
|
||||
}
|
||||
|
||||
// Per-day usage lives off the session object: it never travels to the page.
|
||||
const BUCKETS = new WeakMap() // session -> Map(day -> { turns, tokens })
|
||||
function bucket(s, t) {
|
||||
if (!t) return null
|
||||
let days = BUCKETS.get(s)
|
||||
if (!days) BUCKETS.set(s, (days = new Map()))
|
||||
const k = dayKey(t)
|
||||
let b = days.get(k)
|
||||
if (!b) days.set(k, (b = { turns: 0, tokens: 0 }))
|
||||
return b
|
||||
}
|
||||
function countTurn(s, t) {
|
||||
const b = bucket(s, t)
|
||||
if (b) b.turns++
|
||||
}
|
||||
function adjustTokens(s, t, n) {
|
||||
if (!Number.isFinite(n) || n === 0) return
|
||||
const b = bucket(s, t)
|
||||
if (b) b.tokens += n
|
||||
}
|
||||
function addTokens(s, t, n) {
|
||||
if (!Number.isFinite(n) || n <= 0) return
|
||||
const b = bucket(s, t)
|
||||
if (b) b.tokens += n
|
||||
}
|
||||
export function finalizeUsage(s, now) {
|
||||
const b = BUCKETS.get(s)?.get(dayKey(now))
|
||||
s.tokensToday = b ? Math.round(b.tokens) : 0
|
||||
s.turnsToday = b ? b.turns : 0
|
||||
}
|
||||
|
||||
// Preserve a trailing separator until the next chunk, but normalize runs so
|
||||
// whitespace-only chunks cannot consume the whole bounded text buffer.
|
||||
function appendChunk(text, chunk, max) {
|
||||
return (text + String(chunk ?? "")).replace(/\s+/g, " ").trimStart().slice(0, max + 2)
|
||||
}
|
||||
|
||||
// A tool's arguments can hold secrets; a message keeps only its name.
|
||||
const STREAMS = new WeakMap() // session -> { role, text, msg }
|
||||
function streamMsg(s, role, chunk, t) {
|
||||
let st = STREAMS.get(s)
|
||||
if (!st && !chunk) return
|
||||
if (!st || st.role !== role) {
|
||||
st = { role, text: "", msg: { role, text: "", at: t || 0 } }
|
||||
s.messages.push(st.msg)
|
||||
STREAMS.set(s, st)
|
||||
while (s.messages.length > MESSAGES_MAX) s.messages.shift()
|
||||
}
|
||||
// Keep raw, bounded text between chunks; clip only the displayed value.
|
||||
// Trimming each chunk turns ["hello ", "world"] into "helloworld".
|
||||
st.text = appendChunk(st.text, chunk, MESSAGE_TEXT_MAX)
|
||||
st.msg.text = clip(st.text, MESSAGE_TEXT_MAX)
|
||||
}
|
||||
function endStream(s) { STREAMS.delete(s) }
|
||||
|
||||
function message(s, role, text, t, name, stream = false) {
|
||||
if (!text) return
|
||||
if (stream) { streamMsg(s, role, text, t); return }
|
||||
endStream(s)
|
||||
const m = { role, text: clip(text, MESSAGE_TEXT_MAX), at: t || 0 }
|
||||
if (name) m.name = String(name)
|
||||
s.messages.push(m)
|
||||
while (s.messages.length > MESSAGES_MAX) s.messages.shift()
|
||||
}
|
||||
|
||||
function textOf(content) {
|
||||
if (typeof content === "string") return content
|
||||
if (!Array.isArray(content)) return ""
|
||||
@@ -87,7 +177,9 @@ function base(p) {
|
||||
|
||||
function fresh(agent, id) {
|
||||
return { agent, id, cwd: "", project: "", title: "", query: "", model: "", started: 0, updated: 0,
|
||||
phase: "", step: "", stepName: "", reply: "", pending: [], error: "", turns: 0 }
|
||||
phase: "", step: "", stepName: "", reply: "", pending: [], error: "", turns: 0,
|
||||
messages: [], tokensToday: 0, turnsToday: 0, context: 0, contextWindow: 0,
|
||||
subagent: false, parent: "", profile: "" }
|
||||
}
|
||||
|
||||
function touch(s, t) {
|
||||
@@ -102,10 +194,12 @@ function prompted(s, text, t) {
|
||||
s.query = clip(q, QUERY_MAX)
|
||||
if (!s.title) s.title = clip(q, TITLE_MAX)
|
||||
s.turns++
|
||||
countTurn(s, t)
|
||||
s.phase = "thinking"
|
||||
s.reply = ""
|
||||
s.error = ""
|
||||
s.pending = []
|
||||
message(s, "user", q, t)
|
||||
touch(s, t)
|
||||
return true
|
||||
}
|
||||
@@ -116,6 +210,7 @@ function called(s, id, name, args, t) {
|
||||
s.step = line
|
||||
s.stepName = String(name)
|
||||
s.phase = ASK_TOOLS.test(name) ? "ask" : "tool"
|
||||
message(s, "tool", String(name || "tool"), t, String(name || "tool"))
|
||||
touch(s, t)
|
||||
}
|
||||
|
||||
@@ -131,36 +226,60 @@ function answered(s, id, t) {
|
||||
// ~/.claude/projects/<folder>/<session>.jsonl: one line per message; an
|
||||
// assistant message with tool_use blocks, then a user message whose
|
||||
// tool_result blocks answer them; stop_reason "end_turn" ends the turn.
|
||||
export function readClaude(text, agent = "claude", id = "") {
|
||||
const s = fresh(agent, id)
|
||||
for (const d of lines(text)) {
|
||||
function claudeEvents(s, opts) {
|
||||
if (opts.subagent) s.subagent = true
|
||||
const responseUsage = new Map()
|
||||
return (d) => {
|
||||
const t = ms(d.timestamp)
|
||||
if (d.sessionId && !s.id) s.id = d.sessionId
|
||||
if (d.cwd) { s.cwd = d.cwd; s.project = base(d.cwd) }
|
||||
if (d.type === "custom-title" && d.customTitle) { s.title = clip(d.customTitle, TITLE_MAX); s.named = true }
|
||||
else if (d.type === "ai-title" && d.aiTitle && !s.named) s.title = clip(d.aiTitle, TITLE_MAX)
|
||||
if (d.isSidechain) continue
|
||||
if (d.isSidechain && !s.subagent) return
|
||||
const m = d.message
|
||||
if (!m) continue
|
||||
if (!m) return
|
||||
if (d.type === "user" && m.role === "user") {
|
||||
if (Array.isArray(m.content)) {
|
||||
let results = 0
|
||||
for (const b of m.content) if (b?.type === "tool_result") { answered(s, b.tool_use_id, t); results++ }
|
||||
if (results) continue
|
||||
if (results) return
|
||||
const txt = textOf(m.content)
|
||||
if (/^\[Request interrupted/.test(txt.trim())) { s.phase = "aborted"; s.pending = []; touch(s, t); continue }
|
||||
if (/^\[Request interrupted/.test(txt.trim())) { s.phase = "aborted"; s.pending = []; touch(s, t); return }
|
||||
if (!d.isMeta) prompted(s, txt, t)
|
||||
} else if (!d.isMeta) {
|
||||
if (/^\[Request interrupted/.test(String(m.content).trim())) { s.phase = "aborted"; s.pending = []; touch(s, t); continue }
|
||||
if (/^\[Request interrupted/.test(String(m.content).trim())) { s.phase = "aborted"; s.pending = []; touch(s, t); return }
|
||||
prompted(s, m.content, t)
|
||||
}
|
||||
continue
|
||||
return
|
||||
}
|
||||
if (d.type === "assistant" && m.role === "assistant") {
|
||||
if (m.model && m.model !== "<synthetic>") s.model = m.model
|
||||
// A response can appear once per content block, with a later block
|
||||
// updating its output usage. Count its final record once, even if other
|
||||
// responses were interleaved between its blocks.
|
||||
const u = m.usage
|
||||
if (u && typeof u === "object") {
|
||||
const n = (k) => (Number.isFinite(u[k]) ? u[k] : 0)
|
||||
const prompt = n("input_tokens") + n("cache_creation_input_tokens") + n("cache_read_input_tokens")
|
||||
const out = n("output_tokens")
|
||||
if (prompt + out > 0) {
|
||||
s.context = prompt + out
|
||||
// A prompt past 200k is the long-context window; Claude does not
|
||||
// record the window itself.
|
||||
s.contextWindow = s.context > 200_000 ? 1_000_000 : 200_000
|
||||
}
|
||||
const tokens = n("input_tokens") + n("cache_creation_input_tokens") + out
|
||||
if (m.id != null) {
|
||||
const old = responseUsage.get(m.id)
|
||||
if (old) adjustTokens(s, old.t, -old.tokens)
|
||||
responseUsage.set(m.id, { t, tokens })
|
||||
addTokens(s, t, tokens)
|
||||
}
|
||||
else addTokens(s, t, tokens)
|
||||
}
|
||||
const blocks = Array.isArray(m.content) ? m.content : []
|
||||
const txt = blocks.filter((b) => b?.type === "text").map((b) => b.text).join("\n").trim()
|
||||
if (txt) s.reply = clip(txt, TEXT_MAX)
|
||||
if (txt) { s.reply = clip(txt, TEXT_MAX); message(s, "assistant", txt, t) }
|
||||
for (const b of blocks) if (b?.type === "tool_use") called(s, b.id, b.name, b.input, t)
|
||||
if (d.isApiErrorMessage) { s.phase = "error"; s.error = clip(txt, 160); s.pending = [] }
|
||||
else if (m.stop_reason === "end_turn" || m.stop_reason === "stop_sequence") { s.phase = "done"; s.pending = [] }
|
||||
@@ -168,7 +287,6 @@ export function readClaude(text, agent = "claude", id = "") {
|
||||
touch(s, t)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ---- Codex ----------------------------------------------------------------
|
||||
@@ -176,16 +294,15 @@ export function readClaude(text, agent = "claude", id = "") {
|
||||
// response_items (messages, function_call / custom_tool_call and their
|
||||
// outputs) and event_msgs (task_started, task_complete, turn_aborted,
|
||||
// *_approval_request, error).
|
||||
export function readCodex(text, id = "") {
|
||||
const s = fresh("codex", id)
|
||||
for (const d of lines(text)) {
|
||||
function codexEvents(s, opts) {
|
||||
return (d) => {
|
||||
const t = ms(d.timestamp)
|
||||
const p = d.payload || {}
|
||||
if (d.type === "session_meta") {
|
||||
s.id = p.id || p.session_id || s.id
|
||||
if (p.cwd) { s.cwd = p.cwd; s.project = base(p.cwd) }
|
||||
touch(s, ms(p.timestamp) || t)
|
||||
continue
|
||||
return
|
||||
}
|
||||
if (d.type === "turn_context" && p.cwd) { s.cwd = p.cwd; s.project = base(p.cwd); if (p.model) s.model = p.model }
|
||||
if (d.type === "event_msg") {
|
||||
@@ -204,16 +321,26 @@ export function readCodex(text, id = "") {
|
||||
touch(s, t)
|
||||
break
|
||||
case "request_user_input": s.phase = "ask"; touch(s, t); break
|
||||
case "agent_message": if (p.message) s.reply = clip(p.message, TEXT_MAX); touch(s, t); break
|
||||
case "token_count": {
|
||||
const last = p.info?.last_token_usage
|
||||
if (last && typeof last === "object") {
|
||||
const n = (k) => (Number.isFinite(last[k]) ? last[k] : 0)
|
||||
s.context = n("input_tokens") + n("output_tokens")
|
||||
if (Number.isFinite(p.info?.model_context_window) && p.info.model_context_window > 0) s.contextWindow = p.info.model_context_window
|
||||
addTokens(s, t, n("input_tokens") - n("cached_input_tokens") + n("output_tokens"))
|
||||
}
|
||||
break
|
||||
}
|
||||
case "agent_message": if (p.message) { s.reply = clip(p.message, TEXT_MAX); message(s, "assistant", p.message, t) } touch(s, t); break
|
||||
case "task_complete":
|
||||
s.phase = "done"; s.pending = []
|
||||
if (p.last_agent_message) s.reply = clip(p.last_agent_message, TEXT_MAX)
|
||||
if (p.last_agent_message) { s.reply = clip(p.last_agent_message, TEXT_MAX); message(s, "assistant", p.last_agent_message, ms(p.completed_at) || t) }
|
||||
touch(s, ms(p.completed_at) || t)
|
||||
break
|
||||
case "turn_aborted": s.phase = "aborted"; s.pending = []; touch(s, ms(p.completed_at) || t); break
|
||||
case "error": s.phase = "error"; s.error = clip(p.message, 160); s.pending = []; touch(s, t); break
|
||||
}
|
||||
continue
|
||||
return
|
||||
}
|
||||
if (d.type === "response_item") {
|
||||
switch (p.type) {
|
||||
@@ -222,23 +349,21 @@ export function readCodex(text, id = "") {
|
||||
case "local_shell_call": called(s, p.call_id, "shell", { command: p.action?.command }, t); break
|
||||
case "function_call_output": case "custom_tool_call_output": case "local_shell_call_output": answered(s, p.call_id, t); break
|
||||
case "message":
|
||||
if (p.role === "assistant") { const x = textOf(p.content).trim(); if (x) s.reply = clip(x, TEXT_MAX) }
|
||||
if (p.role === "assistant") { const x = textOf(p.content).trim(); if (x) { s.reply = clip(x, TEXT_MAX); message(s, "assistant", x, t) } }
|
||||
touch(s, t)
|
||||
break
|
||||
case "reasoning": if (s.phase !== "tool" && s.phase !== "approval") s.phase = s.phase === "done" ? "done" : "thinking"; touch(s, t); break
|
||||
}
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ---- DeepSeek Harness -----------------------------------------------------
|
||||
// ~/.dsh/sessions/<folder>/<session>/session.v4.jsonl.zstd: typed events —
|
||||
// session, turn/start, tool/call, approval/asked, approval/decided,
|
||||
// tool/result, assistant/message, turn/end {reason: completed|aborted|error}.
|
||||
export function readDsh(text, id = "") {
|
||||
const s = fresh("dsh", id)
|
||||
for (const d of lines(text)) {
|
||||
function dshEvents(s, opts) {
|
||||
return (d) => {
|
||||
const t = ms(d.time || d.createdAt)
|
||||
const x = d.data || {}
|
||||
switch (d.type) {
|
||||
@@ -255,7 +380,7 @@ export function readDsh(text, id = "") {
|
||||
case "assistant/message": {
|
||||
const c = x.message?.content
|
||||
const txt = Array.isArray(c) ? c.filter((b) => b?.type === "text").map((b) => b.text).join("\n").trim() : ""
|
||||
if (txt) s.reply = clip(txt, TEXT_MAX)
|
||||
if (txt) { s.reply = clip(txt, TEXT_MAX); message(s, "assistant", txt, t) }
|
||||
touch(s, t)
|
||||
break
|
||||
}
|
||||
@@ -270,42 +395,32 @@ export function readDsh(text, id = "") {
|
||||
}
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ---- Gemini CLI / Qwen Code -----------------------------------------------
|
||||
// ~/.gemini/tmp/<project>/chats/session-*.json(l): messages, the model's
|
||||
// with toolCalls each carrying a status (scheduled, awaiting_approval,
|
||||
// executing, success, error, cancelled).
|
||||
export function readGemini(text, agent = "gemini", id = "") {
|
||||
const s = fresh(agent, id)
|
||||
let msgs = []
|
||||
const trimmed = String(text).trim()
|
||||
if (trimmed.startsWith("{") && !trimmed.includes("\n{")) {
|
||||
try { const j = JSON.parse(trimmed); msgs = j.messages || []; s.id = j.sessionId || id; touch(s, ms(j.startTime)) } catch {}
|
||||
} else {
|
||||
for (const d of lines(text)) {
|
||||
if (d.sessionId && !s.id) s.id = d.sessionId
|
||||
if (Array.isArray(d.messages)) msgs.push(...d.messages)
|
||||
else if (d.type) msgs.push(d)
|
||||
}
|
||||
}
|
||||
for (const m of msgs) {
|
||||
function geminiEvents(s, opts) {
|
||||
const seenTools = new Set()
|
||||
return (m) => {
|
||||
const t = ms(m.timestamp)
|
||||
if (m.type === "user") {
|
||||
const txt = typeof m.content === "string" ? m.content : textOf(m.content)
|
||||
if (!/functionResponse/.test(JSON.stringify(m.content || ""))) prompted(s, txt, t)
|
||||
continue
|
||||
return
|
||||
}
|
||||
if (m.type === "gemini" || m.type === "model" || m.type === "assistant") {
|
||||
if (m.model) s.model = m.model
|
||||
const txt = typeof m.content === "string" ? m.content : textOf(m.content)
|
||||
if (txt.trim()) s.reply = clip(txt, TEXT_MAX)
|
||||
if (txt.trim()) { s.reply = clip(txt, TEXT_MAX); message(s, "assistant", txt, t) }
|
||||
const calls = Array.isArray(m.toolCalls) ? m.toolCalls : []
|
||||
s.pending = []
|
||||
s.phase = "thinking"
|
||||
for (const c of calls) {
|
||||
const st = String(c.status || "").toLowerCase()
|
||||
if (c.name) s.stepName = String(c.name)
|
||||
if (c.name && !seenTools.has(c.id || c.name)) { seenTools.add(c.id || c.name); message(s, "tool", String(c.name), t, String(c.name)) }
|
||||
if (st === "awaiting_approval") { s.phase = "approval"; s.step = toolLine(c.name, c.args) }
|
||||
else if (st === "scheduled" || st === "executing" || st === "validating") { s.pending.push({ id: c.id, name: c.name, line: toolLine(c.name, c.args), at: t }); s.step = toolLine(c.name, c.args) }
|
||||
else if (c.name) s.step = toolLine(c.name, c.args)
|
||||
@@ -316,30 +431,28 @@ export function readGemini(text, agent = "gemini", id = "") {
|
||||
if (m.type === "error") { s.phase = "error"; s.error = clip(m.content, 160); touch(s, t) }
|
||||
if (m.type === "info" && /cancel/i.test(String(m.content))) { s.phase = "aborted"; touch(s, t) }
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ---- Pi / omp ----------------------------------------------------------------
|
||||
// ~/.pi/agent/sessions/<folder>/<time>_<id>.jsonl: a session header, then
|
||||
// message lines whose message has a role (user, assistant, toolResult) and,
|
||||
// for the assistant, a stopReason (stop, toolUse, aborted, error).
|
||||
export function readPi(text, agent = "pi", id = "") {
|
||||
const s = fresh(agent, id)
|
||||
for (const d of lines(text)) {
|
||||
function piEvents(s, opts) {
|
||||
return (d) => {
|
||||
const t = ms(d.timestamp)
|
||||
if (d.type === "session") { s.id = d.id || s.id; if (d.cwd) { s.cwd = d.cwd; s.project = base(d.cwd) } touch(s, t); continue }
|
||||
if (d.type === "session") { s.id = d.id || s.id; if (d.cwd) { s.cwd = d.cwd; s.project = base(d.cwd) } touch(s, t); return }
|
||||
if (d.type === "session_info" && d.name) s.title = clip(d.name, TITLE_MAX)
|
||||
if (d.type === "title_change" && d.title) s.title = clip(d.title, TITLE_MAX)
|
||||
if (d.type === "model_change") s.model = d.modelId || d.model || s.model
|
||||
const m = d.message
|
||||
if (d.type !== "message" || !m) continue
|
||||
if (m.role === "user") { prompted(s, textOf(m.content), t); continue }
|
||||
if (m.role === "toolResult") { answered(s, m.toolCallId, t); continue }
|
||||
if (d.type !== "message" || !m) return
|
||||
if (m.role === "user") { prompted(s, textOf(m.content), t); return }
|
||||
if (m.role === "toolResult") { answered(s, m.toolCallId, t); return }
|
||||
if (m.role === "assistant") {
|
||||
if (m.model) s.model = m.model
|
||||
const parts = Array.isArray(m.content) ? m.content : []
|
||||
const txt = parts.filter((p) => p?.type === "text").map((p) => p.text).join("\n").trim()
|
||||
if (txt) s.reply = clip(txt, TEXT_MAX)
|
||||
if (txt) { s.reply = clip(txt, TEXT_MAX); message(s, "assistant", txt, t) }
|
||||
for (const p of parts) if (p?.type === "toolCall") called(s, p.id, p.name, p.arguments, t)
|
||||
if (m.stopReason === "stop" || m.stopReason === "length") { s.phase = "done"; s.pending = [] }
|
||||
else if (m.stopReason === "aborted") { s.phase = "aborted"; s.pending = [] }
|
||||
@@ -347,7 +460,395 @@ export function readPi(text, agent = "pi", id = "") {
|
||||
touch(s, t)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
export const READERS = { claude: readClaude, codex: readCodex, dsh: readDsh, gemini: readGemini, pi: readPi }
|
||||
// ---- GitHub Copilot CLI ----------------------------------------------------
|
||||
// ~/.copilot/session-state/<session>/events.jsonl: session.start, user.message,
|
||||
// assistant.message, tool.execution_start / _complete / _error, session.end.
|
||||
// The event shapes follow whatsmyagentdoing's Copilot parser (MIT).
|
||||
function extractCopilotText(value, depth = 0) {
|
||||
if (value == null || depth > 4) return ""
|
||||
if (typeof value === "string") return value
|
||||
if (Array.isArray(value)) return value.map((v) => extractCopilotText(v, depth + 1)).join("\n")
|
||||
if (typeof value === "object") {
|
||||
if (typeof value.text === "string") return value.text
|
||||
if (typeof value.content === "string") return value.content
|
||||
if (Array.isArray(value.content)) return extractCopilotText(value.content, depth + 1)
|
||||
if (typeof value.message === "string") return value.message
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
function copilotEvents(s, opts) {
|
||||
return (d) => {
|
||||
if (!d || typeof d !== "object") return
|
||||
const data = d.data || d
|
||||
const t = ms(d.timestamp) || ms(data.startTime) || ms(data.timestamp)
|
||||
switch (d.type) {
|
||||
case "session.start":
|
||||
if (data.context?.cwd) { s.cwd = data.context.cwd; s.project = base(s.cwd) }
|
||||
else if (data.context?.gitRoot) { s.cwd = data.context.gitRoot; s.project = base(s.cwd) }
|
||||
if (data.selectedModel) s.model = data.selectedModel
|
||||
touch(s, ms(data.startTime) || t)
|
||||
break
|
||||
case "user.message":
|
||||
prompted(s, extractCopilotText(data.content ?? data.transformedContent ?? data.prompt), t)
|
||||
break
|
||||
case "assistant.message": {
|
||||
const txt = extractCopilotText(data.content ?? data.message)
|
||||
if (txt) { s.reply = clip(txt, TEXT_MAX); message(s, "assistant", txt, t) }
|
||||
if (data.model) s.model = data.model
|
||||
if (s.phase !== "tool" && s.phase !== "approval" && s.phase !== "ask") s.phase = "thinking"
|
||||
touch(s, t)
|
||||
break
|
||||
}
|
||||
case "tool.execution_start": {
|
||||
const name = data.toolName || data.tool_name || "tool"
|
||||
const callId = data.toolCallId || data.callId || data.id
|
||||
// The message keeps the name only; arguments may hold secrets.
|
||||
called(s, callId, name, {}, t)
|
||||
break
|
||||
}
|
||||
case "tool.execution_complete":
|
||||
answered(s, data.toolCallId || data.callId || data.id, t)
|
||||
if (data.model) s.model = data.model
|
||||
break
|
||||
case "tool.execution_error":
|
||||
s.phase = "error"; s.error = clip(data.message || "Tool error", 160); touch(s, t)
|
||||
break
|
||||
case "session.end": s.phase = "done"; s.pending = []; touch(s, t); break
|
||||
case "session.error": s.phase = "error"; s.error = clip(data.message || data.error, 160); touch(s, t); break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Kimi Code --------------------------------------------------------------
|
||||
// ~/.kimi-code/sessions/<project>/<session>/agents/<agent>/wire.jsonl, with
|
||||
// <session>/state.json for cwd/title. A child agent is a session of its own:
|
||||
// id "<session>/<agent>", parent "<session>". Event names and shapes follow
|
||||
// whatsmyagentdoing's Kimi reader (MIT).
|
||||
function kimiEvents(s, opts) {
|
||||
const rawId = String(s.id || "")
|
||||
if (rawId.includes("/")) { s.subagent = true; s.parent = rawId.slice(0, rawId.lastIndexOf("/")) }
|
||||
const approvals = new Map() // id -> "approval" | "ask"
|
||||
const sync = () => {
|
||||
if (approvals.size) { s.phase = approvals.values().next().value; return }
|
||||
s.phase = s.pending.length ? "tool" : "thinking"
|
||||
}
|
||||
const ended = (reason, t, err) => {
|
||||
endStream(s)
|
||||
s.pending = []; approvals.clear()
|
||||
const k = String(reason || "").toLowerCase()
|
||||
if (["cancelled", "canceled", "aborted", "interrupted", "max-tokens", "max_tokens"].includes(k)) s.phase = "aborted"
|
||||
else if (["error", "failed", "failure"].includes(k)) { s.phase = "error"; s.error = clip(err || "Turn failed", 160) }
|
||||
else s.phase = "done"
|
||||
touch(s, t)
|
||||
}
|
||||
return (d) => {
|
||||
const t = ms(d.time)
|
||||
const e = d.event || {}
|
||||
switch (d.type) {
|
||||
case "profile.bind":
|
||||
if (d.modelAlias) s.model = d.modelAlias
|
||||
if (d.environmentDisclosure?.cwd) { s.cwd = d.environmentDisclosure.cwd; s.project = base(s.cwd) }
|
||||
break
|
||||
case "turn.prompt":
|
||||
endStream(s)
|
||||
s.pending = []; approvals.clear()
|
||||
if (!prompted(s, textOf(d.input), t)) { s.phase = "thinking"; s.reply = ""; touch(s, t) }
|
||||
break
|
||||
case "agent.turn.started":
|
||||
endStream(s)
|
||||
s.pending = []; approvals.clear(); s.reply = ""; s.phase = "thinking"; s.error = ""
|
||||
touch(s, t)
|
||||
break
|
||||
case "llm.request":
|
||||
if (d.modelAlias || d.model) s.model = d.modelAlias || d.model
|
||||
if (s.phase !== "tool" && s.phase !== "approval" && s.phase !== "ask") s.phase = "thinking"
|
||||
break
|
||||
case "interaction.request":
|
||||
approvals.set(String(d.id || ""), d.kind === "question" ? "ask" : "approval")
|
||||
s.stepName = d.kind === "question" ? "Question" : "Approval"
|
||||
s.step = s.stepName
|
||||
s.phase = approvals.get(String(d.id || ""))
|
||||
touch(s, t)
|
||||
break
|
||||
case "interaction.resolved":
|
||||
approvals.delete(String(d.id || "")); sync(); touch(s, t)
|
||||
break
|
||||
case "turn.cancel": case "prompt.aborted":
|
||||
ended("cancelled", t)
|
||||
break
|
||||
case "turn.ended":
|
||||
ended(d.reason, t, d.error?.message || d.error)
|
||||
break
|
||||
case "agent.turn.ended":
|
||||
ended(d.outcome, t, d.error?.message || d.error)
|
||||
break
|
||||
case "forked":
|
||||
endStream(s)
|
||||
s.pending = []; approvals.clear(); s.reply = ""; s.query = ""; s.phase = "thinking"; touch(s, t)
|
||||
break
|
||||
case "context.append_loop_event":
|
||||
switch (e.type) {
|
||||
case "step.begin": s.reply = ""; endStream(s); sync(); touch(s, t); break
|
||||
case "tool.call": called(s, e.toolCallId, e.name, e.arguments || e.args, t); if (approvals.size) sync(); break
|
||||
case "tool.result": answered(s, e.toolCallId, t); if (approvals.size) sync(); break
|
||||
case "content.part":
|
||||
if (e.part?.type === "text" && e.part.text) {
|
||||
message(s, "assistant", e.part.text, t, undefined, true)
|
||||
s.reply = clip(STREAMS.get(s).text, TEXT_MAX)
|
||||
if (s.phase !== "tool" && s.phase !== "approval" && s.phase !== "ask") s.phase = "thinking"
|
||||
touch(s, t)
|
||||
} else if (e.part?.type === "think") {
|
||||
if (s.phase !== "tool" && s.phase !== "approval" && s.phase !== "ask") s.phase = "thinking"
|
||||
}
|
||||
break
|
||||
// step.end and usage.record end a model call, not the turn
|
||||
}
|
||||
break
|
||||
case "usage.record": {
|
||||
const u = d.usage || d.data?.usage || e.usage
|
||||
if (u && typeof u === "object") {
|
||||
const n = (k) => (Number.isFinite(u[k]) ? u[k] : 0)
|
||||
const add = n("inputTokens") + n("outputTokens") || n("input_tokens") + n("output_tokens")
|
||||
addTokens(s, t, add)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Grok Build -------------------------------------------------------------
|
||||
// ~/.grok/sessions/<project>/<session>/updates.jsonl, with summary.json for
|
||||
// cwd/title/model and an explicit subagent kind. Each line is
|
||||
// { timestamp (seconds), params: { update: { sessionUpdate, ... } } }; ACP
|
||||
// chunk types follow whatsmyagentdoing's Grok reader (MIT).
|
||||
function grokEvents(s, opts) {
|
||||
let previous = ""
|
||||
let userBuf = ""
|
||||
let userTurn = null
|
||||
let userPrompted = false
|
||||
let replyStream = null
|
||||
let replyBuf = ""
|
||||
const completeTool = (callId, title) => {
|
||||
const i = s.pending.findIndex((p) => p.id === String(callId))
|
||||
if (i >= 0) {
|
||||
if (title) { s.pending[i].name = String(title); s.pending[i].line = String(title) }
|
||||
s.pending.splice(i, 1)
|
||||
}
|
||||
if (!s.pending.length && s.phase === "tool") s.phase = "thinking"
|
||||
}
|
||||
return (d) => {
|
||||
const p = d.params || {}
|
||||
const e = p.update || {}
|
||||
const type = e.sessionUpdate
|
||||
const t = ms(d.timestamp)
|
||||
const tm = p._meta || {}
|
||||
const start = Number.isFinite(tm.turnStartMs) ? tm.turnStartMs : t
|
||||
switch (type) {
|
||||
case "user_message_chunk": {
|
||||
if (previous !== type || (Number.isFinite(tm.turnStartMs) && tm.turnStartMs !== userTurn)) {
|
||||
endStream(s)
|
||||
replyStream = null
|
||||
replyBuf = ""
|
||||
userBuf = ""
|
||||
userPrompted = false
|
||||
userTurn = start
|
||||
}
|
||||
userBuf = appendChunk(userBuf, e.content?.text, MESSAGE_TEXT_MAX)
|
||||
if (!userPrompted) userPrompted = prompted(s, userBuf, start)
|
||||
if (userPrompted) {
|
||||
s.query = clip(userBuf, QUERY_MAX)
|
||||
if (s.turns === 1) s.title = clip(userBuf, TITLE_MAX)
|
||||
const last = s.messages[s.messages.length - 1]
|
||||
if (last?.role === "user") last.text = clip(userBuf, MESSAGE_TEXT_MAX)
|
||||
}
|
||||
if (e._meta?.modelId || tm.modelId) s.model = e._meta?.modelId || tm.modelId
|
||||
if (s.phase !== "tool" && s.phase !== "approval" && s.phase !== "ask") s.phase = "thinking"
|
||||
touch(s, start)
|
||||
break
|
||||
}
|
||||
case "agent_thought_chunk":
|
||||
if (s.phase !== "tool" && s.phase !== "approval" && s.phase !== "ask") s.phase = "thinking"
|
||||
touch(s, t)
|
||||
break
|
||||
case "agent_message_chunk": {
|
||||
const streamStart = tm.streamStartMs
|
||||
if ((streamStart != null && streamStart !== replyStream) || (streamStart == null && previous !== type)) {
|
||||
replyStream = streamStart ?? null
|
||||
replyBuf = ""
|
||||
endStream(s)
|
||||
}
|
||||
replyBuf = appendChunk(replyBuf, e.content?.text, TEXT_MAX)
|
||||
if (replyBuf) s.reply = clip(replyBuf, TEXT_MAX)
|
||||
message(s, "assistant", e.content?.text || "", t, undefined, true)
|
||||
if (s.phase !== "tool" && s.phase !== "approval" && s.phase !== "ask") s.phase = "thinking"
|
||||
touch(s, t)
|
||||
break
|
||||
}
|
||||
case "tool_call":
|
||||
case "tool_call_update": {
|
||||
const callId = e.toolCallId || e.id
|
||||
const title = e.title || e._meta?.["x.ai/tool"]?.name || tm?.updateParams?.title
|
||||
const status = String(e.status || tm.updateParams?.status || "").toLowerCase()
|
||||
const done = ["completed", "complete", "failed"].includes(status)
|
||||
if (done) completeTool(callId, title)
|
||||
else if (callId) {
|
||||
const existing = s.pending.find((x) => x.id === String(callId))
|
||||
if (existing) {
|
||||
if (title) { existing.name = String(title); existing.line = String(title); s.stepName = String(title); s.step = String(title) }
|
||||
} else {
|
||||
called(s, callId, title || "Tool", {}, t)
|
||||
}
|
||||
if (s.phase !== "approval" && s.phase !== "ask") s.phase = "tool"
|
||||
}
|
||||
touch(s, t)
|
||||
break
|
||||
}
|
||||
case "turn_completed": {
|
||||
s.pending = []
|
||||
const reason = String(e.stop_reason || "").toLowerCase()
|
||||
if (reason === "rate_limit") { s.phase = "error"; s.error = "Rate limited" }
|
||||
else if (["max_tokens", "refusal", "cancelled", "canceled", "interrupted", "aborted"].includes(reason)) s.phase = "aborted"
|
||||
else if (["error", "failed"].includes(reason)) { s.phase = "error"; s.error = "Turn failed" }
|
||||
else s.phase = "done"
|
||||
touch(s, t)
|
||||
break
|
||||
}
|
||||
case "retry_state":
|
||||
if (s.phase !== "tool" && s.phase !== "approval" && s.phase !== "ask") s.phase = "thinking"
|
||||
break
|
||||
}
|
||||
if (type) previous = type
|
||||
}
|
||||
}
|
||||
|
||||
// A reader owns only its live parsing state, bounded text, and usage/dedupe
|
||||
// indexes. update receives newly appended complete lines, never a replay.
|
||||
const PROCESSORS = { claude: claudeEvents, codex: codexEvents, dsh: dshEvents,
|
||||
gemini: geminiEvents, pi: piEvents, copilot: copilotEvents, kimi: kimiEvents, grok: grokEvents }
|
||||
|
||||
function refreshMetadata(s, kind, meta) {
|
||||
if (!meta || typeof meta !== "object") return
|
||||
if (kind === "kimi") {
|
||||
const cwd = typeof meta.cwd === "string" && meta.cwd ? meta.cwd : meta.workDir
|
||||
if (!s.cwd && typeof cwd === "string" && cwd) { s.cwd = cwd; s.project = base(cwd) }
|
||||
const title = typeof meta.title === "string" && meta.title ? meta.title : meta.customTitle
|
||||
if (typeof title === "string" && title) s.title = clip(title, TITLE_MAX)
|
||||
const model = typeof meta.model === "string" && meta.model ? meta.model : meta.modelAlias
|
||||
if (!s.model && typeof model === "string" && model) s.model = model
|
||||
touch(s, ms(meta.createdAt))
|
||||
} else if (kind === "grok") {
|
||||
const cwd = meta.info?.cwd
|
||||
if (!s.cwd && typeof cwd === "string" && cwd) { s.cwd = cwd; s.project = base(cwd) }
|
||||
const title = meta.generated_title || meta.session_summary || meta.title
|
||||
if (typeof title === "string" && title) s.title = clip(title, TITLE_MAX)
|
||||
if (!s.model && typeof meta.current_model_id === "string" && meta.current_model_id) s.model = meta.current_model_id
|
||||
touch(s, ms(meta.created_at))
|
||||
if (typeof meta.session_kind === "string") {
|
||||
s.subagent = meta.session_kind.startsWith("subagent")
|
||||
s.parent = s.subagent && meta.parent_session_id ? String(meta.parent_session_id) : ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createSessionReader(kind, agent = kind, id = "", opts = {}) {
|
||||
const processor = PROCESSORS[kind]
|
||||
if (!processor) throw new TypeError(`Unknown session reader: ${kind}`)
|
||||
const session = fresh(agent, id)
|
||||
// Sidecars describe the current snapshot, not events. Keep their values out
|
||||
// of parser state so removing them restores facts already read from the log.
|
||||
const exposed = kind === "kimi" || kind === "grok" ? fresh(agent, id) : session
|
||||
const days = new Map()
|
||||
BUCKETS.set(session, days)
|
||||
BUCKETS.set(exposed, days) // cached scans finalize usage on the exposed object
|
||||
let metadata = opts.meta
|
||||
const defaultNow = opts.now
|
||||
const state = { subagent: opts.subagent }
|
||||
const consume = processor(session, state)
|
||||
const publish = (now) => {
|
||||
if (exposed !== session) {
|
||||
Object.assign(exposed, session)
|
||||
refreshMetadata(exposed, kind, metadata)
|
||||
}
|
||||
finalizeUsage(exposed, now)
|
||||
return exposed
|
||||
}
|
||||
let usageDays = new Map()
|
||||
// Grok's usage sidecar is a replacement snapshot. Keep only totals per
|
||||
// calendar day so corrections and removal never double count prior usage.
|
||||
// Its session total and modelUsage repeat turn deltas, not extra charges.
|
||||
const refreshUsage = (usage) => {
|
||||
const next = new Map()
|
||||
for (const turn of Array.isArray(usage?.turns) ? usage.turns : []) {
|
||||
if (!turn || typeof turn !== "object") continue
|
||||
const t = ms(turn.endedAt)
|
||||
if (!t) continue
|
||||
const n = (k) => Number.isFinite(turn[k]) && turn[k] > 0 ? turn[k] : 0
|
||||
const key = dayKey(t)
|
||||
const day = next.get(key) || { t, tokens: 0 }
|
||||
day.tokens += Math.max(0, n("inputTokens") - n("cachedReadTokens")) + n("outputTokens")
|
||||
next.set(key, day)
|
||||
}
|
||||
for (const day of usageDays.values()) adjustTokens(session, day.t, -day.tokens)
|
||||
for (const day of next.values()) addTokens(session, day.t, day.tokens)
|
||||
usageDays = next
|
||||
}
|
||||
if (kind === "grok" && opts.usage !== undefined) refreshUsage(opts.usage)
|
||||
function update(input, changes = {}) {
|
||||
const { usage, now } = changes
|
||||
if (Object.hasOwn(changes, "meta")) metadata = changes.meta
|
||||
for (const d of lines(input)) {
|
||||
if (kind === "gemini") {
|
||||
if (d.sessionId && !session.id) session.id = d.sessionId
|
||||
if (d.startTime) touch(session, ms(d.startTime))
|
||||
if (Array.isArray(d.messages)) { for (const m of d.messages) consume(m) }
|
||||
else if (d.type) consume(d)
|
||||
} else consume(d)
|
||||
}
|
||||
if (kind === "grok" && usage !== undefined) refreshUsage(usage)
|
||||
return publish(now ?? defaultNow ?? Date.now())
|
||||
}
|
||||
publish(opts.now ?? Date.now())
|
||||
return { session: exposed, update }
|
||||
}
|
||||
|
||||
export function readClaude(text, agent = "claude", id = "", opts = {}) {
|
||||
return createSessionReader("claude", agent, id, opts).update(text)
|
||||
}
|
||||
export function readCodex(text, id = "", opts = {}) {
|
||||
return createSessionReader("codex", "codex", id, opts).update(text)
|
||||
}
|
||||
export function readDsh(text, id = "", opts = {}) {
|
||||
return createSessionReader("dsh", "dsh", id, opts).update(text)
|
||||
}
|
||||
export function readGemini(text, agent = "gemini", id = "", opts = {}) {
|
||||
// Gemini also writes a whole JSON document rather than JSONL.
|
||||
if (typeof text === "string") {
|
||||
try {
|
||||
const document = JSON.parse(text)
|
||||
if (document && Array.isArray(document.messages)) {
|
||||
id = document.sessionId || id
|
||||
text = [JSON.stringify(document)]
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
return createSessionReader("gemini", agent, id, opts).update(text)
|
||||
}
|
||||
export function readPi(text, agent = "pi", id = "", opts = {}) {
|
||||
return createSessionReader("pi", agent, id, opts).update(text)
|
||||
}
|
||||
export function readCopilot(text, id = "", opts = {}) {
|
||||
return createSessionReader("copilot", "copilot", id, opts).update(text)
|
||||
}
|
||||
export function readKimi(text, id = "", meta = {}, opts = {}) {
|
||||
return createSessionReader("kimi", "kimi", id, { ...opts, meta }).update(text)
|
||||
}
|
||||
export function readGrok(text, id = "", meta = {}, opts = {}) {
|
||||
return createSessionReader("grok", "grok", id, { ...opts, meta }).update(text)
|
||||
}
|
||||
|
||||
export const READERS = { claude: readClaude, codex: readCodex, dsh: readDsh, gemini: readGemini, pi: readPi,
|
||||
copilot: readCopilot, kimi: readKimi, grok: readGrok }
|
||||
|
||||
@@ -1,33 +1,26 @@
|
||||
// Finds the session files each agent writes, in each agent's own folder,
|
||||
// and reads the ones that changed: whole when new, then only what was
|
||||
// appended. readers.mjs turns the text into a session's facts.
|
||||
//
|
||||
// Cheap on purpose: it runs every second or two while magpie is open. A
|
||||
// folder is listed only for files changed in the last `days`; a file is
|
||||
// read again only when its size or time moved; a big file is read from its
|
||||
// tail (a turn's state is in its last lines, and the start of the file —
|
||||
// the session header, its first prompt — is read once and kept).
|
||||
import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from "node:fs"
|
||||
// Finds each agent's session files. JSONL readers keep their parsing state
|
||||
// and byte cursor: a normal tick reads only appended bytes. A replacement,
|
||||
// truncation or same-size rewrite starts a fresh replay. Calendar-day usage
|
||||
// is refreshed even when the log has not changed.
|
||||
import { closeSync, existsSync, openSync, fstatSync, readFileSync, readSync, readdirSync, statSync } from "node:fs"
|
||||
import { homedir } from "node:os"
|
||||
import { basename, dirname, join } from "node:path"
|
||||
import { readClaude, readCodex, readDsh, readGemini, readPi } from "./readers.mjs"
|
||||
import { StringDecoder } from "node:string_decoder"
|
||||
import { createSessionReader, finalizeUsage, readClaude, readCodex, readCopilot, readDsh, readGemini, readGrok, readKimi, readPi } from "./readers.mjs"
|
||||
|
||||
const HEAD = 64 * 1024 // what is kept of a file's start: its header, its first prompt
|
||||
const TAIL = 512 * 1024 // what is read of a big file's end
|
||||
const READ_CHUNK = 64 * 1024
|
||||
const GUARD_BYTES = 64 // bounded prefix/end witnesses catch truncate-and-regrow between ticks
|
||||
// A dsh session is one compressed file that is rewritten on every step, so
|
||||
// decoding all of it each 1.5 s tick is wasteful while it is being written.
|
||||
// The cap keeps a pathological file from stalling a tick, and an active one
|
||||
// is decoded at most once every ZSTD_EVERY: its last facts stand meanwhile.
|
||||
const ZSTD_MAX = 8 * 1024 * 1024
|
||||
const ZSTD_EVERY = 4000
|
||||
// Claude Code keeps one file per running process, <config>/sessions/<pid>.json
|
||||
// ({pid, sessionId, …}). It takes the file away when it ends on SIGINT or
|
||||
// SIGTERM and leaves it when SIGKILLed, so a session with no living process
|
||||
// in that folder has stopped, whatever its last line says. That is the case
|
||||
// of an agent another agent ran and interrupted (`claude -p` killed from the
|
||||
// shell): its file ends mid-turn, and without this it read as at work and
|
||||
// then stuck for good. A turn quiet less than GONE_AFTER is not judged: the
|
||||
// process may be starting.
|
||||
const META_MAX = 256 * 1024 // state.json / summary.json remain small
|
||||
const USAGE_MAX = 32 * 1024 * 1024 // usage.json grows with every recorded turn
|
||||
// Claude Code keeps one file per running process, <config>/sessions/<pid>.json.
|
||||
// A mid-turn session with no live process has stopped, even when the file
|
||||
// ends before a turn-ending event: `claude -p` killed from another agent.
|
||||
const GONE_AFTER = 10e3
|
||||
const MIDTURN = new Set(["thinking", "tool", "approval", "ask"])
|
||||
|
||||
@@ -35,31 +28,61 @@ function env(k) { return (process.env[k] || "").trim() }
|
||||
function home(...p) { return join(env("HOME") || homedir(), ...p) }
|
||||
function expand(p) { return p.startsWith("~/") ? home(p.slice(2)) : p }
|
||||
|
||||
// Use the agent's own home variable, without inventing CONFIG_DIR aliases.
|
||||
function agentHome(homeVar, ...fallback) {
|
||||
if (env(homeVar)) return expand(env(homeVar))
|
||||
return home(...fallback)
|
||||
}
|
||||
|
||||
// omp keeps a profile per working identity: <home>/profiles/<name>/agent/sessions
|
||||
function ompProfiles(omp) {
|
||||
const out = []
|
||||
let names = []
|
||||
try { names = readdirSync(join(omp, "profiles"), { withFileTypes: true }) } catch { return out }
|
||||
for (const e of names) {
|
||||
if (!e.isDirectory()) continue
|
||||
out.push({ agent: "omp", kind: "pi", root: join(omp, "profiles", e.name, "agent", "sessions"), depth: 1, match: (n) => n.endsWith(".jsonl"), profile: e.name })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// where each agent keeps its sessions: { agent, kind, root, depth, match }
|
||||
// depth: how many folders down from root the files sit
|
||||
export function sources() {
|
||||
const claude = env("CLAUDE_CONFIG_DIR") ? expand(env("CLAUDE_CONFIG_DIR")) : home(".claude")
|
||||
const codex = env("CODEX_HOME") ? expand(env("CODEX_HOME")) : home(".codex")
|
||||
const dsh = env("DSH_HOME") ? expand(env("DSH_HOME")) : home(".dsh")
|
||||
// Vendor-documented: https://code.claude.com/docs/en/settings#find-or-create-your-settings-files
|
||||
const claude = agentHome("CLAUDE_CONFIG_DIR", ".claude")
|
||||
const codex = agentHome("CODEX_HOME", ".codex")
|
||||
const dsh = agentHome("DSH_HOME", ".dsh")
|
||||
const pi = env("PI_CODING_AGENT_DIR") ? expand(env("PI_CODING_AGENT_DIR")) : home(".pi", "agent")
|
||||
const qoder = env("QODER_CONFIG_DIR") ? expand(env("QODER_CONFIG_DIR")) : home(".qoder")
|
||||
const qodercn = env("QODERCN_CONFIG_DIR") ? expand(env("QODERCN_CONFIG_DIR")) : home(".qoder-cn")
|
||||
const workbuddy = env("WORKBUDDY_CONFIG_DIR") ? expand(env("WORKBUDDY_CONFIG_DIR")) : home(".workbuddy")
|
||||
const codebuddy = env("CODEBUDDY_CONFIG_DIR") ? expand(env("CODEBUDDY_CONFIG_DIR")) : home(".codebuddy")
|
||||
const omp = agentHome("OMP_HOME", ".omp")
|
||||
const kimi = agentHome("KIMI_CODE_HOME", ".kimi-code")
|
||||
const grok = agentHome("GROK_HOME", ".grok")
|
||||
const copilot = agentHome("COPILOT_HOME", ".copilot")
|
||||
const qoder = home(".qoder")
|
||||
const qodercn = home(".qoder-cn")
|
||||
const workbuddy = home(".workbuddy")
|
||||
const codebuddy = home(".codebuddy")
|
||||
const jsonl = (n) => n.endsWith(".jsonl")
|
||||
return [
|
||||
const srcs = [
|
||||
{ agent: "claude", kind: "claude", root: join(claude, "projects"), depth: 1, match: jsonl, live: join(claude, "sessions") },
|
||||
// a subagent's file sits project/<session>/subagents/<agent>.jsonl
|
||||
{ agent: "claude", kind: "claude", root: join(claude, "projects"), depth: 3, match: (n, p) => n.endsWith(".jsonl") && basename(dirname(p)) === "subagents", subagent: true },
|
||||
{ agent: "codex", kind: "codex", root: join(codex, "sessions"), depth: 3, match: (n) => n.startsWith("rollout-") && n.endsWith(".jsonl") },
|
||||
{ agent: "dsh", kind: "dsh", root: join(dsh, "sessions"), depth: 2, match: (n) => n === "session.v4.jsonl.zstd" || n === "session.v4.jsonl" },
|
||||
{ agent: "gemini", kind: "gemini", root: home(".gemini", "tmp"), depth: 2, match: (n) => n.startsWith("session-") && (n.endsWith(".json") || n.endsWith(".jsonl")) },
|
||||
{ agent: "qwen", kind: "gemini", root: home(".qwen", "tmp"), depth: 2, match: (n) => n.startsWith("session-") && (n.endsWith(".json") || n.endsWith(".jsonl")) },
|
||||
{ agent: "pi", kind: "pi", root: join(pi, "sessions"), depth: 1, match: jsonl },
|
||||
{ agent: "omp", kind: "pi", root: home(".omp", "agent", "sessions"), depth: 1, match: jsonl },
|
||||
{ agent: "omp", kind: "pi", root: join(omp, "agent", "sessions"), depth: 1, match: jsonl },
|
||||
...ompProfiles(omp),
|
||||
{ agent: "kimi", kind: "kimi", root: join(kimi, "sessions"), depth: 4, match: (n) => n === "wire.jsonl", meta: (p) => join(dirname(dirname(dirname(p))), "state.json") },
|
||||
{ agent: "grok", kind: "grok", root: join(grok, "sessions"), depth: 2, match: (n) => n === "updates.jsonl", meta: (p) => join(dirname(p), "summary.json"), usage: (p) => join(dirname(p), "usage.json") },
|
||||
{ agent: "copilot", kind: "copilot", root: join(copilot, "session-state"), depth: 1, match: (n) => n === "events.jsonl" },
|
||||
{ agent: "qoder", kind: "claude", root: join(qoder, "projects"), depth: 1, match: jsonl, live: join(qoder, "sessions") },
|
||||
{ agent: "qoder-cn", kind: "claude", root: join(qodercn, "projects"), depth: 1, match: jsonl, live: join(qodercn, "sessions") },
|
||||
{ agent: "workbuddy", kind: "claude", root: join(workbuddy, "projects"), depth: 1, match: jsonl, live: join(workbuddy, "sessions") },
|
||||
{ agent: "codebuddy", kind: "claude", root: join(codebuddy, "projects"), depth: 1, match: jsonl, live: join(codebuddy, "sessions") },
|
||||
]
|
||||
return srcs
|
||||
}
|
||||
|
||||
// the files under root, `depth` folders down, changed since `since`
|
||||
@@ -72,20 +95,110 @@ function walk(root, depth, match, since, out) {
|
||||
if (!e.isDirectory()) continue
|
||||
// Codex's YYYY/MM/DD: a whole old month or day is skipped by its name
|
||||
walk(p, depth - 1, match, since, out)
|
||||
} else if (e.isFile() && match(e.name)) {
|
||||
} else if (e.isFile() && match(e.name, p)) {
|
||||
let st
|
||||
try { st = statSync(p) } catch { continue }
|
||||
if (st.mtimeMs >= since) out.push({ path: p, size: st.size, mtime: st.mtimeMs })
|
||||
if (st.mtimeMs >= since) out.push({ path: p, size: st.size, mtime: st.mtimeMs, ctime: st.ctimeMs, dev: st.dev, ino: st.ino, birthtime: st.birthtimeMs })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function readRange(path, from, len) {
|
||||
const fd = openSync(path, "r")
|
||||
// A cursor buffers only the current unfinished line. StringDecoder carries
|
||||
// an incomplete UTF-8 code point between chunks AND between scan ticks.
|
||||
function framing() { return { started: false, quoted: false, escape: false, depth: 0, complete: false, invalid: false } }
|
||||
function framePart(state, text) {
|
||||
for (const char of text) {
|
||||
if (state.invalid) return
|
||||
if (!state.started) {
|
||||
if (/\s/.test(char)) continue
|
||||
state.started = true
|
||||
if (char !== "{") { state.invalid = true; return }
|
||||
state.depth = 1
|
||||
} else if (state.complete) {
|
||||
if (!/\s/.test(char)) state.invalid = true
|
||||
} else if (state.quoted) {
|
||||
if (state.escape) state.escape = false
|
||||
else if (char === "\\") state.escape = true
|
||||
else if (char === '"') state.quoted = false
|
||||
} else if (char === '"') state.quoted = true
|
||||
else if (char === "{" || char === "[") state.depth++
|
||||
else if (char === "}" || char === "]") { state.depth--; if (state.depth === 0) state.complete = true }
|
||||
}
|
||||
}
|
||||
function cursor() {
|
||||
return { offset: 0, decoder: new StringDecoder("utf8"), parts: [], frame: framing(), committedTail: false, prefix: Buffer.alloc(0), tail: Buffer.alloc(0) }
|
||||
}
|
||||
// Size growth alone cannot distinguish append from truncate-and-regrow
|
||||
// between ticks. Verify at most 128 old bytes without parsing any history.
|
||||
function appendWitnessMatches(f, c, read) {
|
||||
const fd = openSync(f.path, "r")
|
||||
try {
|
||||
const b = Buffer.alloc(len)
|
||||
const n = readSync(fd, b, 0, len, from)
|
||||
return b.subarray(0, n).toString("utf8")
|
||||
const st = fstatSync(fd)
|
||||
if (st.dev !== f.dev || st.ino !== f.ino || st.size < c.offset) return false
|
||||
const prefix = Buffer.alloc(c.prefix.length)
|
||||
if (prefix.length && (read(fd, prefix, 0, prefix.length, 0) !== prefix.length || !prefix.equals(c.prefix))) return false
|
||||
if (c.offset > prefix.length && c.tail.length) {
|
||||
const tail = Buffer.alloc(c.tail.length)
|
||||
if (read(fd, tail, 0, tail.length, c.offset - tail.length) !== tail.length || !tail.equals(c.tail)) return false
|
||||
}
|
||||
return true
|
||||
} finally { closeSync(fd) }
|
||||
}
|
||||
class ExtendedTail extends Error {}
|
||||
|
||||
function* readAppended(f, c, read) {
|
||||
const fd = openSync(f.path, "r")
|
||||
const buf = Buffer.alloc(READ_CHUNK)
|
||||
try {
|
||||
const st = fstatSync(fd)
|
||||
// The path can rotate between walk() and open(). Retry next tick rather
|
||||
// than adding another file's bytes to the existing reader.
|
||||
if (st.dev !== f.dev || st.ino !== f.ino || st.size < c.offset) throw new Error("session file changed while opening")
|
||||
while (c.offset < f.size) {
|
||||
const n = read(fd, buf, 0, Math.min(buf.length, f.size - c.offset), c.offset)
|
||||
if (!n) break
|
||||
c.offset += n
|
||||
const block = buf.subarray(0, n)
|
||||
if (c.prefix.length < GUARD_BYTES) c.prefix = Buffer.concat([c.prefix, block.subarray(0, GUARD_BYTES - c.prefix.length)])
|
||||
c.tail = Buffer.from(n >= GUARD_BYTES ? block.subarray(n - GUARD_BYTES) : Buffer.concat([c.tail, block]).subarray(-GUARD_BYTES))
|
||||
const text = c.decoder.write(block)
|
||||
let start = 0
|
||||
while (start < text.length) {
|
||||
const end = text.indexOf("\n", start)
|
||||
const part = text.slice(start, end < 0 ? text.length : end)
|
||||
if (c.committedTail) {
|
||||
// A valid record at EOF was already applied. Its later newline
|
||||
// must not count it twice. Non-whitespace extending that record
|
||||
// instead invalidates the speculative EOF parse and needs replay.
|
||||
if (/\S/.test(part)) throw new ExtendedTail()
|
||||
if (end >= 0) c.committedTail = false
|
||||
} else if (end >= 0) {
|
||||
c.parts.push(part)
|
||||
const line = c.parts.join("")
|
||||
c.parts = []
|
||||
c.frame = framing()
|
||||
yield line
|
||||
} else if (part) {
|
||||
c.parts.push(part)
|
||||
framePart(c.frame, part)
|
||||
}
|
||||
if (end < 0) break
|
||||
start = end + 1
|
||||
}
|
||||
}
|
||||
// Some clients flush a complete JSON record before its newline. Accept
|
||||
// it once, but never repeatedly parse a growing base64/text fragment.
|
||||
if (!c.committedTail && c.frame.complete && !c.frame.invalid && !c.frame.quoted) {
|
||||
const tail = c.parts.join("")
|
||||
let complete = false
|
||||
try { const record = JSON.parse(tail); complete = !!record && typeof record === "object" && !Array.isArray(record) } catch { c.frame.invalid = true }
|
||||
if (complete) {
|
||||
c.parts = []
|
||||
c.frame = framing()
|
||||
c.committedTail = true
|
||||
yield tail
|
||||
}
|
||||
}
|
||||
} finally { closeSync(fd) }
|
||||
}
|
||||
|
||||
@@ -102,12 +215,11 @@ function pidAlive(pid) {
|
||||
}
|
||||
|
||||
// The sessions folder of a Claude-format agent: which session ids have a
|
||||
// running process. null when it can't say: the folder has never been seen
|
||||
// to hold such a file (an agent, or a version, that doesn't keep them), or
|
||||
// can't be read. Once a folder has held one, an empty folder means no
|
||||
// process runs.
|
||||
// running process. null when it can't say: the folder has never held such a
|
||||
// file (an agent/version that keeps none), or can't be read. Once it has
|
||||
// held one, an empty folder means no process runs.
|
||||
export function createProcesses() {
|
||||
const dirs = new Map() // dir -> { kept: bool, files: Map(name -> { mtime, pid, id, here }) }
|
||||
const dirs = new Map()
|
||||
function running(dir) {
|
||||
let d = dirs.get(dir)
|
||||
if (!d) { d = { kept: false, files: new Map() }; dirs.set(dir, d) }
|
||||
@@ -125,8 +237,6 @@ export function createProcesses() {
|
||||
let j
|
||||
try { j = JSON.parse(readFileSync(p, "utf8")) } catch { j = null }
|
||||
if (!j) { d.files.delete(n); return null } // half-written: unknown this time
|
||||
// a pid of another system's (Claude Code in WSL writing here) can't
|
||||
// be asked about from this one
|
||||
const here = !j.pidDomain || j.pidDomain === process.platform
|
||||
f = { mtime: st.mtimeMs, pid: Number(j.pid), id: String(j.sessionId || ""), here }
|
||||
d.files.set(n, f)
|
||||
@@ -142,13 +252,16 @@ export function createProcesses() {
|
||||
return { running }
|
||||
}
|
||||
|
||||
function readerFor(kind, agent) {
|
||||
function readerFor(kind, agent, src = {}) {
|
||||
switch (kind) {
|
||||
case "claude": return (t, id) => readClaude(t, agent, id)
|
||||
case "codex": return (t, id) => readCodex(t, id)
|
||||
case "dsh": return (t, id) => readDsh(t, id)
|
||||
case "gemini": return (t, id) => readGemini(t, agent, id)
|
||||
case "pi": return (t, id) => readPi(t, agent, id)
|
||||
case "claude": return (t, id, meta, now) => readClaude(t, agent, id, { subagent: !!src.subagent, now })
|
||||
case "codex": return (t, id, meta, now) => readCodex(t, id, { now })
|
||||
case "dsh": return (t, id, meta, now) => readDsh(t, id, { now })
|
||||
case "gemini": return (t, id, meta, now) => readGemini(t, agent, id, { now })
|
||||
case "pi": return (t, id, meta, now) => readPi(t, agent, id, { now })
|
||||
case "copilot": return (t, id, meta, now) => readCopilot(t, id, { now })
|
||||
case "kimi": return (t, id, meta, now) => readKimi(t, id, meta, { now })
|
||||
case "grok": return (t, id, meta, now, usage) => readGrok(t, id, meta, { now, usage })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,30 +269,80 @@ function idOf(src, path) {
|
||||
const name = basename(path)
|
||||
if (src.kind === "dsh") return basename(dirname(path))
|
||||
if (src.kind === "codex") { const m = /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_[^.]*)?\.jsonl$/i.exec(name); return m ? m[1] : name }
|
||||
// the session folder names the session: ~/.grok/sessions/<project>/<session>
|
||||
if (src.kind === "grok" || src.kind === "copilot") return basename(dirname(path))
|
||||
if (src.kind === "kimi") {
|
||||
const child = basename(dirname(path)) // …/<session>/agents/<agent>/wire.jsonl
|
||||
const session = basename(dirname(dirname(dirname(path))))
|
||||
return child === "main" ? session : `${session}/${child}`
|
||||
}
|
||||
return name.replace(/\.jsonl?$/, "").replace(/^\d{4}-\d{2}-\d{2}T[^_]+_/, "")
|
||||
}
|
||||
|
||||
// the parent a source's file layout implies, for a child session without one
|
||||
function parentOf(src, path, id) {
|
||||
if (src.kind === "claude" && src.subagent) return basename(dirname(dirname(path))) // project/<session>/subagents/<agent>.jsonl
|
||||
const i = String(id || "").lastIndexOf("/")
|
||||
return i > 0 ? String(id).slice(0, i) : ""
|
||||
}
|
||||
|
||||
// state.json / summary.json, bounded: a broken or huge one is simply ignored
|
||||
function readMeta(src, path, field = "meta") {
|
||||
if (typeof src[field] !== "function") return null
|
||||
try {
|
||||
const file = src[field](path)
|
||||
const st = statSync(file)
|
||||
if (!st.isFile() || st.size > (field === "usage" ? USAGE_MAX : META_MAX)) return null
|
||||
return JSON.parse(readFileSync(file, "utf8"))
|
||||
} catch { return null }
|
||||
}
|
||||
|
||||
function sidecars(src, path) {
|
||||
return ["meta", "usage"].map((field) => {
|
||||
if (typeof src[field] !== "function") return ""
|
||||
try {
|
||||
const st = statSync(src[field](path))
|
||||
return `${st.size}:${st.mtimeMs}:${st.ctimeMs}`
|
||||
} catch { return "missing" }
|
||||
}).join("|")
|
||||
}
|
||||
|
||||
// Codex names a thread in session_index.jsonl ({id, thread_name}), the
|
||||
// latest line for an id winning
|
||||
function codexTitles() {
|
||||
function codexTitles(was, readBytes) {
|
||||
const dir = env("CODEX_HOME") ? expand(env("CODEX_HOME")) : home(".codex")
|
||||
const out = new Map()
|
||||
const path = join(dir, "session_index.jsonl")
|
||||
let f
|
||||
try {
|
||||
for (const l of readFileSync(join(dir, "session_index.jsonl"), "utf8").split("\n")) {
|
||||
if (!l) continue
|
||||
try { const d = JSON.parse(l); if (d.id && d.thread_name) out.set(d.id, String(d.thread_name).trim()) } catch {}
|
||||
const st = statSync(path)
|
||||
f = { path, size: st.size, mtime: st.mtimeMs, ctime: st.ctimeMs, dev: st.dev, ino: st.ino, birthtime: st.birthtimeMs }
|
||||
} catch { return { titles: new Map() } }
|
||||
const same = was?.path === path && was.dev === f.dev && was.ino === f.ino && was.birthtime === f.birthtime
|
||||
if (same && was.size === f.size && was.mtime === f.mtime && was.ctime === f.ctime) return was
|
||||
const reusable = same && was.cursor && f.size > was.size && f.size >= was.cursor.offset && appendWitnessMatches(f, was.cursor, readBytes)
|
||||
let c = reusable ? was : { cursor: cursor(), titles: new Map() }
|
||||
const consume = () => {
|
||||
for (const line of readAppended(f, c.cursor, readBytes)) {
|
||||
try { const d = JSON.parse(line); if (d.id && d.thread_name) c.titles.set(d.id, String(d.thread_name).trim()) } catch {}
|
||||
}
|
||||
} catch {}
|
||||
return out
|
||||
}
|
||||
try { consume() }
|
||||
catch (error) {
|
||||
if (error instanceof ExtendedTail && reusable) { c = { cursor: cursor(), titles: new Map() }; consume() }
|
||||
else return was || { titles: new Map() }
|
||||
}
|
||||
return Object.assign(c, f)
|
||||
}
|
||||
|
||||
export function createScanner(opts = {}) {
|
||||
const o = { days: 2, max: 40, zstdMax: ZSTD_MAX, zstdEvery: ZSTD_EVERY, ...opts }
|
||||
const files = new Map() // path -> { size, mtime, head, session }
|
||||
const files = new Map() // path -> file identity, JSONL cursor/reader, published session
|
||||
const readBytes = typeof o.readSync === "function" ? o.readSync : readSync
|
||||
const procs = createProcesses()
|
||||
let srcs = o.sources || sources()
|
||||
const procs = o.processes || createProcesses()
|
||||
let titleCache = null
|
||||
|
||||
// one pass: every changed file read again; gives the sessions, latest first
|
||||
// One pass: append-only JSONL changes reuse reader state; latest sessions first.
|
||||
function scan(now = Date.now()) {
|
||||
const since = now - o.days * 86400e3
|
||||
const found = []
|
||||
@@ -194,31 +357,42 @@ export function createScanner(opts = {}) {
|
||||
const live = new Set(keep.map((f) => f.path))
|
||||
for (const p of files.keys()) if (!live.has(p)) files.delete(p)
|
||||
const out = []
|
||||
const running = new Map() // a live-process folder, once per tick
|
||||
let titles = null
|
||||
const running = new Map() // a sessions folder, read once a pass
|
||||
for (const f of keep) {
|
||||
let c = files.get(f.path)
|
||||
const changed = !c || c.size !== f.size || c.mtime !== f.mtime
|
||||
const metadata = sidecars(f.src, f.path)
|
||||
const changed = !c || c.size !== f.size || c.mtime !== f.mtime || c.ctime !== f.ctime || c.dev !== f.dev || c.ino !== f.ino || c.birthtime !== f.birthtime || c.metadata !== metadata || (c.cursor && c.cursor.offset < f.size)
|
||||
if (changed) {
|
||||
const zstd = f.path.endsWith(".zstd")
|
||||
// decode an active compressed session at most once every
|
||||
// zstdEvery ms; its file time still says it is at work
|
||||
// Leave size/mtime at the last decoded revision while throttled, so
|
||||
// a final write is still decoded after the throttle interval elapses.
|
||||
if (zstd && c?.session && now - (c.decodedAt || 0) < o.zstdEvery) {
|
||||
c.size = f.size
|
||||
c.mtime = f.mtime
|
||||
c.session.touched = Math.max(c.session.touched || 0, f.mtime)
|
||||
} else {
|
||||
try { c = readOne(f, c, now) } catch (e) { continue }
|
||||
files.set(f.path, c)
|
||||
try {
|
||||
c = readOne({ ...f, metadata }, c, now)
|
||||
c.metadata = metadata
|
||||
files.set(f.path, c)
|
||||
} catch (e) {
|
||||
// Keep valid facts/cursor progress through a transient read
|
||||
// failure. Do not mark the new metadata revision consumed.
|
||||
if (!c?.session) continue
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!c.session) continue
|
||||
if (c.session.agent === "codex") {
|
||||
titles ??= codexTitles()
|
||||
const t = titles.get(c.session.id)
|
||||
if (t) c.session.title = t.length > 48 ? t.slice(0, 47) + "…" : t
|
||||
// Keep scanner-derived path/title/time fields out of the parser's
|
||||
// stable state, so they cannot override subsequent log events.
|
||||
const parsed = c.reader ? c.reader.session : c.session
|
||||
finalizeUsage(parsed, now)
|
||||
const s = c.reader ? finish({ ...parsed, path: f.path }, f) : c.session
|
||||
c.session = s
|
||||
if (s.agent === "codex") {
|
||||
if (!titles) { titleCache = codexTitles(titleCache, readBytes); titles = titleCache.titles }
|
||||
const t = titles.get(s.id)
|
||||
if (t) s.title = t.length > 48 ? t.slice(0, 47) + "…" : t
|
||||
}
|
||||
const s = c.session
|
||||
if (f.src.live && MIDTURN.has(s.phase) && now - f.mtime >= GONE_AFTER) {
|
||||
if (!running.has(f.src.live)) running.set(f.src.live, procs.running(f.src.live))
|
||||
const ids = running.get(f.src.live)
|
||||
@@ -230,34 +404,50 @@ export function createScanner(opts = {}) {
|
||||
}
|
||||
|
||||
function readOne(f, was, now = Date.now()) {
|
||||
const read = readerFor(f.src.kind, f.src.agent)
|
||||
const id = idOf(f.src, f.path)
|
||||
let text
|
||||
if (f.path.endsWith(".zstd")) {
|
||||
if (f.size > o.zstdMax) return { size: f.size, mtime: f.mtime, session: was?.session || null, decodedAt: now }
|
||||
text = zstd(f.path)
|
||||
const s = read(text, id)
|
||||
const sig = f.metadata.split("|")
|
||||
const before = was?.metadata?.split("|")
|
||||
const compressed = f.path.endsWith(".zstd")
|
||||
const document = f.src.kind === "gemini" && f.path.endsWith(".json")
|
||||
if (compressed || document) {
|
||||
// A rewritten compressed blob / JSON document has no append cursor.
|
||||
if (compressed && f.size > o.zstdMax) return { ...f, session: was?.session || null, decodedAt: now }
|
||||
const text = compressed ? zstd(f.path) : readFileSync(f.path, "utf8")
|
||||
const s = readerFor(f.src.kind, f.src.agent, f.src)(text, id, readMeta(f.src, f.path), now, readMeta(f.src, f.path, "usage"))
|
||||
s.path = f.path
|
||||
return { size: f.size, mtime: f.mtime, session: finish(s, f), decodedAt: now }
|
||||
} else if (f.size <= HEAD + TAIL) {
|
||||
text = readRange(f.path, 0, f.size)
|
||||
} else {
|
||||
// the start once (header, first prompt), and the end every time
|
||||
const head = was?.head ?? readRange(f.path, 0, HEAD)
|
||||
let tail = readRange(f.path, f.size - TAIL, TAIL)
|
||||
tail = tail.slice(tail.indexOf("\n") + 1)
|
||||
text = head.slice(0, head.lastIndexOf("\n") + 1) + tail
|
||||
const s = read(text, id)
|
||||
s.path = f.path
|
||||
return { size: f.size, mtime: f.mtime, head, session: finish(s, f) }
|
||||
return { size: f.size, mtime: f.mtime, ctime: f.ctime, dev: f.dev, ino: f.ino, birthtime: f.birthtime, session: finish(s, f), decodedAt: now }
|
||||
}
|
||||
const s = read(text, id)
|
||||
s.path = f.path
|
||||
return { size: f.size, mtime: f.mtime, session: finish(s, f) }
|
||||
const sameFile = was && was.dev === f.dev && was.ino === f.ino && was.birthtime === f.birthtime
|
||||
const rewritten = sameFile && f.size === was.size && (f.mtime !== was.mtime || f.ctime !== was.ctime)
|
||||
const reusable = sameFile && was.reader && was.cursor && f.size >= was.cursor.offset && !rewritten && (f.size === was.cursor.offset || appendWitnessMatches(f, was.cursor, readBytes))
|
||||
let c = reusable ? was : {
|
||||
reader: createSessionReader(f.src.kind, f.src.agent, id, { subagent: !!f.src.subagent }),
|
||||
cursor: cursor(),
|
||||
}
|
||||
const changes = { now }
|
||||
// Do not retain a whole usage.json snapshot or re-aggregate it on each
|
||||
// append. The reader keeps its daily totals; re-read only a new revision.
|
||||
if (!reusable || before?.[0] !== sig[0]) changes.meta = readMeta(f.src, f.path)
|
||||
if (!reusable || before?.[1] !== sig[1]) changes.usage = readMeta(f.src, f.path, "usage")
|
||||
try { c.reader.update(readAppended(f, c.cursor, readBytes), changes) }
|
||||
catch (error) {
|
||||
if (!(error instanceof ExtendedTail) || !reusable) throw error
|
||||
c = { reader: createSessionReader(f.src.kind, f.src.agent, id, { subagent: !!f.src.subagent }), cursor: cursor() }
|
||||
c.reader.update(readAppended(f, c.cursor, readBytes), { meta: readMeta(f.src, f.path), usage: readMeta(f.src, f.path, "usage"), now })
|
||||
}
|
||||
Object.assign(c, { size: f.size, mtime: f.mtime, ctime: f.ctime, dev: f.dev, ino: f.ino, birthtime: f.birthtime, decodedAt: now })
|
||||
c.session = finish({ ...c.reader.session, path: f.path }, f)
|
||||
return c
|
||||
}
|
||||
|
||||
function finish(s, f) {
|
||||
if (!s.id) s.id = idOf(f.src, f.path)
|
||||
if (f.src.subagent) {
|
||||
s.subagent = true
|
||||
if (!s.parent) s.parent = parentOf(f.src, f.path, s.id)
|
||||
}
|
||||
if (f.src.kind === "kimi" && s.subagent && !s.parent) s.parent = parentOf(f.src, f.path, s.id)
|
||||
if (f.src.profile) s.profile = f.src.profile
|
||||
if (!s.updated) s.updated = f.mtime
|
||||
// the file's own time: a line being written is the session at work
|
||||
s.touched = f.mtime
|
||||
@@ -265,5 +455,5 @@ export function createScanner(opts = {}) {
|
||||
return s
|
||||
}
|
||||
|
||||
return { scan, files, setSources: (x) => { srcs = x; files.clear() } }
|
||||
return { scan, files, setSources: (x) => { srcs = x; files.clear(); titleCache = null } }
|
||||
}
|
||||
|
||||
@@ -70,6 +70,12 @@ function fromFiles(s, text) {
|
||||
started: s.started, updated: Math.max(s.updated || 0, s.touched || 0), touched: s.touched,
|
||||
phase: s.phase || "done", step: text ? s.step : (s.stepName || ""), reply: text ? s.reply : "", error: text ? s.error : "",
|
||||
pendingSince: s.pending?.[0]?.at || 0, turns: s.turns,
|
||||
// the workbench's extra facts: a child session, its recent words, and
|
||||
// what this session used today. Words are dropped with text off.
|
||||
subagent: s.subagent === true, parent: s.parent || "", profile: s.profile || "",
|
||||
messages: text && Array.isArray(s.messages) ? s.messages.slice(-8) : [],
|
||||
tokensToday: Number(s.tokensToday) || 0, turnsToday: Number(s.turnsToday) || 0,
|
||||
context: Number(s.context) || 0, contextWindow: Number(s.contextWindow) || 0,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-office",
|
||||
"version": "0.1.1",
|
||||
"description": "我的 Agent 在干嘛:读取本机 Claude Code、Codex、DeepSeek Harness、Gemini CLI、Qwen Code、Pi、omp、Qoder、WorkBuddy、CodeBuddy 的会话文件(提问、回复与工具命令,可用 text:false 关闭文本),把每个会话画成太空站办公室里的小人(3D/2D)或列表。Live agent activity dashboard for magpie that reads local agent session files.",
|
||||
"version": "0.2.0",
|
||||
"description": "我的 Agent 在干嘛:读取本机 Claude Code、Codex、Copilot CLI、Kimi Code、DeepSeek Harness、Gemini CLI、Qwen Code、Pi、omp、Qoder、WorkBuddy、CodeBuddy、Grok Build 的会话文件,把每个会话画成真 3D / 等距 / 2D 办公室里的小人,或分组工作台。Live agent activity dashboard for magpie, with a real WebGL office and six scenes.",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"page/index.html",
|
||||
@@ -12,12 +12,16 @@
|
||||
"page/scene.js",
|
||||
"page/app.js",
|
||||
"page/icon.svg",
|
||||
"page/scene3d.js",
|
||||
"page/three.min.js",
|
||||
"page/icons",
|
||||
"lib",
|
||||
"office.hooks.mjs",
|
||||
"CHANGELOG.md",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
"LICENSE",
|
||||
"bin",
|
||||
"SKILL.md"
|
||||
],
|
||||
"keywords": [
|
||||
"magpie",
|
||||
@@ -27,7 +31,11 @@
|
||||
"status",
|
||||
"office",
|
||||
"dashboard",
|
||||
"opencode"
|
||||
"opencode",
|
||||
"3d",
|
||||
"threejs",
|
||||
"webgl",
|
||||
"scenes"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
@@ -66,7 +74,17 @@
|
||||
"showDone": true,
|
||||
"hideAfter": "6h",
|
||||
"text": true,
|
||||
"remote": false
|
||||
"remote": false,
|
||||
"scene": "office",
|
||||
"quality": "medium",
|
||||
"agents": [],
|
||||
"showSub": true,
|
||||
"showIdle": true,
|
||||
"side": false,
|
||||
"lang": "auto"
|
||||
}
|
||||
},
|
||||
"bin": {
|
||||
"agent-office": "bin/agent-office.mjs"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,58 +1,91 @@
|
||||
// The page: loads live.js (what the plugin's host part wrote) again every
|
||||
// second, works out each agent's status (model.js), and draws the office
|
||||
// (scene.js) or the list. It reads nothing of magpie's but its own options,
|
||||
// and has no network: live.js is one of its own files.
|
||||
// (scene.js) or the grouped workbench. It reads nothing of magpie's but its
|
||||
// own options, and has no network: live.js is one of its own files.
|
||||
//
|
||||
// Interaction, kept calm on purpose: nothing opens because the pointer
|
||||
// passes over it. Hovering only highlights. A click on a worker, its name
|
||||
// tag, or a row opens that agent's panel at the side, which stays put (it
|
||||
// doesn't ride the animation) until it's closed or another agent is
|
||||
// clicked. The DOM is updated in place: nothing is rebuilt each second.
|
||||
// tag, a list row or a side-rail row opens that agent's panel at the side,
|
||||
// which stays put until it's closed or another agent is clicked. The DOM is
|
||||
// updated in place: nothing is rebuilt each second unless it really changed.
|
||||
(async () => {
|
||||
const M = globalThis.AgentOfficeModel
|
||||
const I = globalThis.AgentOfficeIcons
|
||||
const { Scene } = globalThis.AgentOfficeScene
|
||||
const Scene3D = globalThis.AgentOfficeScene3D
|
||||
const $ = (id) => document.getElementById(id)
|
||||
const theme = await magpie.ready
|
||||
let lang = theme.lang
|
||||
let opts = {}
|
||||
try { opts = (await magpie.options.get()) || {} } catch {}
|
||||
const view = {
|
||||
mode: opts.mode === "list" ? "list" : "office",
|
||||
dim: opts.dim === "2d" ? "2d" : "3d",
|
||||
demo: opts.demo === true,
|
||||
showDone: opts.showDone !== false,
|
||||
hideAfter: M.HIDE[opts.hideAfter] !== undefined ? opts.hideAfter : M.DEFAULTS.hideAfter,
|
||||
text: opts.text !== false,
|
||||
approvalAfterSec: Number(opts.approvalAfterSec) > 0 ? Number(opts.approvalAfterSec) : M.DEFAULTS.approvalAfterSec,
|
||||
cleared: opts.cleared && typeof opts.cleared === "object" && !Array.isArray(opts.cleared) ? { ...opts.cleared } : {},
|
||||
}
|
||||
const state = { snap: null, loaded: false, list: [], open: "", hover: "", showText: true }
|
||||
let floatHome = null
|
||||
const t = () => M.text(lang)
|
||||
const el = (tag, cls, text) => {
|
||||
const e = document.createElement(tag)
|
||||
if (cls) e.className = cls
|
||||
if (text != null) e.textContent = text
|
||||
return e
|
||||
}
|
||||
const theme = await magpie.ready
|
||||
let themeLang = theme.lang
|
||||
let opts = {}
|
||||
try { opts = (await magpie.options.get()) || {} } catch {}
|
||||
const view = {
|
||||
mode: opts.mode === "list" ? "list" : "office",
|
||||
dim: ["2d", "iso", "3d"].includes(opts.dim) ? opts.dim : "3d",
|
||||
scene: ["office", "station", "cafe", "castle", "pirate", "graveyard"].includes(opts.scene) ? opts.scene : "office",
|
||||
quality: ["low", "medium", "high"].includes(opts.quality) ? opts.quality : "medium",
|
||||
demo: opts.demo === true,
|
||||
showDone: opts.showDone !== false,
|
||||
hideAfter: M.HIDE[opts.hideAfter] !== undefined ? opts.hideAfter : M.DEFAULTS.hideAfter,
|
||||
text: opts.text !== false,
|
||||
approvalAfterSec: Number(opts.approvalAfterSec) > 0 ? Number(opts.approvalAfterSec) : M.DEFAULTS.approvalAfterSec,
|
||||
showSub: opts.showSub !== false,
|
||||
showIdle: opts.showIdle !== false,
|
||||
agents: Array.isArray(opts.agents) ? opts.agents.filter((x) => typeof x === "string") : [],
|
||||
// an old saved side:true predates the default-closed rail; it is
|
||||
// ignored until this version saves the preference again
|
||||
side: opts.side === true && Number(opts.sideV) === 2,
|
||||
cleared: opts.cleared && typeof opts.cleared === "object" && !Array.isArray(opts.cleared) ? { ...opts.cleared } : {},
|
||||
}
|
||||
let manualLang = opts.lang === "auto" || M.LANG_NAMES[opts.lang] ? opts.lang : "auto"
|
||||
const state = {
|
||||
snap: null, loaded: false, all: [], list: [], open: "", hover: "", showText: true,
|
||||
alerts: new Map(), alertsSeeded: false, scene3Failed: false,
|
||||
}
|
||||
let floatHome = null
|
||||
const t = () => M.text(lang)
|
||||
const navLangs = () => (navigator.languages && navigator.languages.length ? navigator.languages : [navigator.language])
|
||||
// manual pick → the newest prompt's script → magpie's theme → the browser
|
||||
function pickLang(sample) {
|
||||
return M.detectLang({ manual: manualLang, theme: themeLang, nav: navLangs(), sample: view.text && state.snap?.text !== false ? (sample || M.sample(state.snap)) : "" })
|
||||
}
|
||||
let lang = pickLang()
|
||||
|
||||
// a status as a person reads it: the sub-state says more than the six
|
||||
function label(a) {
|
||||
const w = t()
|
||||
if (a.sub === "approval") return w.approval
|
||||
if (a.sub === "ask") return w.ask
|
||||
if (a.sub === "stopped") return w.stopped
|
||||
if (a.sub === "noprog") return w.noProgress
|
||||
if (a.sub === "stuck") return M.fill(w.stuck, M.duration(Date.now() - a.at, lang))
|
||||
// a finished session nobody has touched for a while is idling
|
||||
if (a.idle && a.status === "done") return w.idle
|
||||
return w[a.status]
|
||||
}
|
||||
|
||||
// ---- words -----------------------------------------------------------
|
||||
let lastLegend = ""
|
||||
let langSelectSig = ""
|
||||
function words() {
|
||||
document.querySelectorAll("[data-t]").forEach((e) => { e.textContent = t()[e.dataset.t] })
|
||||
$("pip").textContent = floatHome ? t().pipOn : t().pip
|
||||
document.documentElement.lang = lang || "en"
|
||||
statusLegend()
|
||||
lastLegend = ""
|
||||
railSig = ""
|
||||
todaySig = ""
|
||||
langSelectSig = ""
|
||||
syncLangSelect()
|
||||
if (typeof scene2 !== "undefined") scene2.lang = lang
|
||||
if ($("optScene")) {
|
||||
for (const option of $("optScene").options) option.textContent = t()["scene" + ({office:"Office",station:"Station",cafe:"Cafe",castle:"Castle",pirate:"Pirate",graveyard:"Graveyard"})[option.value]]
|
||||
}
|
||||
}
|
||||
|
||||
function statusLegend() {
|
||||
@@ -66,7 +99,6 @@
|
||||
}
|
||||
|
||||
// the agents in the office now, each once, by its own icon
|
||||
let lastLegend = ""
|
||||
function brandLegend() {
|
||||
const ids = []
|
||||
for (const a of state.list) if (!ids.includes(a.agent)) ids.push(a.agent)
|
||||
@@ -108,7 +140,40 @@
|
||||
}
|
||||
|
||||
// ---- the office ------------------------------------------------------
|
||||
const scene = new Scene($("office"), { dim: view.dim, onFrame: place })
|
||||
// two renderers share the stage: the canvas isometric/2D one and a real
|
||||
// WebGL one. They cannot share a canvas context, so each has its own and
|
||||
// only the selected one is visible and running.
|
||||
const office2 = $("office"), office3 = $("office3d")
|
||||
const scene2 = new Scene(office2, { dim: view.dim === "2d" ? "2d" : "3d", onFrame: (anchors) => { if (scene === scene2 && view.mode === "office" && !document.hidden) place(anchors) } })
|
||||
let scene3 = null
|
||||
let scene = scene2
|
||||
|
||||
function wants3D() { return view.mode === "office" && view.dim === "3d" && !!Scene3D && !state.scene3Failed }
|
||||
function ensure3D() {
|
||||
if (!wants3D()) return null
|
||||
if (!scene3) {
|
||||
try {
|
||||
scene3 = new Scene3D(office3, { scene: view.scene, quality: view.quality, agents: state.list, onFrame: (anchors) => { if (scene === scene3 && view.mode === "office" && !document.hidden) place(anchors) } })
|
||||
if (!scene3.available) { try { scene3.dispose() } catch {} ; scene3 = null; state.scene3Failed = true }
|
||||
} catch { scene3 = null; state.scene3Failed = true }
|
||||
}
|
||||
if (scene3 && scene3.id !== view.scene) scene3.setScene(view.scene)
|
||||
return scene3
|
||||
}
|
||||
function activateScene() {
|
||||
office3.hidden = !wants3D()
|
||||
const s3 = ensure3D()
|
||||
if (s3) {
|
||||
if (scene !== s3) { try { scene2.stop() } catch {} ; scene = s3 }
|
||||
office2.hidden = true; office3.hidden = false
|
||||
return s3
|
||||
}
|
||||
if (scene3) scene3.stop()
|
||||
scene = scene2
|
||||
office2.hidden = false; office3.hidden = true
|
||||
scene2.setDim(view.dim === "2d" ? "2d" : "3d")
|
||||
return scene2
|
||||
}
|
||||
const tags = new Map()
|
||||
|
||||
function tagFor(a) {
|
||||
@@ -123,7 +188,7 @@
|
||||
$("tags").append(e)
|
||||
tags.set(a.key, e)
|
||||
}
|
||||
const sig = [a.brand.icon, a.brand.name, a.title, a.status].join("|")
|
||||
const sig = [a.brand.icon, a.brand.name, a.title, a.status, a.sub].join("|")
|
||||
if (e.dataset.sig !== sig) {
|
||||
e.dataset.sig = sig
|
||||
const name = el("span", "tn", a.title)
|
||||
@@ -145,28 +210,38 @@
|
||||
const shown = []
|
||||
for (const p of anchors) {
|
||||
const e = tags.get(p.key)
|
||||
if (!e) continue
|
||||
if (!e._w) e._w = e.offsetWidth || 90
|
||||
if (!e || p.visible === false) continue
|
||||
// Hidden labels have zero offsetWidth: measure them invisibly so
|
||||
// collision tests use actual text width, never a guessed 90px.
|
||||
if (e.hidden) { e.style.visibility = "hidden"; e.hidden = false }
|
||||
e._w = e.offsetWidth || 190
|
||||
e.style.visibility = ""
|
||||
shown.push({ e, p })
|
||||
}
|
||||
// two tags that would sit on each other are stacked, the lower one first
|
||||
shown.sort((a, b) => a.p.y - b.p.y || a.p.x - b.p.x)
|
||||
const placed = []
|
||||
const H = 24
|
||||
for (const it of shown) {
|
||||
let y = it.p.y
|
||||
for (let pass = 0; pass < 6; pass++) {
|
||||
const hit = placed.find((q) => Math.abs(q.x - it.p.x) < (q.w + it.e._w) / 2 + 4 && Math.abs(q.y - y) < H)
|
||||
if (!hit) break
|
||||
y = hit.y - H
|
||||
}
|
||||
it.y = y
|
||||
placed.push({ x: it.p.x, y, w: it.e._w })
|
||||
// with many agents the office can hold more name tags than it can show
|
||||
// without turning into a wall of labels: keep the ones that need you,
|
||||
// are working, are selected/hovered, then the rest by recency
|
||||
const box = $("tags")
|
||||
const W = box?.clientWidth || 0
|
||||
const limit = floatHome ? 4 : W < 850 ? 4 : W < 1100 ? 5 : W < 1500 ? 6 : 8
|
||||
const rank = new Map()
|
||||
for (const a of state.list) {
|
||||
const r = a.key === state.open || a.key === state.hover ? 0
|
||||
: a.status === "waiting" || a.status === "error" ? 1
|
||||
: a.status === "thinking" || a.status === "executing" || a.status === "replying" ? 2
|
||||
: 3
|
||||
rank.set(a.key, r)
|
||||
}
|
||||
for (const it of shown) {
|
||||
seen.add(it.p.key)
|
||||
const tf = `translate(${Math.round(it.p.x)}px, ${Math.round(it.y)}px) translate(-50%, -100%)`
|
||||
if (it.e.style.transform !== tf) it.e.style.transform = tf
|
||||
shown.sort((a, b) => (rank.get(a.p.key) ?? 3) - (rank.get(b.p.key) ?? 3) || b.p.y - a.p.y)
|
||||
const byKey = new Map(shown.map(it => [it.p.key, it]))
|
||||
const arranged = M.layoutTags(shown.filter(it => !few || few.has(it.p.key)).map(it => ({
|
||||
key: it.p.key, x: it.p.x, y: it.p.y, w: it.e._w, h: it.e.offsetHeight || 22,
|
||||
})), W, box?.clientHeight || 0, limit)
|
||||
for (const it of arranged) {
|
||||
const e = byKey.get(it.key).e
|
||||
seen.add(it.key)
|
||||
const tf = `translate(${Math.round(it.x)}px, ${Math.round(it.y)}px) translate(-50%, -100%)`
|
||||
if (e.style.transform !== tf) e.style.transform = tf
|
||||
}
|
||||
for (const [k, e] of tags) {
|
||||
const hide = !seen.has(k) || (few ? !few.has(k) : false)
|
||||
@@ -182,24 +257,42 @@
|
||||
for (const [k, e] of tags) e.classList.toggle("hot", k === key)
|
||||
}
|
||||
|
||||
let moveQueued = false
|
||||
$("office").addEventListener("pointermove", (e) => {
|
||||
if (moveQueued) return
|
||||
moveQueued = true
|
||||
const x = e.offsetX, y = e.offsetY
|
||||
requestAnimationFrame(() => {
|
||||
moveQueued = false
|
||||
const k = scene.hit(x, y)
|
||||
$("office").style.cursor = k ? "pointer" : ""
|
||||
highlight(k)
|
||||
function bindCanvas(canvas) {
|
||||
let moveQueued = false
|
||||
canvas.addEventListener("pointermove", (e) => {
|
||||
if (moveQueued) return
|
||||
moveQueued = true
|
||||
const x = e.offsetX, y = e.offsetY
|
||||
requestAnimationFrame(() => {
|
||||
moveQueued = false
|
||||
const k = scene.hit(x, y)
|
||||
canvas.style.cursor = k ? "pointer" : (canvas === office3 ? "grab" : "")
|
||||
highlight(k)
|
||||
})
|
||||
})
|
||||
})
|
||||
$("office").addEventListener("pointerleave", () => highlight(""))
|
||||
$("office").addEventListener("click", (e) => {
|
||||
const k = scene.hit(e.offsetX, e.offsetY)
|
||||
if (k) open(k)
|
||||
else close()
|
||||
})
|
||||
canvas.addEventListener("pointerleave", () => highlight(""))
|
||||
canvas.addEventListener("click", (e) => {
|
||||
if (scene === scene3 && scene3.dragged) { scene3.dragged = false; return }
|
||||
const k = scene.hit(e.offsetX, e.offsetY)
|
||||
if (k) open(k)
|
||||
else close()
|
||||
})
|
||||
}
|
||||
bindCanvas(office2)
|
||||
bindCanvas(office3)
|
||||
|
||||
// ---- context bars ------------------------------------------------------
|
||||
// 60% is worth noticing, 85% is nearly full; both use the same bar.
|
||||
function ctxBar(c, name) {
|
||||
const e = el("div", "ctx" + (c.level === "warn" || c.level === "full" ? " " + c.level : ""))
|
||||
const bar = el("span", "bar")
|
||||
const fill = el("i")
|
||||
fill.style.width = c.pct + "%"
|
||||
bar.append(fill)
|
||||
e.append(el("span", "cn", name), bar, el("span", "cp", c.pct + "%"))
|
||||
e.title = `${name} ${M.fmtTokens(c.used)} / ${M.fmtTokens(c.window)}`
|
||||
return e
|
||||
}
|
||||
|
||||
// ---- the panel ---------------------------------------------------------
|
||||
// one agent, opened by a click, at the side; it doesn't move with the
|
||||
@@ -226,20 +319,43 @@
|
||||
P.step = el("div", "pstep")
|
||||
P.err = el("div", "perr")
|
||||
P.reply = el("div", "pr")
|
||||
P.ctx = el("div", "pctx")
|
||||
P.convoHead = el("div", "pconvo-h")
|
||||
P.msgs = el("div", "pmsgs")
|
||||
const foot = el("div", "pf")
|
||||
P.meta = el("span", "pm")
|
||||
P.copy = el("button", "pc")
|
||||
P.copy.type = "button"
|
||||
P.copy.addEventListener("click", (e) => { e.stopPropagation(); showCommand(P.copy.dataset.value, P.copy) })
|
||||
P.clear = el("button", "pc pclr")
|
||||
P.clear = el("button", "pc")
|
||||
P.clear.type = "button"
|
||||
P.clear.addEventListener("click", (e) => { e.stopPropagation(); clearAgent(state.open) })
|
||||
P.clear.addEventListener("click", (e) => { e.stopPropagation(); clearAgent(P.clear.dataset.key) })
|
||||
foot.append(P.meta, P.copy, P.clear)
|
||||
P.src = el("div", "psrc")
|
||||
panel.replaceChildren(head, P.title, P.status, P.query, P.step, P.err, P.reply, foot, P.src)
|
||||
panel.replaceChildren(head, P.title, P.status, P.query, P.step, P.err, P.reply, P.ctx, P.convoHead, P.msgs, foot, P.src)
|
||||
})()
|
||||
panel.addEventListener("click", (e) => e.stopPropagation())
|
||||
|
||||
const clock = (at) => {
|
||||
const d = new Date(Number(at))
|
||||
if (Number.isNaN(d.getTime())) return ""
|
||||
return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`
|
||||
}
|
||||
let msgSig = ""
|
||||
function renderMessages(msgs) {
|
||||
const sig = JSON.stringify(msgs)
|
||||
if (sig === msgSig) return
|
||||
msgSig = sig
|
||||
P.msgs.replaceChildren(...msgs.map((m) => {
|
||||
const role = m?.role === "assistant" ? "assistant" : m?.role === "tool" ? "tool" : "user"
|
||||
const row = el("div", "msg " + role)
|
||||
if (role !== "tool") row.append(el("span", "mn", m?.name || (role === "assistant" ? t().agent : role === "user" ? t().you : "")))
|
||||
row.append(document.createTextNode(String(m?.text || "")))
|
||||
if (m?.at) row.append(el("span", "mt", clock(m.at)))
|
||||
return row
|
||||
}))
|
||||
}
|
||||
|
||||
const ICON = { done: "✓", error: "!", waiting: "?", thinking: "…", executing: "⟳", replying: "✎" }
|
||||
function fillPanel(a) {
|
||||
const w = t()
|
||||
@@ -254,13 +370,23 @@
|
||||
P.status.className = "ps " + a.status
|
||||
setText(P.stIcon, ICON[a.status] || "")
|
||||
setText(P.stText, label(a))
|
||||
const more = a.status === "executing" && a.since > 3000 ? M.fill(w.ran, M.duration(a.since, lang)) : a.turns ? M.fill(w.turns, a.turns) : ""
|
||||
const more = a.sub === "noprog" || a.sub === "stuck" ? M.duration(Date.now() - a.at, lang)
|
||||
: a.status === "executing" && a.since > 3000 ? M.fill(w.ran, M.duration(a.since, lang))
|
||||
: a.turns ? M.fill(w.turns, a.turns) : ""
|
||||
setText(P.stMore, more)
|
||||
const q = a.query || (state.showText ? "" : w.quiet)
|
||||
setText(P.query, q); P.query.hidden = !q
|
||||
setText(P.step, a.step ? "› " + a.step : ""); P.step.hidden = !a.step
|
||||
setText(P.err, a.error); P.err.hidden = !a.error
|
||||
setText(P.reply, a.reply ? "← " + a.reply : ""); P.reply.hidden = !a.reply
|
||||
// context fullness, when the agent's files carry usage
|
||||
P.ctx.hidden = !a.ctx
|
||||
if (a.ctx) P.ctx.replaceChildren(ctxBar(a.ctx, w.context))
|
||||
// the conversation: only when text is on and the session has messages
|
||||
const msgs = state.showText && !a.private && Array.isArray(a.messages) ? a.messages.slice(-8) : []
|
||||
P.convoHead.hidden = P.msgs.hidden = !msgs.length
|
||||
setText(P.convoHead, msgs.length ? w.recent : "")
|
||||
renderMessages(msgs)
|
||||
setText(P.meta, [a.model, a.project].filter(Boolean).join(" · "))
|
||||
const copy = a.resume || a.session
|
||||
P.copy.hidden = !copy
|
||||
@@ -271,17 +397,18 @@
|
||||
P.copy.dataset.label = a.resume ? w.copyResume : w.copySession
|
||||
P.copy.textContent = P.copy.dataset.label
|
||||
}
|
||||
P.clear.hidden = !M.clearable(a.status)
|
||||
P.clear.hidden = !M.clearable(a)
|
||||
P.clear.dataset.key = a.key
|
||||
setText(P.clear, w.clear)
|
||||
P.clear.title = w.clearTip
|
||||
setText(P.src, a.source === "files" ? w.fromFiles : w.via)
|
||||
}
|
||||
|
||||
// out of the office until its session moves again; kept in the options,
|
||||
// only for sessions live.js still has
|
||||
// out of the office until its session moves again; kept in options, only
|
||||
// for sessions live.js still has
|
||||
function clearAgent(key) {
|
||||
const a = state.list.find((x) => x.key === key)
|
||||
if (!a || !M.clearable(a.status)) return
|
||||
if (!a || !M.clearable(a)) return
|
||||
const now = Date.now()
|
||||
const known = new Set((snapshot(now)?.sessions || []).map((s) => s?.key))
|
||||
const next = {}
|
||||
@@ -299,18 +426,33 @@
|
||||
if (!a) return
|
||||
state.open = key
|
||||
scene.selected = key
|
||||
scene.setSelected?.(key)
|
||||
msgSig = ""
|
||||
fillPanel(a)
|
||||
panel.hidden = false
|
||||
positionOverlays()
|
||||
$("rail").hidden = true
|
||||
for (const [k, e] of tags) e.classList.toggle("on", k === key)
|
||||
for (const tr of $("rows").children) tr.classList.toggle("on", tr.dataset.key === key)
|
||||
for (const b of $("railGroups").querySelectorAll(".rail-row")) b.classList.toggle("on", b.dataset.key === key)
|
||||
}
|
||||
function clearPanelText() {
|
||||
for (const n of [P.title, P.query, P.step, P.err, P.reply, P.convoHead, P.msgs, P.meta, P.src]) n.replaceChildren()
|
||||
P.copy.nextElementSibling?.classList.contains("pcopy") && P.copy.nextElementSibling.remove()
|
||||
delete P.copy.dataset.value
|
||||
msgSig = ""
|
||||
}
|
||||
function close() {
|
||||
if (!state.open) return
|
||||
state.open = ""
|
||||
scene.selected = ""
|
||||
scene.setSelected?.(null)
|
||||
panel.hidden = true
|
||||
clearPanelText()
|
||||
renderRail()
|
||||
for (const e of tags.values()) e.classList.remove("on")
|
||||
for (const tr of $("rows").children) tr.classList.remove("on")
|
||||
for (const b of $("railGroups").querySelectorAll(".rail-row")) b.classList.remove("on")
|
||||
}
|
||||
|
||||
// magpie frames a page with allow="", so a page cannot reach the
|
||||
@@ -330,6 +472,7 @@
|
||||
// ---- the list --------------------------------------------------------
|
||||
// rows kept by key and updated in place, so nothing jumps under the pointer
|
||||
const rowsByKey = new Map()
|
||||
const groupRows = new Map()
|
||||
function rowFor(a) {
|
||||
let r = rowsByKey.get(a.key)
|
||||
if (!r) {
|
||||
@@ -350,7 +493,10 @@
|
||||
if (r.mark.dataset.icon !== a.brand.icon) { r.mark.dataset.icon = a.brand.icon; r.mark.replaceChildren(I.mark(a.brand, 16)) }
|
||||
set(r.name, a.brand.name)
|
||||
set(r.title, a.title)
|
||||
set(r.sub, a.status === "waiting" || a.status === "done" || a.status === "error" ? a.error || a.reply || a.step || a.query : a.step || a.query)
|
||||
const sub = a.sub === "noprog" || a.sub === "stuck" ? label(a)
|
||||
: a.status === "waiting" || a.status === "done" || a.status === "error" ? a.error || a.reply || a.step || a.query
|
||||
: a.step || a.query
|
||||
set(r.sub, sub)
|
||||
r.badge.style.setProperty("--c", M.COLORS[a.status])
|
||||
set(r.badge, label(a))
|
||||
set(r.dir, a.project)
|
||||
@@ -359,37 +505,252 @@
|
||||
r.tr.classList.toggle("on", a.key === state.open)
|
||||
return r.tr
|
||||
}
|
||||
// a heading row per group, reused across refreshes
|
||||
function groupRowFor(key) {
|
||||
let r = groupRows.get(key)
|
||||
if (!r) {
|
||||
const tr = el("tr", "group")
|
||||
const td = el("td")
|
||||
td.colSpan = 6
|
||||
r = { tr, label: el("span", "glabel"), count: el("span", "gcount") }
|
||||
td.append(r.label, r.count)
|
||||
tr.append(td)
|
||||
groupRows.set(key, r)
|
||||
}
|
||||
return r
|
||||
}
|
||||
function rows() {
|
||||
const list = M.sorted(state.list)
|
||||
$("emptyList").hidden = list.length > 0
|
||||
$("emptyList").textContent = emptyText()
|
||||
const want = list.map(rowFor)
|
||||
const body = $("rows")
|
||||
const keys = new Set(list.map((a) => a.key))
|
||||
for (const [k, r] of rowsByKey) if (!keys.has(k)) { r.tr.remove(); rowsByKey.delete(k) }
|
||||
// put rows in order, moving only the ones out of place
|
||||
const groups = M.groups(state.list)
|
||||
const want = []
|
||||
const usedGroups = new Set()
|
||||
for (const g of groups) {
|
||||
if (!g.list.length) continue
|
||||
usedGroups.add(g.key)
|
||||
const head = groupRowFor(g.key)
|
||||
const name = t()[g.key]
|
||||
if (head.label.textContent !== name) head.label.textContent = name
|
||||
head.count.textContent = g.list.length
|
||||
want.push(head.tr, ...g.list.map(rowFor))
|
||||
}
|
||||
for (const [k, r] of rowsByKey) {
|
||||
if (!groups.some((g) => g.list.some((a) => a.key === k))) { r.tr.remove(); rowsByKey.delete(k) }
|
||||
}
|
||||
for (const [k, r] of groupRows) if (!usedGroups.has(k)) r.tr.remove()
|
||||
want.forEach((tr, i) => { if (body.children[i] !== tr) body.insertBefore(tr, body.children[i] || null) })
|
||||
while (body.children.length > want.length) body.lastElementChild.remove()
|
||||
$("emptyList").hidden = state.list.length > 0
|
||||
$("emptyList").textContent = emptyText()
|
||||
}
|
||||
|
||||
function emptyText() {
|
||||
return state.loaded && state.snap ? t().empty : t().noFile
|
||||
}
|
||||
|
||||
// ---- the side rail ----------------------------------------------------
|
||||
// the same three groups as the list, in a compact panel over the office;
|
||||
// a row opens the same click-only detail panel
|
||||
let railSig = ""
|
||||
function renderRail() {
|
||||
const rail = $("rail")
|
||||
const menus = ($("settings") && !$("settings").hidden) || ($("todayMenu") && !$("todayMenu").hidden)
|
||||
const show = view.side && view.mode === "office" && !floatHome && !state.open && !menus
|
||||
rail.hidden = !show
|
||||
if (show) positionOverlays()
|
||||
const btn = $("sideBtn")
|
||||
btn.classList.toggle("on", view.side)
|
||||
btn.setAttribute("aria-pressed", String(view.side))
|
||||
$("railCount").textContent = state.list.length
|
||||
const groups = M.groups(state.list)
|
||||
const sig = JSON.stringify([lang, state.showText, groups.map(g => [g.key, g.list.map(a => [a.key, a.title, label(a), a.status, a.at])])])
|
||||
if (sig === railSig) return
|
||||
railSig = sig
|
||||
const kids = []
|
||||
for (const g of groups) {
|
||||
if (!g.list.length) continue
|
||||
kids.push(el("div", "rail-group", `${t()[g.key]} · ${g.list.length}`))
|
||||
for (const a of g.list) {
|
||||
const row = el("button", "rail-row")
|
||||
row.type = "button"
|
||||
row.dataset.key = a.key
|
||||
row.classList.toggle("on", a.key === state.open)
|
||||
row.append(I.mark(a.brand, 15))
|
||||
row.append(el("span", "rn", a.title || a.project || a.brand.name))
|
||||
const st = el("span", "rs", label(a))
|
||||
st.style.color = M.COLORS[a.status]
|
||||
row.append(st)
|
||||
row.title = `${a.brand.name} · ${label(a)}`
|
||||
row.addEventListener("click", (e) => { e.stopPropagation(); open(a.key) })
|
||||
kids.push(row)
|
||||
}
|
||||
}
|
||||
$("railGroups").replaceChildren(...kids)
|
||||
}
|
||||
|
||||
// ---- Today ------------------------------------------------------------
|
||||
let todaySig = ""
|
||||
function renderToday() {
|
||||
const data = M.today(state.list)
|
||||
$("todayTokens").textContent = data.hasUsage && data.tokens ? M.fmtTokens(data.tokens) : ""
|
||||
const sig = lang + "|" + JSON.stringify(data)
|
||||
if (sig === todaySig) return
|
||||
todaySig = sig
|
||||
const w = t()
|
||||
const panel = $("todayMenu")
|
||||
const kids = []
|
||||
if (!data.hasUsage && !data.contexts.length) {
|
||||
panel.replaceChildren(el("div", "today-note", w.noUsage))
|
||||
return
|
||||
}
|
||||
const big = el("div", "today-big")
|
||||
for (const [value, name] of [[data.turns, w.turnsL], [M.fmtTokens(data.tokens), w.tokensL], [data.agentCount, w.agentsL]]) {
|
||||
const box = el("div")
|
||||
box.append(el("b", null, String(value)), el("span", null, name))
|
||||
big.append(box)
|
||||
}
|
||||
kids.push(big)
|
||||
const agents = Object.values(data.byAgent).sort((a, b) => b.turns - a.turns || b.tokens - a.tokens)
|
||||
for (const a of agents) {
|
||||
const row = el("div", "today-row")
|
||||
row.append(I.mark(M.brand(a.agent), 16), el("span", "trn", a.name), el("span", "n", `${a.turns} ${w.turnsL} · ${M.fmtTokens(a.tokens)}`))
|
||||
kids.push(row)
|
||||
}
|
||||
if (data.projects.length) {
|
||||
kids.push(el("div", "today-head", w.topProjects))
|
||||
for (const p of data.projects) {
|
||||
const row = el("div", "today-row")
|
||||
row.append(el("span", "trn", p.project), el("span", "n", `${p.turns} ${w.turnsL} · ${M.fmtTokens(p.tokens)}`))
|
||||
kids.push(row)
|
||||
}
|
||||
}
|
||||
if (data.contexts.length) {
|
||||
kids.push(el("div", "today-head", w.context))
|
||||
for (const c of data.contexts) kids.push(ctxBar(c, c.name || c.agent))
|
||||
}
|
||||
if (!data.hasUsage) kids.push(el("div", "today-note", w.noUsage))
|
||||
else kids.push(el("div", "today-note", w.summaryNote))
|
||||
panel.replaceChildren(...kids)
|
||||
}
|
||||
|
||||
// ---- the per-agent filter / language selector -------------------------
|
||||
let agentFilterSig = ""
|
||||
function renderAgentFilter() {
|
||||
const ids = [...new Set(state.all.map((a) => a.agent))].sort()
|
||||
for (const id of view.agents) if (!ids.includes(id)) ids.push(id)
|
||||
const counts = ids.map((id) => `${id}:${state.all.filter((a) => a.agent === id).length}`).join(",")
|
||||
const sig = lang + "|" + counts + "|" + view.agents.join(",")
|
||||
if (sig === agentFilterSig) return
|
||||
agentFilterSig = sig
|
||||
const box = $("optAgents")
|
||||
const kids = []
|
||||
const allRow = el("label", "af")
|
||||
const allBox = document.createElement("input")
|
||||
allBox.type = "checkbox"
|
||||
allBox.checked = view.agents.length === 0
|
||||
allBox.addEventListener("change", () => { view.agents = []; agentFilterSig = ""; renderAgentFilter(); refresh(); save() })
|
||||
allRow.append(allBox, el("span", "afn", t().allAgents))
|
||||
kids.push(allRow)
|
||||
for (const id of ids) {
|
||||
const b = M.brand(id)
|
||||
const row = el("label", "af")
|
||||
const cbox = document.createElement("input")
|
||||
cbox.type = "checkbox"
|
||||
cbox.checked = view.agents.includes(id)
|
||||
cbox.dataset.agent = id
|
||||
cbox.addEventListener("change", () => {
|
||||
const next = view.agents.filter((x) => x !== id)
|
||||
if (cbox.checked) next.push(id)
|
||||
view.agents = next
|
||||
agentFilterSig = ""
|
||||
renderAgentFilter()
|
||||
refresh()
|
||||
save()
|
||||
})
|
||||
row.append(cbox, I.mark(b, 15), el("span", "afn", b.name), el("span", "afc", String(state.all.filter((a) => a.agent === id).length)))
|
||||
kids.push(row)
|
||||
}
|
||||
box.replaceChildren(...kids)
|
||||
}
|
||||
|
||||
function syncLangSelect() {
|
||||
const sel = $("optLang")
|
||||
const sig = lang + "|" + manualLang
|
||||
if (sig === langSelectSig) return
|
||||
langSelectSig = sig
|
||||
const kids = []
|
||||
const option = (value, name) => { const o = document.createElement("option"); o.value = value; o.textContent = name; return o }
|
||||
kids.push(option("auto", t().auto))
|
||||
for (const code of M.LANGS) kids.push(option(code, M.LANG_NAMES[code]))
|
||||
sel.replaceChildren(...kids)
|
||||
sel.value = manualLang
|
||||
}
|
||||
|
||||
// ---- in-page toasts ---------------------------------------------------
|
||||
// magpie frames the page with allow="", so the browser's desktop
|
||||
// notifications are blocked; a small in-page toast opens the agent when
|
||||
// clicked instead.
|
||||
function showToast(a) {
|
||||
const box = $("toasts")
|
||||
while (box.children.length >= 3) box.firstElementChild.remove()
|
||||
const b = el("button", "toast" + (a.status === "error" ? " error" : ""))
|
||||
b.type = "button"
|
||||
b.append(I.mark(a.brand, 18))
|
||||
const text = el("span", "tn")
|
||||
text.append(el("b", null, a.brand.name), el("span", null, `${label(a)} · ${a.title}`))
|
||||
b.append(text)
|
||||
b.title = t().dismiss
|
||||
b.addEventListener("click", (e) => { e.stopPropagation(); b.remove(); open(a.key) })
|
||||
box.append(b)
|
||||
setTimeout(() => b.remove(), 8000)
|
||||
}
|
||||
function trackAlerts() {
|
||||
const next = new Map(state.alerts)
|
||||
// the first snapshot with real sessions is the baseline: sessions that
|
||||
// were already waiting when the page opened are not news
|
||||
const seeded = state.alertsSeeded === true
|
||||
for (const a of state.all) {
|
||||
// sample agents are not news
|
||||
if (String(a.key).startsWith("demo|")) continue
|
||||
next.set(a.key, a.status)
|
||||
const was = state.alerts.get(a.key)
|
||||
if (seeded && (a.status === "waiting" || a.status === "error") && was !== a.status) showToast(a)
|
||||
}
|
||||
state.alerts = next
|
||||
if (state.snap) state.alertsSeeded = true
|
||||
}
|
||||
|
||||
// ---- everything ------------------------------------------------------
|
||||
function refresh() {
|
||||
const now = Date.now()
|
||||
const wasText = state.showText
|
||||
// text off in the page as well as the host: a stale live.js or a host
|
||||
// that has not restarted yet must not render what the switch hid
|
||||
state.showText = view.text && state.snap?.text !== false
|
||||
state.list = M.agents(snapshot(now), now, view)
|
||||
if (!state.showText) state.list = M.redact(state.list)
|
||||
const snap = snapshot(now)
|
||||
// follow the newest real prompt's script while the picker is on Auto
|
||||
// (sample agents are not the user's own prompts and must not pick a UI
|
||||
// language for them)
|
||||
if (manualLang === "auto") {
|
||||
const want = pickLang(M.sample(state.snap))
|
||||
if (want !== lang) { lang = want; words() }
|
||||
}
|
||||
const base = { ...view, progress: true }
|
||||
state.all = M.agents(snap, now, { ...base, agents: [], showSub: true, showIdle: true })
|
||||
state.list = M.agents(snap, now, base)
|
||||
if (!state.showText) {
|
||||
state.list = M.redact(state.list); state.all = M.redact(state.all)
|
||||
if (wasText) $("toasts").replaceChildren()
|
||||
if (!state.open) clearPanelText()
|
||||
}
|
||||
const c = M.counts(state.list)
|
||||
const set = (id, v) => { const n = $(id); if (n.textContent !== String(v)) n.textContent = v }
|
||||
set("nNeed", c.needYou)
|
||||
set("nWork", c.working)
|
||||
set("nDone", c.done)
|
||||
$("counts").classList.toggle("alert", c.needYou > 0)
|
||||
scene.setAgents(state.list)
|
||||
const active = activateScene()
|
||||
active.setAgents(state.list)
|
||||
if (view.mode === "office") active.start()
|
||||
const keys = new Set(state.list.map((a) => a.key))
|
||||
for (const [k, e] of tags) if (!keys.has(k)) { e.remove(); tags.delete(k) }
|
||||
for (const a of state.list) tagFor(a)
|
||||
@@ -400,13 +761,17 @@
|
||||
}
|
||||
$("empty").hidden = state.list.length > 0
|
||||
if (!$("empty").hidden) $("empty").textContent = emptyText()
|
||||
set("note", view.demo ? t().demoOn : "")
|
||||
set("note", view.demo ? t().demoOn : (view.dim === "3d" && state.scene3Failed ? t().webglFallback : ""))
|
||||
const age = state.snap?.written ? now - state.snap.written : 0
|
||||
const live = $("live")
|
||||
live.classList.toggle("stale", !!state.snap && age > 15000)
|
||||
live.title = state.snap ? M.fill(t().stale, M.ago(age, lang)) : ""
|
||||
if (view.mode === "list") rows()
|
||||
rows()
|
||||
brandLegend()
|
||||
renderRail()
|
||||
renderToday()
|
||||
renderAgentFilter()
|
||||
trackAlerts()
|
||||
document.title = c.needYou ? `(${c.needYou}) ${t().title}` : t().title
|
||||
}
|
||||
|
||||
@@ -420,7 +785,9 @@
|
||||
$("stage").hidden = m !== "office"
|
||||
$("listview").hidden = m !== "list"
|
||||
$("dims").classList.toggle("off", m !== "office")
|
||||
if (m === "office") { scene.resize(); scene.start() } else scene.stop()
|
||||
railSig = ""
|
||||
if (m === "office") { const s = activateScene(); s.resize(); s.start() }
|
||||
else { try { scene2.stop() } catch {} ; if (scene3) scene3.stop() }
|
||||
refresh()
|
||||
}
|
||||
|
||||
@@ -431,7 +798,12 @@
|
||||
let saved = JSON.stringify(opts)
|
||||
const textOn = () => $("optText").checked
|
||||
function wanted() {
|
||||
return { ...opts, mode: view.mode, dim: view.dim, demo: view.demo, showDone: view.showDone, hideAfter: view.hideAfter, text: textOn(), cleared: view.cleared }
|
||||
return {
|
||||
...opts, mode: view.mode, dim: view.dim, demo: view.demo, showDone: view.showDone, hideAfter: view.hideAfter,
|
||||
text: textOn(), agents: view.agents.slice(), showSub: view.showSub, showIdle: view.showIdle,
|
||||
side: view.side, sideV: 2, lang: manualLang, scene: view.scene, quality: view.quality,
|
||||
cleared: { ...view.cleared },
|
||||
}
|
||||
}
|
||||
function save() {
|
||||
clearTimeout(saving)
|
||||
@@ -454,26 +826,79 @@
|
||||
if (!d || d === view.dim) return
|
||||
view.dim = d
|
||||
select("dims", "dim", d)
|
||||
scene.setDim(d)
|
||||
const s = activateScene()
|
||||
s.resize()
|
||||
if (view.mode !== "office") setMode("office")
|
||||
refresh()
|
||||
save()
|
||||
})
|
||||
|
||||
// settings
|
||||
// settings and the Today panel share one menu behaviour
|
||||
const menu = $("settings")
|
||||
$("settingsBtn").addEventListener("click", (e) => {
|
||||
e.stopPropagation()
|
||||
menu.hidden = !menu.hidden
|
||||
$("settingsBtn").setAttribute("aria-expanded", String(!menu.hidden))
|
||||
const todayMenu = $("todayMenu")
|
||||
function positionOverlays() {
|
||||
for (const [button, menuId] of [["settingsBtn", "settings"], ["todayBtn", "todayMenu"]]) {
|
||||
const m = $(menuId)
|
||||
if (m.hidden) continue
|
||||
const anchor = $(button).getBoundingClientRect()
|
||||
const width = Math.min(300, innerWidth - 16)
|
||||
const top = Math.min(Math.max(8, anchor.bottom + 6), Math.max(8, innerHeight - 160))
|
||||
Object.assign(m.style, {left: Math.max(8, Math.min(innerWidth-width-8, anchor.right-width)) + "px", top: top + "px", width: width + "px", maxHeight: Math.max(80, innerHeight-top-8) + "px"})
|
||||
}
|
||||
const rect = $("stage").getBoundingClientRect()
|
||||
for (const [id, preferred] of [["pop", 400], ["rail", 256]]) {
|
||||
const node = $(id)
|
||||
if (node.hidden || rect.height <= 0) continue
|
||||
const width = Math.min(preferred, Math.max(0, rect.width-20))
|
||||
Object.assign(node.style, {position: "fixed", right: "auto", left: Math.max(8, rect.right-width-10) + "px", top: Math.max(8, rect.top+10) + "px", width: width + "px", maxHeight: Math.max(80, Math.min(rect.height-20, innerHeight-rect.top-18)) + "px"})
|
||||
}
|
||||
}
|
||||
addEventListener("resize", positionOverlays)
|
||||
function closeMenus(except) {
|
||||
let changed = false
|
||||
for (const [btn, m] of [[$("settingsBtn"), menu], [$("todayBtn"), todayMenu]]) {
|
||||
if (m === except || m.hidden) continue
|
||||
m.hidden = true
|
||||
btn.setAttribute("aria-expanded", "false")
|
||||
changed = true
|
||||
}
|
||||
if (changed) renderRail()
|
||||
}
|
||||
function toggleMenu(btn, m) {
|
||||
const willOpen = m.hidden
|
||||
closeMenus(willOpen ? m : null)
|
||||
m.hidden = !willOpen
|
||||
btn.setAttribute("aria-expanded", String(willOpen))
|
||||
positionOverlays()
|
||||
renderRail()
|
||||
}
|
||||
$("settingsBtn").addEventListener("click", (e) => { e.stopPropagation(); toggleMenu($("settingsBtn"), menu) })
|
||||
$("todayBtn").addEventListener("click", (e) => { e.stopPropagation(); toggleMenu($("todayBtn"), todayMenu) })
|
||||
menu.addEventListener("click", (e) => e.stopPropagation())
|
||||
todayMenu.addEventListener("click", (e) => e.stopPropagation())
|
||||
document.addEventListener("click", (e) => {
|
||||
if (menu.contains(e.target) || todayMenu.contains(e.target)) return
|
||||
if (e.target === $("settingsBtn") || e.target === $("todayBtn")) return
|
||||
closeMenus()
|
||||
})
|
||||
document.addEventListener("click", (e) => { if (!menu.hidden && !menu.contains(e.target) && e.target !== $("settingsBtn")) { menu.hidden = true; $("settingsBtn").setAttribute("aria-expanded", "false") } })
|
||||
$("optDemo").checked = view.demo
|
||||
$("optDone").checked = view.showDone
|
||||
$("optText").checked = opts.text !== false
|
||||
$("optSub").checked = view.showSub
|
||||
$("optIdle").checked = view.showIdle
|
||||
select("optHide", "hide", view.hideAfter)
|
||||
$("optDemo").addEventListener("change", (e) => { view.demo = e.target.checked; state.demoSnap = null; refresh(); save() })
|
||||
$("optDone").addEventListener("change", (e) => { view.showDone = e.target.checked; refresh(); save() })
|
||||
$("optText").addEventListener("change", (e) => { view.text = e.target.checked; refresh(); save() })
|
||||
$("optSub").addEventListener("change", (e) => { view.showSub = e.target.checked; agentFilterSig = ""; refresh(); save() })
|
||||
$("optIdle").addEventListener("change", (e) => { view.showIdle = e.target.checked; agentFilterSig = ""; refresh(); save() })
|
||||
$("optLang").addEventListener("change", (e) => {
|
||||
manualLang = M.LANG_NAMES[e.target.value] ? e.target.value : "auto"
|
||||
lang = pickLang()
|
||||
words()
|
||||
refresh()
|
||||
save()
|
||||
})
|
||||
$("optHide").addEventListener("click", (e) => {
|
||||
const h = e.target.closest("button")?.dataset.hide
|
||||
if (!h) return
|
||||
@@ -483,6 +908,22 @@
|
||||
save()
|
||||
})
|
||||
|
||||
// the rail can be put away; the list view keeps its own groups
|
||||
$("sideBtn").addEventListener("click", (e) => {
|
||||
e.stopPropagation()
|
||||
view.side = !view.side
|
||||
railSig = ""
|
||||
renderRail()
|
||||
save()
|
||||
})
|
||||
$("railClose").addEventListener("click", (e) => {
|
||||
e.stopPropagation()
|
||||
view.side = false
|
||||
railSig = ""
|
||||
renderRail()
|
||||
save()
|
||||
})
|
||||
|
||||
// picture in picture: the office in a window of the page's own (magpie's
|
||||
// frame refuses the browser's own floating window to a sandboxed page).
|
||||
// Its bar moves it, its corner reshapes it, ✕ or Escape puts it back.
|
||||
@@ -497,6 +938,8 @@
|
||||
$("float").style.cssText = ""
|
||||
$("pip").classList.add("on")
|
||||
$("pip").textContent = t().pipOn
|
||||
railSig = ""
|
||||
renderRail()
|
||||
scene.resize()
|
||||
}
|
||||
function closeFloat() {
|
||||
@@ -507,6 +950,8 @@
|
||||
$("float").hidden = true
|
||||
$("pip").classList.remove("on")
|
||||
$("pip").textContent = t().pip
|
||||
railSig = ""
|
||||
renderRail()
|
||||
scene.resize()
|
||||
}
|
||||
$("floatClose").addEventListener("click", closeFloat)
|
||||
@@ -537,10 +982,11 @@
|
||||
new ResizeObserver(() => {
|
||||
if (resizeQueued) return
|
||||
resizeQueued = true
|
||||
requestAnimationFrame(() => { resizeQueued = false; scene.resize() })
|
||||
requestAnimationFrame(() => { resizeQueued = false; scene.resize(); positionOverlays() })
|
||||
}).observe($("stage"))
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Escape") return
|
||||
if (!menu.hidden || !todayMenu.hidden) return closeMenus()
|
||||
if (state.open) return close()
|
||||
if (floatHome) closeFloat()
|
||||
})
|
||||
@@ -548,8 +994,36 @@
|
||||
if (document.hidden) scene.stop()
|
||||
else if (view.mode === "office") scene.start()
|
||||
})
|
||||
magpie.onTheme((th) => { lang = th.lang; words(); refresh() })
|
||||
magpie.onTheme((th) => {
|
||||
themeLang = th.lang
|
||||
const want = pickLang()
|
||||
if (want !== lang) { lang = want; words() }
|
||||
refresh()
|
||||
})
|
||||
|
||||
const SCENE_OPTIONS = [
|
||||
["office", "sceneOffice"], ["station", "sceneStation"], ["cafe", "sceneCafe"],
|
||||
["castle", "sceneCastle"], ["pirate", "scenePirate"], ["graveyard", "sceneGraveyard"],
|
||||
]
|
||||
if ($("optScene")) {
|
||||
$("optScene").replaceChildren(...SCENE_OPTIONS.map(([id, name]) => { const o = el("option", "", t()[name]); o.value = id; return o }))
|
||||
$("optScene").value = view.scene
|
||||
$("optQuality").value = view.quality
|
||||
$("optQuality").addEventListener("change", (e) => {
|
||||
view.quality = e.target.value
|
||||
if (scene3) scene3.setQuality(view.quality)
|
||||
save()
|
||||
})
|
||||
$("optScene").addEventListener("change", (e) => {
|
||||
view.scene = e.target.value
|
||||
// a scene belongs to the real 3D view; choosing one takes you there
|
||||
if (view.dim !== "3d") { view.dim = "3d"; select("dims", "dim", "3d") }
|
||||
if (scene3) scene3.setScene(view.scene)
|
||||
activateScene()
|
||||
refresh()
|
||||
save()
|
||||
})
|
||||
}
|
||||
select("modes", "mode", view.mode)
|
||||
select("dims", "dim", view.dim)
|
||||
words()
|
||||
@@ -558,5 +1032,6 @@
|
||||
// the host writes live.js within a second and a half of a change; the
|
||||
// page looks every second, and "N min ago" moves with its own clock
|
||||
setInterval(load, 1000)
|
||||
setInterval(() => { if (state.open) { const a = state.list.find((x) => x.key === state.open); if (a) fillPanel(a) } }, 5000)
|
||||
// Time-based states must move even when a stalled file never changes.
|
||||
setInterval(() => { if (!document.hidden) refresh() }, 1000)
|
||||
})()
|
||||
|
||||
@@ -4,13 +4,15 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Agent Office</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<link rel="stylesheet" href="style.css?v=284374c66e69">
|
||||
<script src="_magpie/bridge.js"></script>
|
||||
<script src="agents.js"></script>
|
||||
<script src="model.js"></script>
|
||||
<script src="icons.js"></script>
|
||||
<script src="scene.js"></script>
|
||||
<script src="app.js" defer></script>
|
||||
<script src="agents.js?v=d958111cd669"></script>
|
||||
<script src="model.js?v=691ef399f1c8"></script>
|
||||
<script src="icons.js?v=e918b44d46c2"></script>
|
||||
<script src="scene.js?v=b27c2e100f3a"></script>
|
||||
<script src="three.min.js?v=5b5a0ae404b6"></script>
|
||||
<script src="scene3d.js?v=f6a154f817d4"></script>
|
||||
<script src="app.js?v=744effc0b6ea" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<main class="card" id="card">
|
||||
@@ -29,17 +31,46 @@
|
||||
</div>
|
||||
<div class="seg plain" role="tablist" id="dims">
|
||||
<button type="button" role="tab" data-dim="2d">2D</button>
|
||||
<button type="button" role="tab" data-dim="iso">ISO</button>
|
||||
<button type="button" role="tab" data-dim="3d">3D</button>
|
||||
</div>
|
||||
<span class="note" id="note"></span>
|
||||
<span class="grow"></span>
|
||||
<div class="tools">
|
||||
<div class="menu-wrap">
|
||||
<button type="button" class="btn" id="todayBtn" aria-haspopup="true" aria-expanded="false"><span data-t="today">Today</span> <span class="today-tokens" id="todayTokens"></span></button>
|
||||
<div class="menu today-panel" id="todayMenu" hidden></div>
|
||||
</div>
|
||||
<button type="button" class="btn" id="sideBtn" aria-pressed="true"><span data-t="panel">Panel</span></button>
|
||||
<button type="button" class="btn" id="pip" data-t="pip">Picture in picture</button>
|
||||
<div class="menu-wrap">
|
||||
<button type="button" class="btn" id="settingsBtn" aria-haspopup="true" aria-expanded="false"><span data-t="settings">Settings</span> <span class="chev">⌄</span></button>
|
||||
<div class="menu" id="settings" hidden>
|
||||
<div class="menu wide" id="settings" hidden>
|
||||
<label class="row"><input type="checkbox" id="optDemo"> <span data-t="demo">Sample agents</span></label>
|
||||
<label class="row"><input type="checkbox" id="optDone"> <span data-t="showDone">Show finished agents</span></label>
|
||||
<label class="row"><input type="checkbox" id="optText"> <span data-t="showText">Show prompts and replies</span></label>
|
||||
<label class="row"><input type="checkbox" id="optSub"> <span data-t="showSub">Show subagents</span></label>
|
||||
<label class="row"><input type="checkbox" id="optIdle"> <span data-t="showIdle">Show idle agents</span></label>
|
||||
<div class="row col">
|
||||
<span data-t="agents">Agents</span>
|
||||
<div class="agent-filter" id="optAgents"></div>
|
||||
</div>
|
||||
<div class="row col">
|
||||
<span data-t="language">Language</span>
|
||||
<select class="lang-select" id="optLang"></select>
|
||||
</div>
|
||||
<div class="row col">
|
||||
<span data-t="scene">Scene</span>
|
||||
<select class="lang-select" id="optScene"></select>
|
||||
</div>
|
||||
<div class="row col">
|
||||
<span data-t="quality">Quality</span>
|
||||
<select class="lang-select" id="optQuality">
|
||||
<option value="low" data-t="qLow">Low</option>
|
||||
<option value="medium" data-t="qMedium">Medium</option>
|
||||
<option value="high" data-t="qHigh">High</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="row col">
|
||||
<span data-t="hideAfter">Leave the office after</span>
|
||||
<div class="seg small" id="optHide">
|
||||
@@ -51,9 +82,11 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
<section class="stage" id="stage">
|
||||
<canvas id="office"></canvas>
|
||||
<canvas id="office" tabindex="0" aria-label="Agent office"></canvas>
|
||||
<canvas id="office3d" tabindex="0" aria-label="3D Agent office" hidden></canvas>
|
||||
<div class="tags" id="tags"></div>
|
||||
<div class="empty" id="empty" hidden></div>
|
||||
</section>
|
||||
@@ -64,6 +97,10 @@
|
||||
</table>
|
||||
<p class="empty-list" id="emptyList" hidden></p>
|
||||
</section>
|
||||
<aside class="rail" id="rail" hidden>
|
||||
<div class="rail-head"><span data-t="agents">Agents</span> <b id="railCount">0</b><span class="grow"></span><button type="button" class="px" id="railClose" aria-label="Close">✕</button></div>
|
||||
<div class="rail-groups" id="railGroups"></div>
|
||||
</aside>
|
||||
<aside class="pop" id="pop" hidden></aside>
|
||||
<footer>
|
||||
<div class="legend" id="statusLegend"></div>
|
||||
@@ -74,5 +111,6 @@
|
||||
<div class="floatbar" id="floatbar"><span class="fdots" aria-hidden="true"><i></i><i></i></span><span data-t="pip">Picture in picture</span><button type="button" class="fclose" id="floatClose" aria-label="Close">✕</button></div>
|
||||
<div class="floatslot" id="floatslot"></div>
|
||||
</div>
|
||||
<div class="toasts" id="toasts" aria-live="polite"></div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -4,22 +4,28 @@
|
||||
//
|
||||
// A session from an agent's own files says its phase outright (thinking,
|
||||
// tool, approval, ask, done, aborted, error); the page only adds that a
|
||||
// session whose file has not moved for a long while, mid-turn, is stuck.
|
||||
// A session only the gateway saw (an agent whose files aren't read) is
|
||||
// worked out from its requests, as before.
|
||||
// session whose file has not moved for a long while, mid-turn, has made no
|
||||
// progress. A session only the gateway saw (an agent whose files aren't
|
||||
// read) is worked out from its requests, as before.
|
||||
(() => {
|
||||
// ---- words -----------------------------------------------------------
|
||||
// Every language carries exactly the same keys. `zh` is kept as an alias
|
||||
// of zh-CN for older callers and for the tests that came before.
|
||||
const TEXT = {
|
||||
en: {
|
||||
title: "What are my agents doing", needYou: "Need you", working: "Working", doneN: "Done",
|
||||
title: "What are my agents doing", needYou: "Need you", working: "Working", doneN: "Done", finished: "Finished",
|
||||
office: "Office", list: "List", pip: "Picture in picture", settings: "Settings",
|
||||
thinking: "Thinking", executing: "Running tools", replying: "Replying", waiting: "Waiting for you",
|
||||
done: "Done", error: "Error", stopped: "Stopped", idle: "Idle",
|
||||
approval: "Waiting for your approval", ask: "Asked you something", stuck: "No word for {n}",
|
||||
approval: "Waiting for your approval", ask: "Asked you something",
|
||||
stuck: "No progress · {n}", noProgress: "No progress",
|
||||
copyResume: "Copy resume command", copySession: "Copy session id", copied: "Copied",
|
||||
justNow: "just now", sAgo: "{n}s ago", mAgo: "{n} min ago", hAgo: "{n} h ago", dAgo: "{n} d ago",
|
||||
empty: "No agent has been at work in the last two days. Start Claude Code, Codex, DeepSeek Harness, Gemini CLI… and it walks in here.",
|
||||
noFile: "Starting… the plugin reads your agents' sessions in magpie's plugin host.",
|
||||
demo: "Sample agents", showDone: "Show finished agents", showText: "Show prompts and replies",
|
||||
showSub: "Show subagents", showIdle: "Show idle agents", agents: "Agents", allAgents: "All agents",
|
||||
language: "Language", auto: "Auto", scene: "Scene", quality: "Quality",
|
||||
hideAfter: "Leave the office after", h1: "1 hour", h6: "6 hours", h24: "24 hours", never: "Never",
|
||||
demoOn: "Showing sample agents", turns: "{n} turns", noPrompt: "(no prompt)",
|
||||
project: "Folder", model: "Model", status: "Status", task: "Task", last: "Last active", agent: "Agent",
|
||||
@@ -27,19 +33,28 @@
|
||||
floating: "The office has its own window here: move it, reshape it, or ✕ it to put it back",
|
||||
pipOn: "Put it back", ran: "running {n}", via: "seen through magpie's gateway", fromFiles: "from its own session file",
|
||||
live: "live", stale: "Last update {n}",
|
||||
clear: "Clear", clearTip: "Take it out of the office. It comes back when its session moves again.",
|
||||
today: "Today", turnsL: "turns", tokensL: "tokens", agentsL: "agents",
|
||||
topProjects: "Top folders", noUsage: "No usage recorded yet.",
|
||||
summaryNote: "Totals come from the usage records in each agent's own session files.",
|
||||
context: "Context", recent: "Recent conversation", noMessages: "No messages yet.",
|
||||
privateNote: "Text is off, so the conversation is hidden.", loadingMsgs: "Loading…",
|
||||
subAgent: "subagent", panel: "Panel", dismiss: "Dismiss", clear: "Clear", clearTip: "Remove from the office until its session moves",
|
||||
unitS: "s", unitM: "m", unitH: "h",
|
||||
},
|
||||
zh: {
|
||||
title: "我的 Agent 在干嘛", needYou: "需要你", working: "工作中", doneN: "已完成",
|
||||
"zh-CN": {
|
||||
title: "我的 Agent 在干嘛", needYou: "需要你", working: "工作中", doneN: "已完成", finished: "已结束",
|
||||
office: "办公室", list: "列表", pip: "画中画", settings: "设置",
|
||||
thinking: "思考中", executing: "执行中", replying: "回复中", waiting: "等你回应",
|
||||
done: "已完成", error: "错误", stopped: "已中断", idle: "摸鱼中",
|
||||
approval: "等你批准", ask: "在问你问题", stuck: "已 {n} 没有动静",
|
||||
approval: "等你批准", ask: "在问你问题",
|
||||
stuck: "已 {n} 没有进展", noProgress: "没有进展",
|
||||
copyResume: "复制续接命令", copySession: "复制会话 ID", copied: "已复制",
|
||||
justNow: "刚刚", sAgo: "{n}秒前", mAgo: "{n}分钟前", hAgo: "{n}小时前", dAgo: "{n}天前",
|
||||
empty: "最近两天没有 Agent 在干活。打开 Claude Code、Codex、DeepSeek Harness、Gemini CLI……它就会走进这间办公室。",
|
||||
noFile: "正在启动……插件在 magpie 的插件宿主里读取各个 Agent 的会话。",
|
||||
demo: "示例 Agent", showDone: "显示已完成的 Agent", showText: "显示提问和回复",
|
||||
showSub: "显示子 Agent", showIdle: "显示摸鱼 Agent", agents: "Agent", allAgents: "全部 Agent",
|
||||
language: "语言", auto: "自动", scene: "场景", quality: "画质",
|
||||
hideAfter: "多久后离开办公室", h1: "1 小时", h6: "6 小时", h24: "24 小时", never: "从不",
|
||||
demoOn: "正在显示示例 Agent", turns: "{n} 轮", noPrompt: "(没有提问)",
|
||||
project: "目录", model: "模型", status: "状态", task: "任务", last: "最近活动", agent: "Agent",
|
||||
@@ -47,22 +62,472 @@
|
||||
floating: "办公室在这里的小窗中:可拖动、可缩放,点 ✕ 放回去",
|
||||
pipOn: "放回去", ran: "已运行 {n}", via: "经 magpie 网关看到", fromFiles: "来自它自己的会话文件",
|
||||
live: "实时", stale: "最近更新 {n}",
|
||||
clear: "清除", clearTip: "把它移出办公室;会话再有动静时会回来。",
|
||||
today: "今日", turnsL: "轮", tokensL: "tokens", agentsL: "个 Agent",
|
||||
topProjects: "热门目录", noUsage: "还没有用量记录。",
|
||||
summaryNote: "统计来自各个 Agent 自己会话文件里的用量记录。",
|
||||
context: "上下文", recent: "最近对话", noMessages: "还没有消息。",
|
||||
privateNote: "已关闭文本,对话已隐藏。", loadingMsgs: "加载中……",
|
||||
subAgent: "子 Agent", panel: "侧栏", dismiss: "关闭", clear: "清除", clearTip: "从办公室移除,直到会话有新动静",
|
||||
unitS: "秒", unitM: "分", unitH: "小时",
|
||||
},
|
||||
"zh-TW": {
|
||||
title: "我的 Agent 在幹嘛", needYou: "需要你", working: "工作中", doneN: "已完成", finished: "已結束",
|
||||
office: "辦公室", list: "列表", pip: "子母畫面", settings: "設定",
|
||||
thinking: "思考中", executing: "執行中", replying: "回覆中", waiting: "等你回應",
|
||||
done: "已完成", error: "錯誤", stopped: "已中斷", idle: "摸魚中",
|
||||
approval: "等你批准", ask: "在問你問題",
|
||||
stuck: "已 {n} 沒有進展", noProgress: "沒有進展",
|
||||
copyResume: "複製續接指令", copySession: "複製工作階段 ID", copied: "已複製",
|
||||
justNow: "剛剛", sAgo: "{n}秒前", mAgo: "{n}分鐘前", hAgo: "{n}小時前", dAgo: "{n}天前",
|
||||
empty: "最近兩天沒有 Agent 在幹活。打開 Claude Code、Codex、DeepSeek Harness、Gemini CLI……它就會走進這間辦公室。",
|
||||
noFile: "正在啟動……外掛在 magpie 的外掛宿主裡讀取各個 Agent 的工作階段。",
|
||||
demo: "範例 Agent", showDone: "顯示已完成的 Agent", showText: "顯示提問和回覆",
|
||||
showSub: "顯示子 Agent", showIdle: "顯示摸魚 Agent", agents: "Agent", allAgents: "全部 Agent",
|
||||
language: "語言", auto: "自動", scene: "場景", quality: "畫質",
|
||||
hideAfter: "多久後離開辦公室", h1: "1 小時", h6: "6 小時", h24: "24 小時", never: "從不",
|
||||
demoOn: "正在顯示範例 Agent", turns: "{n} 輪", noPrompt: "(沒有提問)",
|
||||
project: "目錄", model: "模型", status: "狀態", task: "任務", last: "最近活動", agent: "Agent",
|
||||
quiet: "已關閉文字:只記錄狀態",
|
||||
floating: "辦公室在這裡的小視窗中:可拖動、可縮放,點 ✕ 放回去",
|
||||
pipOn: "放回去", ran: "已執行 {n}", via: "經 magpie 閘道看到", fromFiles: "來自它自己的工作階段檔案",
|
||||
live: "即時", stale: "最近更新 {n}",
|
||||
today: "今日", turnsL: "輪", tokensL: "tokens", agentsL: "個 Agent",
|
||||
topProjects: "熱門目錄", noUsage: "還沒有用量記錄。",
|
||||
summaryNote: "統計來自各個 Agent 自己工作階段檔案裡的用量記錄。",
|
||||
context: "上下文", recent: "最近對話", noMessages: "還沒有訊息。",
|
||||
privateNote: "已關閉文字,對話已隱藏。", loadingMsgs: "載入中……",
|
||||
subAgent: "子 Agent", panel: "側欄", dismiss: "關閉", clear: "清除", clearTip: "從辦公室移除,直到工作階段有新動靜",
|
||||
unitS: "秒", unitM: "分", unitH: "小時",
|
||||
},
|
||||
ja: {
|
||||
title: "エージェントは何してる?", needYou: "要対応", working: "作業中", doneN: "完了", finished: "終了",
|
||||
office: "オフィス", list: "リスト", pip: "ピクチャーインピクチャー", settings: "設定",
|
||||
thinking: "考え中", executing: "ツール実行中", replying: "返信中", waiting: "あなた待ち",
|
||||
done: "完了", error: "エラー", stopped: "中断", idle: "待機中",
|
||||
approval: "承認待ち", ask: "質問があります",
|
||||
stuck: "{n} 進展なし", noProgress: "進展なし",
|
||||
copyResume: "再開コマンドをコピー", copySession: "セッション ID をコピー", copied: "コピーしました",
|
||||
justNow: "たった今", sAgo: "{n}秒前", mAgo: "{n}分前", hAgo: "{n}時間前", dAgo: "{n}日前",
|
||||
empty: "この2日間、エージェントは動いていません。Claude Code、Codex、DeepSeek Harness、Gemini CLI… を起動すると、ここに現れます。",
|
||||
noFile: "起動中… プラグインが magpie のプラグインホストで各エージェントのセッションを読んでいます。",
|
||||
demo: "サンプルエージェント", showDone: "終了したエージェントを表示", showText: "プロンプトと返信を表示",
|
||||
showSub: "サブエージェントを表示", showIdle: "待機中のエージェントを表示", agents: "エージェント", allAgents: "すべてのエージェント",
|
||||
language: "言語", auto: "自動", scene: "シーン", quality: "画質",
|
||||
hideAfter: "オフィスを離れるまで", h1: "1 時間", h6: "6 時間", h24: "24 時間", never: "なし",
|
||||
demoOn: "サンプルエージェントを表示中", turns: "{n} ターン", noPrompt: "(プロンプトなし)",
|
||||
project: "フォルダ", model: "モデル", status: "状態", task: "タスク", last: "最終活動", agent: "エージェント",
|
||||
quiet: "テキストオフ:状態のみ保持",
|
||||
floating: "オフィスはこの小窓にあります。移動・リサイズでき、✕ で戻せます",
|
||||
pipOn: "戻す", ran: "実行中 {n}", via: "magpie のゲートウェイ経由", fromFiles: "自身のセッションファイルから",
|
||||
live: "ライブ", stale: "最終更新 {n}",
|
||||
today: "今日", turnsL: "ターン", tokensL: "トークン", agentsL: "エージェント",
|
||||
topProjects: "上位フォルダ", noUsage: "まだ使用量の記録がありません。",
|
||||
summaryNote: "合計は各エージェントのセッションファイルの使用量記録から算出します。",
|
||||
context: "コンテキスト", recent: "最近の会話", noMessages: "まだメッセージはありません。",
|
||||
privateNote: "テキストオフのため、会話は非表示です。", loadingMsgs: "読み込み中…",
|
||||
subAgent: "サブエージェント", panel: "パネル", dismiss: "閉じる", clear: "消去", clearTip: "セッションが動くまでオフィスから消す",
|
||||
unitS: "秒", unitM: "分", unitH: "時間",
|
||||
},
|
||||
ko: {
|
||||
title: "내 에이전트는 뭐 하는 중?", needYou: "확인 필요", working: "작업 중", doneN: "완료", finished: "종료",
|
||||
office: "사무실", list: "목록", pip: "화면 속 화면", settings: "설정",
|
||||
thinking: "생각 중", executing: "도구 실행 중", replying: "답변 작성 중", waiting: "응답 대기",
|
||||
done: "완료", error: "오류", stopped: "중단됨", idle: "대기",
|
||||
approval: "승인 대기 중", ask: "질문이 있습니다",
|
||||
stuck: "{n} 동안 진행 없음", noProgress: "진행 없음",
|
||||
copyResume: "이어하기 명령 복사", copySession: "세션 ID 복사", copied: "복사됨",
|
||||
justNow: "방금", sAgo: "{n}초 전", mAgo: "{n}분 전", hAgo: "{n}시간 전", dAgo: "{n}일 전",
|
||||
empty: "지난 이틀 동안 에이전트가 작업하지 않았습니다. Claude Code, Codex, DeepSeek Harness, Gemini CLI…를 실행하면 여기로 들어옵니다.",
|
||||
noFile: "시작 중… 플러그인이 magpie의 플러그인 호스트에서 에이전트 세션을 읽고 있습니다.",
|
||||
demo: "샘플 에이전트", showDone: "완료된 에이전트 표시", showText: "프롬프트와 답변 표시",
|
||||
showSub: "하위 에이전트 표시", showIdle: "대기 중인 에이전트 표시", agents: "에이전트", allAgents: "모든 에이전트",
|
||||
language: "언어", auto: "자동", scene: "장면", quality: "품질",
|
||||
hideAfter: "사무실을 떠나기까지", h1: "1시간", h6: "6시간", h24: "24시간", never: "안 함",
|
||||
demoOn: "샘플 에이전트 표시 중", turns: "{n} 턴", noPrompt: "(프롬프트 없음)",
|
||||
project: "폴더", model: "모델", status: "상태", task: "작업", last: "최근 활동", agent: "에이전트",
|
||||
quiet: "텍스트 꺼짐: 상태만 유지",
|
||||
floating: "사무실이 이 작은 창에 있습니다. 이동·크기 조절하거나 ✕로 되돌리세요",
|
||||
pipOn: "되돌리기", ran: "실행 중 {n}", via: "magpie 게이트웨이로 확인", fromFiles: "자체 세션 파일에서",
|
||||
live: "실시간", stale: "마지막 업데이트 {n}",
|
||||
today: "오늘", turnsL: "턴", tokensL: "토큰", agentsL: "에이전트",
|
||||
topProjects: "상위 폴더", noUsage: "아직 사용량 기록이 없습니다.",
|
||||
summaryNote: "합계는 각 에이전트 세션 파일의 사용량 기록에서 계산합니다.",
|
||||
context: "컨텍스트", recent: "최근 대화", noMessages: "아직 메시지가 없습니다.",
|
||||
privateNote: "텍스트가 꺼져 있어 대화가 숨겨집니다.", loadingMsgs: "불러오는 중…",
|
||||
subAgent: "하위 에이전트", panel: "패널", dismiss: "닫기", clear: "지우기", clearTip: "세션이 움직일 때까지 사무실에서 숨기기",
|
||||
unitS: "초", unitM: "분", unitH: "시간",
|
||||
},
|
||||
es: {
|
||||
title: "¿Qué hacen mis agentes?", needYou: "Te necesitan", working: "Trabajando", doneN: "Hecho", finished: "Terminados",
|
||||
office: "Oficina", list: "Lista", pip: "Imagen en imagen", settings: "Ajustes",
|
||||
thinking: "Pensando", executing: "Ejecutando herramientas", replying: "Respondiendo", waiting: "Esperándote",
|
||||
done: "Hecho", error: "Error", stopped: "Detenido", idle: "Inactivo",
|
||||
approval: "Esperando tu aprobación", ask: "Te ha preguntado algo",
|
||||
stuck: "Sin progreso desde hace {n}", noProgress: "Sin progreso",
|
||||
copyResume: "Copiar comando de reanudación", copySession: "Copiar id de sesión", copied: "Copiado",
|
||||
justNow: "ahora mismo", sAgo: "hace {n} s", mAgo: "hace {n} min", hAgo: "hace {n} h", dAgo: "hace {n} d",
|
||||
empty: "Ningún agente ha trabajado en los últimos dos días. Abre Claude Code, Codex, DeepSeek Harness, Gemini CLI… y entrará aquí.",
|
||||
noFile: "Iniciando… el plugin lee las sesiones de tus agentes en el host de plugins de magpie.",
|
||||
demo: "Agentes de ejemplo", showDone: "Mostrar agentes terminados", showText: "Mostrar preguntas y respuestas",
|
||||
showSub: "Mostrar subagentes", showIdle: "Mostrar agentes inactivos", agents: "Agentes", allAgents: "Todos los agentes",
|
||||
language: "Idioma", auto: "Auto", scene: "Escena", quality: "Calidad",
|
||||
hideAfter: "Salir de la oficina tras", h1: "1 hora", h6: "6 horas", h24: "24 horas", never: "Nunca",
|
||||
demoOn: "Mostrando agentes de ejemplo", turns: "{n} turnos", noPrompt: "(sin pregunta)",
|
||||
project: "Carpeta", model: "Modelo", status: "Estado", task: "Tarea", last: "Última actividad", agent: "Agente",
|
||||
quiet: "Texto desactivado: solo se guardan los estados",
|
||||
floating: "La oficina tiene su propia ventana: muévela, redimensiónala o pulsa ✕ para devolverla",
|
||||
pipOn: "Devolver", ran: "en marcha {n}", via: "visto por la pasarela de magpie", fromFiles: "desde su propio archivo de sesión",
|
||||
live: "en vivo", stale: "Última actualización {n}",
|
||||
today: "Hoy", turnsL: "turnos", tokensL: "tokens", agentsL: "agentes",
|
||||
topProjects: "Carpetas principales", noUsage: "Aún no hay uso registrado.",
|
||||
summaryNote: "Los totales vienen de los registros de uso de las sesiones de cada agente.",
|
||||
context: "Contexto", recent: "Conversación reciente", noMessages: "Aún no hay mensajes.",
|
||||
privateNote: "El texto está desactivado, así que la conversación está oculta.", loadingMsgs: "Cargando…",
|
||||
subAgent: "subagente", panel: "Panel", dismiss: "Cerrar", clear: "Quitar", clearTip: "Quitarlo de la oficina hasta que la sesión se mueva",
|
||||
unitS: "s", unitM: "min", unitH: "h",
|
||||
},
|
||||
fr: {
|
||||
title: "Que font mes agents ?", needYou: "Besoin de vous", working: "Au travail", doneN: "Terminé", finished: "Terminés",
|
||||
office: "Bureau", list: "Liste", pip: "Image dans l'image", settings: "Réglages",
|
||||
thinking: "Réfléchit", executing: "Exécute des outils", replying: "Rédige", waiting: "Vous attend",
|
||||
done: "Terminé", error: "Erreur", stopped: "Arrêté", idle: "Inactif",
|
||||
approval: "En attente de votre accord", ask: "Vous a posé une question",
|
||||
stuck: "Aucun progrès depuis {n}", noProgress: "Aucun progrès",
|
||||
copyResume: "Copier la commande de reprise", copySession: "Copier l'id de session", copied: "Copié",
|
||||
justNow: "à l'instant", sAgo: "il y a {n} s", mAgo: "il y a {n} min", hAgo: "il y a {n} h", dAgo: "il y a {n} j",
|
||||
empty: "Aucun agent n'a travaillé ces deux derniers jours. Lancez Claude Code, Codex, DeepSeek Harness, Gemini CLI… et il entrera ici.",
|
||||
noFile: "Démarrage… le plugin lit les sessions de vos agents dans l'hôte de plugins de magpie.",
|
||||
demo: "Agents d'exemple", showDone: "Afficher les agents terminés", showText: "Afficher les questions et réponses",
|
||||
showSub: "Afficher les sous-agents", showIdle: "Afficher les agents inactifs", agents: "Agents", allAgents: "Tous les agents",
|
||||
language: "Langue", auto: "Auto", scene: "Scène", quality: "Qualité",
|
||||
hideAfter: "Quitter le bureau après", h1: "1 heure", h6: "6 heures", h24: "24 heures", never: "Jamais",
|
||||
demoOn: "Affichage des agents d'exemple", turns: "{n} tours", noPrompt: "(aucune question)",
|
||||
project: "Dossier", model: "Modèle", status: "Statut", task: "Tâche", last: "Dernière activité", agent: "Agent",
|
||||
quiet: "Texte désactivé : seuls les statuts sont gardés",
|
||||
floating: "Le bureau a sa propre fenêtre : déplacez-la, redimensionnez-la ou cliquez sur ✕ pour la remettre",
|
||||
pipOn: "Remettre", ran: "en cours {n}", via: "vu via la passerelle magpie", fromFiles: "depuis son propre fichier de session",
|
||||
live: "en direct", stale: "Dernière mise à jour {n}",
|
||||
today: "Aujourd'hui", turnsL: "tours", tokensL: "jetons", agentsL: "agents",
|
||||
topProjects: "Dossiers principaux", noUsage: "Aucune utilisation enregistrée pour l'instant.",
|
||||
summaryNote: "Les totaux viennent des relevés d'usage des fichiers de session de chaque agent.",
|
||||
context: "Contexte", recent: "Conversation récente", noMessages: "Pas encore de messages.",
|
||||
privateNote: "Le texte est désactivé, la conversation est masquée.", loadingMsgs: "Chargement…",
|
||||
subAgent: "sous-agent", panel: "Panneau", dismiss: "Fermer", clear: "Retirer", clearTip: "Retirer du bureau jusqu'au prochain mouvement de la session",
|
||||
unitS: "s", unitM: "min", unitH: "h",
|
||||
},
|
||||
de: {
|
||||
title: "Was machen meine Agents?", needYou: "Braucht dich", working: "Arbeitet", doneN: "Fertig", finished: "Beendet",
|
||||
office: "Büro", list: "Liste", pip: "Bild im Bild", settings: "Einstellungen",
|
||||
thinking: "Denkt nach", executing: "Führt Tools aus", replying: "Schreibt Antwort", waiting: "Wartet auf dich",
|
||||
done: "Fertig", error: "Fehler", stopped: "Angehalten", idle: "Inaktiv",
|
||||
approval: "Wartet auf deine Freigabe", ask: "Hat dich etwas gefragt",
|
||||
stuck: "Seit {n} kein Fortschritt", noProgress: "Kein Fortschritt",
|
||||
copyResume: "Fortsetzen-Befehl kopieren", copySession: "Sitzungs-ID kopieren", copied: "Kopiert",
|
||||
justNow: "gerade eben", sAgo: "vor {n} s", mAgo: "vor {n} min", hAgo: "vor {n} h", dAgo: "vor {n} T",
|
||||
empty: "In den letzten zwei Tagen war kein Agent tätig. Starte Claude Code, Codex, DeepSeek Harness, Gemini CLI… und er kommt herein.",
|
||||
noFile: "Startet… das Plugin liest die Sitzungen deiner Agenten im magpie-Plugin-Host.",
|
||||
demo: "Beispiel-Agenten", showDone: "Beendete Agenten zeigen", showText: "Fragen und Antworten zeigen",
|
||||
showSub: "Subagenten zeigen", showIdle: "Inaktive Agenten zeigen", agents: "Agents", allAgents: "Alle Agents",
|
||||
language: "Sprache", auto: "Auto", scene: "Szene", quality: "Qualität",
|
||||
hideAfter: "Büro verlassen nach", h1: "1 Stunde", h6: "6 Stunden", h24: "24 Stunden", never: "Nie",
|
||||
demoOn: "Beispiel-Agenten werden gezeigt", turns: "{n} Runden", noPrompt: "(keine Frage)",
|
||||
project: "Ordner", model: "Modell", status: "Status", task: "Aufgabe", last: "Zuletzt aktiv", agent: "Agent",
|
||||
quiet: "Text aus: nur Status werden behalten",
|
||||
floating: "Das Büro hat hier sein eigenes Fenster: verschieben, skalieren oder mit ✕ zurückholen",
|
||||
pipOn: "Zurückholen", ran: "läuft {n}", via: "über magpies Gateway gesehen", fromFiles: "aus seiner eigenen Sitzungsdatei",
|
||||
live: "live", stale: "Letzte Aktualisierung {n}",
|
||||
today: "Heute", turnsL: "Runden", tokensL: "Tokens", agentsL: "Agents",
|
||||
topProjects: "Top-Ordner", noUsage: "Noch keine Nutzung erfasst.",
|
||||
summaryNote: "Die Summen stammen aus den Nutzungsdaten der Sitzungsdateien der Agenten.",
|
||||
context: "Kontext", recent: "Letzte Unterhaltung", noMessages: "Noch keine Nachrichten.",
|
||||
privateNote: "Text ist aus, daher ist die Unterhaltung verborgen.", loadingMsgs: "Lädt…",
|
||||
subAgent: "Subagent", panel: "Seitenleiste", dismiss: "Schließen", clear: "Entfernen", clearTip: "Aus dem Büro entfernen, bis sich die Sitzung bewegt",
|
||||
unitS: "s", unitM: "min", unitH: "Std",
|
||||
},
|
||||
pt: {
|
||||
title: "O que meus agentes estão fazendo?", needYou: "Precisam de você", working: "Trabalhando", doneN: "Concluído", finished: "Concluídos",
|
||||
office: "Escritório", list: "Lista", pip: "Imagem em imagem", settings: "Configurações",
|
||||
thinking: "Pensando", executing: "Executando ferramentas", replying: "Escrevendo", waiting: "Esperando você",
|
||||
done: "Concluído", error: "Erro", stopped: "Parado", idle: "Ocioso",
|
||||
approval: "Aguardando sua aprovação", ask: "Perguntou algo a você",
|
||||
stuck: "Sem progresso há {n}", noProgress: "Sem progresso",
|
||||
copyResume: "Copiar comando de retomar", copySession: "Copiar id da sessão", copied: "Copiado",
|
||||
justNow: "agora mesmo", sAgo: "há {n} s", mAgo: "há {n} min", hAgo: "há {n} h", dAgo: "há {n} d",
|
||||
empty: "Nenhum agente trabalhou nos últimos dois dias. Abra Claude Code, Codex, DeepSeek Harness, Gemini CLI… e ele entra aqui.",
|
||||
noFile: "Iniciando… o plugin lê as sessões dos seus agentes no host de plugins do magpie.",
|
||||
demo: "Agentes de exemplo", showDone: "Mostrar agentes finalizados", showText: "Mostrar perguntas e respostas",
|
||||
showSub: "Mostrar subagentes", showIdle: "Mostrar agentes ociosos", agents: "Agentes", allAgents: "Todos os agentes",
|
||||
language: "Idioma", auto: "Auto", scene: "Cenário", quality: "Qualidade",
|
||||
hideAfter: "Sair do escritório após", h1: "1 hora", h6: "6 horas", h24: "24 horas", never: "Nunca",
|
||||
demoOn: "Mostrando agentes de exemplo", turns: "{n} turnos", noPrompt: "(sem pergunta)",
|
||||
project: "Pasta", model: "Modelo", status: "Status", task: "Tarefa", last: "Última atividade", agent: "Agente",
|
||||
quiet: "Texto desativado: só os status são mantidos",
|
||||
floating: "O escritório tem a própria janela aqui: mova, redimensione ou ✕ para devolver",
|
||||
pipOn: "Devolver", ran: "rodando {n}", via: "visto pelo gateway do magpie", fromFiles: "do próprio arquivo de sessão",
|
||||
live: "ao vivo", stale: "Última atualização {n}",
|
||||
today: "Hoje", turnsL: "turnos", tokensL: "tokens", agentsL: "agentes",
|
||||
topProjects: "Pastas principais", noUsage: "Ainda sem uso registrado.",
|
||||
summaryNote: "Os totais vêm dos registros de uso das sessões de cada agente.",
|
||||
context: "Contexto", recent: "Conversa recente", noMessages: "Ainda não há mensagens.",
|
||||
privateNote: "O texto está desativado, então a conversa fica oculta.", loadingMsgs: "Carregando…",
|
||||
subAgent: "subagente", panel: "Painel", dismiss: "Fechar", clear: "Remover", clearTip: "Remover do escritório até a sessão se mover",
|
||||
unitS: "s", unitM: "min", unitH: "h",
|
||||
},
|
||||
}
|
||||
const EXTRA_TEXT = {
|
||||
"en": [
|
||||
"Office",
|
||||
"Space station",
|
||||
"Café",
|
||||
"Castle",
|
||||
"Pirate cove",
|
||||
"Haunted hollow",
|
||||
"Low",
|
||||
"Medium",
|
||||
"High",
|
||||
"WebGL unavailable · ISO view",
|
||||
"You",
|
||||
"READING",
|
||||
"ARCADE",
|
||||
"HUDDLE",
|
||||
"PING-PONG",
|
||||
"COFFEE",
|
||||
"ORBITAL STATION 7"
|
||||
],
|
||||
"zh-CN": [
|
||||
"办公室",
|
||||
"空间站",
|
||||
"咖啡店",
|
||||
"城堡",
|
||||
"海盗湾",
|
||||
"幽灵谷",
|
||||
"低",
|
||||
"中",
|
||||
"高",
|
||||
"WebGL 不可用 · 已切换等距视图",
|
||||
"你",
|
||||
"阅读",
|
||||
"街机",
|
||||
"讨论",
|
||||
"乒乓球",
|
||||
"咖啡",
|
||||
"轨道空间站 7"
|
||||
],
|
||||
"zh-TW": [
|
||||
"辦公室",
|
||||
"太空站",
|
||||
"咖啡店",
|
||||
"城堡",
|
||||
"海盜灣",
|
||||
"幽靈谷",
|
||||
"低",
|
||||
"中",
|
||||
"高",
|
||||
"WebGL 無法使用 · 已切換等距視圖",
|
||||
"你",
|
||||
"閱讀",
|
||||
"街機",
|
||||
"討論",
|
||||
"乒乓球",
|
||||
"咖啡",
|
||||
"軌道太空站 7"
|
||||
],
|
||||
"ja": [
|
||||
"オフィス",
|
||||
"宇宙ステーション",
|
||||
"カフェ",
|
||||
"城",
|
||||
"海賊の入り江",
|
||||
"幽霊の谷",
|
||||
"低",
|
||||
"中",
|
||||
"高",
|
||||
"WebGL が利用できません · 等角表示",
|
||||
"あなた",
|
||||
"読書",
|
||||
"ゲーム",
|
||||
"相談",
|
||||
"卓球",
|
||||
"コーヒー",
|
||||
"軌道ステーション 7"
|
||||
],
|
||||
"ko": [
|
||||
"사무실",
|
||||
"우주 정거장",
|
||||
"카페",
|
||||
"성",
|
||||
"해적 만",
|
||||
"유령 골짜기",
|
||||
"낮음",
|
||||
"중간",
|
||||
"높음",
|
||||
"WebGL 사용 불가 · 등각 보기",
|
||||
"나",
|
||||
"독서",
|
||||
"게임",
|
||||
"회의",
|
||||
"탁구",
|
||||
"커피",
|
||||
"궤도 정거장 7"
|
||||
],
|
||||
"es": [
|
||||
"Oficina",
|
||||
"Estación espacial",
|
||||
"Cafetería",
|
||||
"Castillo",
|
||||
"Bahía pirata",
|
||||
"Valle encantado",
|
||||
"Baja",
|
||||
"Media",
|
||||
"Alta",
|
||||
"WebGL no disponible · Vista ISO",
|
||||
"Tú",
|
||||
"LECTURA",
|
||||
"JUEGOS",
|
||||
"REUNIÓN",
|
||||
"PING-PONG",
|
||||
"CAFÉ",
|
||||
"ESTACIÓN ORBITAL 7"
|
||||
],
|
||||
"fr": [
|
||||
"Bureau",
|
||||
"Station spatiale",
|
||||
"Café",
|
||||
"Château",
|
||||
"Baie pirate",
|
||||
"Vallée hantée",
|
||||
"Basse",
|
||||
"Moyenne",
|
||||
"Haute",
|
||||
"WebGL indisponible · Vue ISO",
|
||||
"Vous",
|
||||
"LECTURE",
|
||||
"ARCADE",
|
||||
"RÉUNION",
|
||||
"PING-PONG",
|
||||
"CAFÉ",
|
||||
"STATION ORBITALE 7"
|
||||
],
|
||||
"de": [
|
||||
"Büro",
|
||||
"Raumstation",
|
||||
"Café",
|
||||
"Burg",
|
||||
"Piratenbucht",
|
||||
"Geistertal",
|
||||
"Niedrig",
|
||||
"Mittel",
|
||||
"Hoch",
|
||||
"WebGL nicht verfügbar · ISO-Ansicht",
|
||||
"Du",
|
||||
"LESEN",
|
||||
"SPIELE",
|
||||
"TREFFEN",
|
||||
"TISCHTENNIS",
|
||||
"KAFFEE",
|
||||
"ORBITALSTATION 7"
|
||||
],
|
||||
"pt": [
|
||||
"Escritório",
|
||||
"Estação espacial",
|
||||
"Café",
|
||||
"Castelo",
|
||||
"Baía pirata",
|
||||
"Vale assombrado",
|
||||
"Baixa",
|
||||
"Média",
|
||||
"Alta",
|
||||
"WebGL indisponível · Vista ISO",
|
||||
"Você",
|
||||
"LEITURA",
|
||||
"JOGOS",
|
||||
"REUNIÃO",
|
||||
"PINGUE-PONGUE",
|
||||
"CAFÉ",
|
||||
"ESTAÇÃO ORBITAL 7"
|
||||
]
|
||||
}
|
||||
const EXTRA_KEYS = ["sceneOffice", "sceneStation", "sceneCafe", "sceneCastle", "scenePirate", "sceneGraveyard", "qLow", "qMedium", "qHigh", "webglFallback", "you", "venueReading", "venueArcade", "venueMeeting", "venuePingpong", "venueCoffee", "stationSign"]
|
||||
for (const [code, values] of Object.entries(EXTRA_TEXT)) EXTRA_KEYS.forEach((key, i) => { TEXT[code][key] = values[i] })
|
||||
const LANGS = ["en", "zh-CN", "zh-TW", "ja", "ko", "es", "fr", "de", "pt"]
|
||||
const LANG_NAMES = {
|
||||
en: "English", "zh-CN": "简体中文", "zh-TW": "繁體中文", ja: "日本語", ko: "한국어",
|
||||
es: "Español", fr: "Français", de: "Deutsch", pt: "Português",
|
||||
}
|
||||
Object.defineProperty(TEXT, "zh", { value: TEXT["zh-CN"], enumerable: false })
|
||||
// the six the page draws, in the legend's order
|
||||
const STATUSES = ["thinking", "executing", "replying", "waiting", "done", "error"]
|
||||
const COLORS = { thinking: "#8b6cf6", executing: "#3b82f6", replying: "#10b981", waiting: "#f59e0b", done: "#22a35a", error: "#ef4444", idle: "#9ca3af" }
|
||||
const HIDE = { "1h": 3600e3, "6h": 6 * 3600e3, "24h": 24 * 3600e3, never: Infinity }
|
||||
const DEFAULTS = { mode: "office", dim: "3d", demo: false, showDone: true, hideAfter: "6h", approvalAfterSec: 90 }
|
||||
// a turn whose file hasn't moved this long is stuck, not working
|
||||
const DEFAULTS = {
|
||||
mode: "office", dim: "3d", scene: "office", quality: "medium", demo: false, showDone: true,
|
||||
hideAfter: "6h", approvalAfterSec: 90, agents: [], showSub: true, showIdle: true, side: false,
|
||||
lang: "auto", progress: true, text: true, cleared: {},
|
||||
}
|
||||
// a turn whose file hasn't moved this long has made no progress
|
||||
const NOPROGRESS_MS = 8 * 60e3
|
||||
const STUCK_MS = 10 * 60e3
|
||||
// a finished session nobody has touched for this long is idling about
|
||||
const IDLE_MS = 20 * 60e3
|
||||
|
||||
// Map a locale like "zh-HK", "pt-BR" or "en-US" to one we have.
|
||||
function normalizeLang(code) {
|
||||
const s = String(code || "").toLowerCase()
|
||||
if (!s) return ""
|
||||
if (s === "zh" || s.startsWith("zh-hans") || /^zh-(cn|sg|my)/.test(s)) return "zh-CN"
|
||||
if (s.startsWith("zh")) return "zh-TW"
|
||||
const base = s.split("-")[0]
|
||||
return LANGS.includes(base) ? base : ""
|
||||
}
|
||||
function text(lang) {
|
||||
return String(lang || "").toLowerCase().startsWith("zh") ? TEXT.zh : TEXT.en
|
||||
return TEXT[normalizeLang(lang)] || TEXT.en
|
||||
}
|
||||
function fill(s, n) { return String(s).replace("{n}", n) }
|
||||
|
||||
// The language of a prompt, for CJK scripts only: Latin prompts say
|
||||
// nothing about which UI language to use.
|
||||
const TRADITIONAL = /[這個們說時間對麼為與動檔設開關點錯誤務資讀寫頁於後裡嗎沒還進來]/
|
||||
function scriptLang(sample) {
|
||||
const s = String(sample || "")
|
||||
let han = 0, kana = 0, hangul = 0
|
||||
for (const ch of s) {
|
||||
const c = ch.codePointAt(0)
|
||||
if ((c >= 0x3040 && c <= 0x30ff) || (c >= 0x31f0 && c <= 0x31ff)) kana++
|
||||
else if (c >= 0x4e00 && c <= 0x9fff) han++
|
||||
else if ((c >= 0xac00 && c <= 0xd7af) || (c >= 0x1100 && c <= 0x11ff) || (c >= 0x3130 && c <= 0x318f)) hangul++
|
||||
}
|
||||
if (kana) return "ja"
|
||||
if (hangul) return "ko"
|
||||
if (han) return TRADITIONAL.test(s) ? "zh-TW" : "zh-CN"
|
||||
return ""
|
||||
}
|
||||
// Manual pick, then the prompt's script, then magpie's UI theme, then the
|
||||
// browser, then English.
|
||||
function detectLang(o = {}) {
|
||||
const manual = normalizeLang(o.manual)
|
||||
if (manual) return manual
|
||||
const script = scriptLang(o.sample)
|
||||
if (script) return script
|
||||
const theme = normalizeLang(o.theme)
|
||||
if (theme) return theme
|
||||
for (const n of (Array.isArray(o.nav) ? o.nav : [o.nav])) {
|
||||
const c = normalizeLang(n)
|
||||
if (c) return c
|
||||
}
|
||||
return "en"
|
||||
}
|
||||
// the newest prompt/title in a snapshot, the sample the script check reads
|
||||
function sample(snap) {
|
||||
let best = null
|
||||
for (const s of Array.isArray(snap?.sessions) ? snap.sessions : []) {
|
||||
const t = [s?.query, s?.title].filter(Boolean).join(" ")
|
||||
if (!t) continue
|
||||
const at = Math.max(s.updated || 0, s.touched || 0, s.last?.at || 0, s.started || 0)
|
||||
if (!best || at > best.at) best = { at, text: t }
|
||||
}
|
||||
return best ? best.text : ""
|
||||
}
|
||||
|
||||
function hash(s) {
|
||||
let h = 2166136261
|
||||
for (const c of String(s)) h = Math.imul(h ^ c.codePointAt(0), 16777619)
|
||||
@@ -79,7 +544,9 @@
|
||||
}
|
||||
|
||||
// { status, sub }: status one of STATUSES; sub says more (approval, ask,
|
||||
// stopped, stuck) for the card and the list
|
||||
// stopped, noprog, stuck) for the card and the list. `progress: true` is
|
||||
// the workbench's reading: a stalled turn still works, it merely says it
|
||||
// has made no progress. Without it the older reading is kept.
|
||||
function state(s, now, opts = {}) {
|
||||
if (s.source === "files" || s.phase) {
|
||||
const quiet = now - (s.touched || s.updated || now)
|
||||
@@ -89,11 +556,15 @@
|
||||
case "error": return { status: "error", sub: "" }
|
||||
case "aborted": return { status: "done", sub: "stopped" }
|
||||
case "done": return { status: "done", sub: "" }
|
||||
case "tool": return quiet > STUCK_MS ? { status: "error", sub: "stuck" } : { status: "executing", sub: "" }
|
||||
case "tool":
|
||||
if (quiet > STUCK_MS) return opts.progress ? { status: "executing", sub: "stuck" } : { status: "error", sub: "stuck" }
|
||||
return { status: "executing", sub: "" }
|
||||
case "thinking": default:
|
||||
if (quiet > STUCK_MS) return { status: "error", sub: "stuck" }
|
||||
// a reply being written: the model has the word and the file moves
|
||||
return { status: s.reply && quiet < 4000 ? "replying" : "thinking", sub: "" }
|
||||
if (s.reply && quiet < 4000) return { status: "replying", sub: "" }
|
||||
if (quiet > (opts.progress ? NOPROGRESS_MS : STUCK_MS)) {
|
||||
return opts.progress ? { status: "thinking", sub: "noprog" } : { status: "error", sub: "stuck" }
|
||||
}
|
||||
return { status: "thinking", sub: "" }
|
||||
}
|
||||
}
|
||||
// only the gateway saw it: from its requests
|
||||
@@ -110,7 +581,11 @@
|
||||
|
||||
// what the user may clear: an agent not at work. A stuck one (error), a
|
||||
// stopped or finished one, and one waiting on a process that may be gone.
|
||||
function clearable(st) { return st === "done" || st === "error" || st === "waiting" }
|
||||
function clearable(value, sub = "") {
|
||||
const st = typeof value === "object" ? value?.status : value
|
||||
const detail = typeof value === "object" ? value?.sub : sub
|
||||
return st === "done" || st === "error" || st === "waiting" || detail === "stuck" || detail === "noprog"
|
||||
}
|
||||
|
||||
function ago(ms, lang) {
|
||||
const t = text(lang)
|
||||
@@ -124,13 +599,16 @@
|
||||
|
||||
// 45 000 → "45s"; 130 000 → "2m 10s"; 3 900 000 → "1h 5m"
|
||||
function duration(ms, lang) {
|
||||
const zh = text(lang) === TEXT.zh
|
||||
const w = text(lang)
|
||||
const code = normalizeLang(lang)
|
||||
const cjk = code === "zh-CN" || code === "zh-TW" || code === "ja" || code === "ko"
|
||||
const gap = cjk ? "" : " "
|
||||
const s = Math.max(0, Math.round(ms / 1000))
|
||||
if (s < 60) return zh ? s + "秒" : s + "s"
|
||||
if (s < 60) return s + w.unitS
|
||||
const m = Math.floor(s / 60), r = s % 60
|
||||
if (m < 60) return zh ? `${m}分${r ? r + "秒" : ""}` : `${m}m${r ? " " + r + "s" : ""}`
|
||||
if (m < 60) return m + w.unitM + (r ? gap + r + w.unitS : "")
|
||||
const h = Math.floor(m / 60), mm = m % 60
|
||||
return zh ? `${h}小时${mm ? mm + "分" : ""}` : `${h}h${mm ? " " + mm + "m" : ""}`
|
||||
return h + w.unitH + (mm ? gap + mm + w.unitM : "")
|
||||
}
|
||||
|
||||
function shellQuote(s) {
|
||||
@@ -139,6 +617,8 @@
|
||||
|
||||
// the command that picks the session up again, where the agent has one
|
||||
function resume(s) {
|
||||
// a reader that already knows the agent's own resume syntax wins
|
||||
if (typeof s.resumeCommand === "string" && s.resumeCommand) return s.resumeCommand
|
||||
const id0 = String(s.session || "")
|
||||
if (!id0 || id0.startsWith("cwd:") || id0.startsWith("model:")) return ""
|
||||
const id = shellQuote(id0)
|
||||
@@ -150,36 +630,82 @@
|
||||
case "gemini": return `${cd}gemini --resume ${id}`
|
||||
case "qwen": return `${cd}qwen --resume ${id}`
|
||||
case "pi": return `${cd}pi --session ${id}`
|
||||
case "copilot": return `${cd}copilot --resume ${id}`
|
||||
case "kimi": return `${cd}kimi --session ${id}`
|
||||
case "grok": return `${cd}grok --resume ${id}`
|
||||
case "omp": return `${cd}omp --resume ${id}`
|
||||
case "dsh": return `${cd}dsh --resume ${shellQuote(id0.replace(/^session-/, ""))}`
|
||||
default: return ""
|
||||
}
|
||||
}
|
||||
|
||||
function num(v) { const n = Number(v); return Number.isFinite(n) ? n : 0 }
|
||||
|
||||
// How full the model's context window is. `context` may be a number of
|
||||
// used tokens or {used, window}; contextWindow overrides the window.
|
||||
function context(a) {
|
||||
if (!a) return null
|
||||
let used = null, window = 0
|
||||
const c = a.context
|
||||
if (typeof c === "number") used = c
|
||||
else if (c && typeof c === "object") {
|
||||
if (c.used != null) used = num(c.used)
|
||||
if (c.window != null) window = num(c.window)
|
||||
}
|
||||
if (a.contextWindow != null) window = num(a.contextWindow)
|
||||
if (used == null || !(window > 0)) return null
|
||||
const pct = Math.max(0, Math.min(100, Math.round((used / window) * 100)))
|
||||
return { used: Math.round(used), window: Math.round(window), pct, level: pct >= 85 ? "full" : pct >= 60 ? "warn" : "ok" }
|
||||
}
|
||||
|
||||
function fmtTokens(n) {
|
||||
n = num(n)
|
||||
if (n < 1000) return String(Math.round(n))
|
||||
if (n < 1e6) return n < 1e4 ? (n / 1e3).toFixed(1) + "k" : Math.round(n / 1e3) + "k"
|
||||
return n < 1e7 ? (n / 1e6).toFixed(2) + "M" : (n / 1e6).toFixed(1) + "M"
|
||||
}
|
||||
|
||||
// the agents to draw: [{ key, agent, brand, title, status, sub, at, … }]
|
||||
function agents(snap, now, opts = {}) {
|
||||
const o = { ...DEFAULTS, ...opts }
|
||||
const hide = HIDE[o.hideAfter] ?? HIDE["6h"]
|
||||
// { key: at } the user cleared; it stays out until its session moves
|
||||
const picked = Array.isArray(o.agents) ? o.agents.filter((x) => typeof x === "string") : []
|
||||
const cleared = o.cleared && typeof o.cleared === "object" ? o.cleared : {}
|
||||
const out = []
|
||||
for (const s of Array.isArray(snap?.sessions) ? snap.sessions : []) {
|
||||
if (!s || typeof s.key !== "string") continue
|
||||
if (picked.length && !picked.includes(s.agent)) continue
|
||||
const subagent = !!(s.subagent || s.isSubagent || (s.parent && s.parent !== s.key))
|
||||
if (subagent && o.showSub === false) continue
|
||||
const { status: st, sub } = state(s, now, o)
|
||||
const at = Math.max(s.updated || 0, s.touched || 0, s.last?.at || 0)
|
||||
const quiet = now - at
|
||||
if ((st === "done" || st === "error") && quiet > hide) continue
|
||||
if (st === "done" && !o.showDone) continue
|
||||
const c = Number(cleared[s.key])
|
||||
if (c && at <= c && clearable(st)) continue
|
||||
if (c && at <= c && clearable(st, sub)) continue
|
||||
const idle = st === "done" && quiet > IDLE_MS
|
||||
if (idle && o.showIdle === false) continue
|
||||
const b = brand(s.agent)
|
||||
// how long the current step has gone on
|
||||
const since = s.pendingSince ? now - s.pendingSince : quiet
|
||||
out.push({
|
||||
key: s.key, agent: s.agent, brand: b, session: s.session || "", status: st, sub, source: s.source || "gateway",
|
||||
idle: st === "done" && quiet > 20 * 60e3,
|
||||
idle,
|
||||
subagent,
|
||||
parent: s.parent || "",
|
||||
profile: s.profile || "",
|
||||
title: s.title || s.project || b.name, project: s.project || "", cwd: s.cwd || "",
|
||||
query: s.query || "", step: s.step || s.last?.step || "", reply: s.reply || s.last?.text || "", error: s.error || "",
|
||||
model: s.model || "", at, since, started: s.started || at, turns: s.turns || 0,
|
||||
turnsToday: s.turnsToday,
|
||||
tokensToday: s.tokensToday,
|
||||
context: s.context,
|
||||
contextWindow: s.contextWindow,
|
||||
ctx: context(s),
|
||||
messages: Array.isArray(s.messages) ? s.messages : [],
|
||||
private: s.private === true,
|
||||
noProgress: sub === "noprog" || sub === "stuck",
|
||||
resume: resume(s), seed: hash(s.key),
|
||||
})
|
||||
}
|
||||
@@ -203,17 +729,105 @@
|
||||
return list.slice().sort((a, b) => (RANK[a.status] - RANK[b.status]) || (b.at - a.at))
|
||||
}
|
||||
|
||||
// the workbench's three groups, in the order they matter
|
||||
const GROUPS = [
|
||||
{ key: "needYou", match: (a) => a.status === "waiting" || a.status === "error" },
|
||||
{ key: "working", match: (a) => a.status === "thinking" || a.status === "executing" || a.status === "replying" },
|
||||
{ key: "finished", match: (a) => a.status === "done" },
|
||||
]
|
||||
function groups(list) {
|
||||
return GROUPS.map((g) => ({
|
||||
key: g.key,
|
||||
list: list.filter((a) => g.match(a)).sort((a, b) => b.at - a.at),
|
||||
}))
|
||||
}
|
||||
|
||||
// Today's turns and tokens, per agent and per folder, plus each session's
|
||||
// context fullness. Sessions without the fields simply don't contribute.
|
||||
function today(list) {
|
||||
const byAgent = {}
|
||||
const projects = {}
|
||||
const contexts = []
|
||||
let turns = 0, tokens = 0, hasUsage = false
|
||||
for (const a of list) {
|
||||
// readers write 0 when the file says nothing, so only positive counts
|
||||
// are usage; all-zero sessions must not look like a busy day
|
||||
const hasTurns = a.turnsToday != null && Number.isFinite(Number(a.turnsToday)) && Number(a.turnsToday) > 0
|
||||
const hasTokens = a.tokensToday != null && Number.isFinite(Number(a.tokensToday)) && Number(a.tokensToday) > 0
|
||||
const at = hasTurns ? num(a.turnsToday) : 0
|
||||
const ak = hasTokens ? num(a.tokensToday) : 0
|
||||
if (hasTurns || hasTokens) {
|
||||
hasUsage = true
|
||||
turns += at
|
||||
tokens += ak
|
||||
const id = a.agent || a.brand?.id || "agent"
|
||||
const row = byAgent[id] || (byAgent[id] = { agent: id, name: a.brand?.name || id, turns: 0, tokens: 0 })
|
||||
row.turns += at
|
||||
row.tokens += ak
|
||||
const project = a.project || a.brand?.name || id
|
||||
const p = projects[project] || (projects[project] = { project, turns: 0, tokens: 0 })
|
||||
p.turns += at
|
||||
p.tokens += ak
|
||||
}
|
||||
const c = a.ctx || context(a)
|
||||
if (c) contexts.push({ key: a.key, agent: a.agent, name: a.brand?.name || a.agent, project: a.project || "", ...c })
|
||||
}
|
||||
const projectList = Object.values(projects)
|
||||
.filter((p) => p.turns > 0 || p.tokens > 0)
|
||||
.sort((a, b) => b.turns - a.turns || b.tokens - a.tokens)
|
||||
.slice(0, 5)
|
||||
return {
|
||||
hasUsage, turns, tokens,
|
||||
agentCount: Object.keys(byAgent).length,
|
||||
byAgent,
|
||||
projects: projectList,
|
||||
contexts: contexts.sort((a, b) => b.pct - a.pct),
|
||||
}
|
||||
}
|
||||
|
||||
// the page's own side of text off: whatever live.js holds, no prompt,
|
||||
// reply, error or tool argument is shown. A tool step keeps its name only.
|
||||
// reply, error, tool argument or conversation is shown. A tool step keeps
|
||||
// its name only.
|
||||
function redact(list) {
|
||||
return list.map((a) => {
|
||||
const step = String(a.step || "")
|
||||
const name = step.includes(" · ") ? step.split(" · ")[0]
|
||||
: /^[A-Za-z0-9_.-]{1,40}$/.test(step) ? step : ""
|
||||
return { ...a, title: a.project || a.brand?.name || a.agent || "", query: "", reply: "", error: "", step: name }
|
||||
const candidate = step.split(" · ", 1)[0]
|
||||
const name = /^[A-Za-z_][A-Za-z0-9_.:-]{0,95}$/.test(candidate) ? candidate : ""
|
||||
return {
|
||||
...a, title: a.project || a.brand?.name || a.agent || "", query: "", reply: "", error: "", step: name,
|
||||
messages: [], private: true,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Pack labels in CSS pixels after clamping to the viewport. Candidates
|
||||
// above and below an anchor let dense crowds spread without clamping
|
||||
// every label to the same top edge. Omit a label if no safe box exists.
|
||||
function layoutTags(items, width, height, limit = 8) {
|
||||
const gap = 6, edge = 6, placed = []
|
||||
if (width <= edge * 2 || height <= edge * 2) return placed
|
||||
for (const item of items) {
|
||||
if (placed.length >= limit) break
|
||||
const w = Math.min(item.w || 90, width - edge * 2), h = item.h || 22
|
||||
if (h > height - edge * 2) continue
|
||||
const clampX = x => Math.max(edge + w / 2, Math.min(width - edge - w / 2, x))
|
||||
const clampY = y => Math.max(edge + h, Math.min(height - edge, y))
|
||||
const xs = [...new Set([item.x, item.x - w - gap, item.x + w + gap, width / 2].map(clampX))]
|
||||
const baseY = clampY(item.y)
|
||||
const candidates = []
|
||||
for (let row = 0; row <= Math.ceil(height / (h + gap)); row++) {
|
||||
for (const y of row ? [baseY - row * (h + gap), baseY + row * (h + gap)] : [baseY]) {
|
||||
if (y - h < edge || y > height - edge) continue
|
||||
for (const x of xs) candidates.push({x, y, score: Math.abs(x - item.x) + Math.abs(y - item.y) * 1.4})
|
||||
}
|
||||
}
|
||||
candidates.sort((a,b) => a.score-b.score)
|
||||
const fit = candidates.find(p => !placed.some(q => p.x-w/2 < q.x+q.w/2+gap && p.x+w/2+gap > q.x-q.w/2 && p.y-h < q.y+gap && p.y+gap > q.y-q.h))
|
||||
if (fit) placed.push({key: item.key, x: fit.x, y: fit.y, w, h})
|
||||
}
|
||||
return placed
|
||||
}
|
||||
|
||||
// what the page draws: what the host wrote, and, with sample agents on,
|
||||
// theirs beside it — never instead of it
|
||||
function merge(real, demo) {
|
||||
@@ -224,27 +838,58 @@
|
||||
// sample agents, for a first look (Settings › Sample agents)
|
||||
function demo(now) {
|
||||
const m = 60e3
|
||||
const msg = (role, text, name, at) => ({ role, text, name, at })
|
||||
const S = (agent, session, cwd, title, query, model, phase, extra) => ({
|
||||
key: `demo|${agent}|${session}`, source: "files", agent, session, cwd, project: cwd.split("/").pop(), title, query, model,
|
||||
started: now - 50 * m, updated: now - 1000, touched: now - 1000, phase, turns: 3, ...extra,
|
||||
started: now - 50 * m, updated: now - 1000, touched: now - 1000, phase, turns: 3,
|
||||
turnsToday: 1, tokensToday: 2400, context: 48000, contextWindow: 200000,
|
||||
messages: [
|
||||
msg("user", query, "", now - 40 * m),
|
||||
msg("assistant", "收到,我先看一下现状。", "assistant", now - 39 * m),
|
||||
],
|
||||
...extra,
|
||||
})
|
||||
return { v: 2, written: now, text: true, demo: true, sessions: [
|
||||
S("codex", "demo-1", "/Users/me/blog", "封面图", "用 punk skill 生成文章封面", "gpt-6-astra", "done",
|
||||
{ touched: now - 28 * m, updated: now - 28 * m, step: "image_gen · cover.png", reply: "已用内置生图完成「方块世界」封面,PNG · 1600×900,放进 assets/cover.png。" }),
|
||||
{ touched: now - 28 * m, updated: now - 28 * m, step: "image_gen · cover.png", reply: "已用内置生图完成「方块世界」封面,PNG · 1600×900,放进 assets/cover.png。",
|
||||
turnsToday: 3, tokensToday: 18200, context: 96000,
|
||||
messages: [
|
||||
msg("user", "用 punk skill 生成文章封面", "", now - 46 * m),
|
||||
msg("assistant", "我先读一下文章结构,再定封面方向。", "assistant", now - 45 * m),
|
||||
msg("tool", "image_gen · cover.png", "", now - 30 * m),
|
||||
msg("assistant", "已用内置生图完成「方块世界」封面,PNG · 1600×900,放进 assets/cover.png。", "assistant", now - 28 * m),
|
||||
] }),
|
||||
S("claude", "demo-2", "/Users/me/oh-my-x", "oh-my-x", "给 CLI 加一个 --json 输出", "claude-opus-5", "tool",
|
||||
{ touched: now - 3000, pendingSince: now - 42000, step: "Bash · bun test" }),
|
||||
{ touched: now - 3000, pendingSince: now - 42000, step: "Bash · bun test", context: 172000,
|
||||
messages: [
|
||||
msg("user", "给 CLI 加一个 --json 输出", "", now - 12 * m),
|
||||
msg("tool", "Bash · bun test", "", now - 42e3),
|
||||
] }),
|
||||
S("claude", "demo-3", "/Users/me/x", "X 选题", "下周发什么?给我 5 个选题", "claude-sonnet-5", "ask",
|
||||
{ touched: now - 2 * m, step: "AskUserQuestion · 工具测评还是工作流?", reply: "我列了 5 个方向。你更想写工具测评,还是写自己的工作流?" }),
|
||||
{ touched: now - 2 * m, step: "AskUserQuestion · 工具测评还是工作流?", reply: "我列了 5 个方向。你更想写工具测评,还是写自己的工作流?",
|
||||
turnsToday: 1, tokensToday: 3600, context: 118000,
|
||||
messages: [
|
||||
msg("user", "下周发什么?给我 5 个选题", "", now - 8 * m),
|
||||
msg("assistant", "我列了 5 个方向。你更想写工具测评,还是写自己的工作流?", "assistant", now - 2 * m),
|
||||
] }),
|
||||
S("dsh", "demo-4", "/Users/me/site", "站点部署", "部署到 Cloudflare Pages", "deepseek-flash", "approval",
|
||||
{ touched: now - 40000, step: "bash · wrangler pages deploy ./dist" }),
|
||||
{ touched: now - 40000, step: "bash · wrangler pages deploy ./dist", turnsToday: 0, tokensToday: 5800, context: 76000 }),
|
||||
S("gemini", "demo-5", "/Users/me/music", "自动修歌", "把副歌的节拍对齐到 120 BPM", "gemini-3-pro", "thinking",
|
||||
{ touched: now - 1500, reply: "" }),
|
||||
{ touched: now - 1500, reply: "", turnsToday: 1, tokensToday: 2100, context: 45000 }),
|
||||
S("qwen", "demo-6", "/Users/me/notes", "工具整理", "整理这周收藏的工具和思路", "qwen3-coder", "done",
|
||||
{ touched: now - 40 * m, updated: now - 40 * m, reply: "整理好了:12 个工具、5 条思路,按「写作 / 编程 / 效率」分组写进 weekly.md。" }),
|
||||
{ touched: now - 40 * m, updated: now - 40 * m, reply: "整理好了:12 个工具、5 条思路,按「写作 / 编程 / 效率」分组写进 weekly.md。",
|
||||
turnsToday: 3, tokensToday: 9800, context: 64000 }),
|
||||
S("codex", "demo-7", "/Users/me/app", "支付接入", "接入 Stripe 订阅", "gpt-6.1-terra", "error",
|
||||
{ touched: now - 6 * m, error: "429: usage limit reached", step: "exec · npm run test:e2e" }),
|
||||
{ touched: now - 6 * m, error: "429: usage limit reached", step: "exec · npm run test:e2e", turnsToday: 1, tokensToday: 1200, context: 88000 }),
|
||||
] }
|
||||
}
|
||||
|
||||
globalThis.AgentOfficeModel = { TEXT, STATUSES, COLORS, DEFAULTS, HIDE, STUCK_MS, text, fill, hash, brand, state, status, clearable, ago, duration, resume, agents, counts, sorted, demo, merge, redact }
|
||||
globalThis.AgentOfficeModel = {
|
||||
TEXT, LANGS, LANG_NAMES, STATUSES, COLORS, DEFAULTS, HIDE, GROUPS, clearable,
|
||||
NOPROGRESS_MS, STUCK_MS, IDLE_MS,
|
||||
text, normalizeLang, scriptLang, detectLang, sample, fill, hash, brand,
|
||||
state, status, ago, duration, resume,
|
||||
context, fmtTokens, today, agents, counts, sorted, groups,
|
||||
demo, merge, redact, layoutTags,
|
||||
}
|
||||
})()
|
||||
|
||||
@@ -62,12 +62,34 @@
|
||||
const ZONE_SPOTS = []
|
||||
for (let j = 0; j < 3; j++) for (let i = 0; i < 4; i++) ZONE_SPOTS.push([ZONE.x + 0.6 + i * 1.05 + (j % 2) * 0.3, ZONE.y + 0.6 + j * 1.05])
|
||||
const ERROR_SPOTS = [[12.3, 9.6], [14.5, 8.6], [12.9, 10.45], [14.6, 10.3]]
|
||||
const WANDER = [[7.0, 4.4], [8.6, 5.7], [6.0, 5.8], [9.0, 8.0], [10.2, 9.0], [2.8, 3.2], [5.0, 3.4], [9.6, 2.9], [2.4, 6.0]]
|
||||
const WANDER = [[7.0, 4.4], [8.6, 5.7], [6.0, 5.8], [9.0, 8.0], [10.2, 9.0], [4.9, 4.8], [5.0, 3.4], [9.6, 2.9], [2.4, 6.0]]
|
||||
const DOOR = [0.6, 2.6]
|
||||
|
||||
// ---- activity venues -------------------------------------------------
|
||||
// A finished worker doesn't only sleep on the sofa any more: it drifts
|
||||
// to a venue, lingers a while, then drifts on. Each venue has a front
|
||||
// approach on the side the camera sees (south or east) and a facing that
|
||||
// looks at the furniture, so a reader can tell what it is doing.
|
||||
const ACTIVITIES = [
|
||||
{ id: "bookshelf", label: "READING", x: 1.45, y: 0.5, w: 1.6, d: 0.55, ax: 2.25, ay: 1.65, face: "n", lz: 2.4, color: "#fcd34d" },
|
||||
{ id: "arcade", label: "ARCADE", x: 2.5, y: 3.2, w: 0.9, d: 0.7, ax: 3.95, ay: 3.55, face: "w", lz: 1.95, color: "#38bdf8" },
|
||||
{ id: "meeting", label: "HUDDLE", x: 6.9, y: 2.55, w: 1.7, d: 0.95, ax: 7.75, ay: 3.95, face: "n", lz: 2.05, color: "#a78bfa" },
|
||||
{ id: "pingpong", label: "PING-PONG", x: 9.55, y: 7.15, w: 1.9, d: 1.05, ax: 10.5, ay: 8.85, face: "n", lz: 1.15, color: "#34d399" },
|
||||
{ id: "coffee", label: "COFFEE", x: 14.35, y: 2.15, w: 1.35, d: 0.85, ax: 14.9, ay: 3.4, face: "n", lz: 1.55, color: "#fb923c" },
|
||||
]
|
||||
const POIS = ACTIVITIES
|
||||
const POI_APPROACHES = ACTIVITIES.map((a) => [a.ax, a.ay, a.face])
|
||||
// The sofa seats are venues too: a worker that has finished for a while
|
||||
// may curl up there instead of standing at a table.
|
||||
const ACTIVITY_SPOTS = [
|
||||
...ACTIVITIES.map((a) => [a.ax, a.ay, a.face]),
|
||||
...SOFA.map(([x, y], i) => [x, y, SOFA_FACE[i]]),
|
||||
]
|
||||
|
||||
// What stands on the floor and can't be walked through, and the places a
|
||||
// worker goes, which are free even inside a piece of furniture (a seat).
|
||||
const BLOCKERS = [
|
||||
...ACTIVITIES.map((a) => [a.x, a.y, a.w, a.d]),
|
||||
...DESKS.map((d) => [d.x, d.y, d.w, d.d]),
|
||||
[0, 4.1, 1.5, 5.0], // full sofa and the gap behind its backrest
|
||||
[2.5, 10.55, 2.4, 1.45], // full sofa and rear wall gap
|
||||
@@ -78,7 +100,7 @@
|
||||
[14.3, 6.6, 1.2, 1.6], // the broken console
|
||||
[14.0, 0.5, 1.6, 1.0], // the console on the far wall
|
||||
]
|
||||
const FREE = [...DESKS.map((d) => d.seat), ...SOFA_APPROACH, ...ZONE_SPOTS, ...ERROR_SPOTS, ...WANDER, DOOR]
|
||||
const FREE = [...DESKS.map((d) => d.seat), ...SOFA_APPROACH, ...ZONE_SPOTS, ...ERROR_SPOTS, ...WANDER, ...ACTIVITIES.map((a) => [a.ax, a.ay]), DOOR]
|
||||
|
||||
// A coarse grid of where a worker may walk, and the shortest way across
|
||||
// it: eight neighbours, diagonals only when both sides are free, then
|
||||
@@ -219,6 +241,41 @@
|
||||
amount: Math.sin(Math.PI * phase / 4), phase }
|
||||
}
|
||||
|
||||
// ---- local time of day ------------------------------------------------
|
||||
// The office follows the viewer's clock: dawn warms the glass, day is a
|
||||
// cool blue, dusk goes pink, night is the dark space station again. Pure:
|
||||
// an hour or a Date in, a palette out (the tests use it directly).
|
||||
const SKY_PHASES = {
|
||||
night: { sky: ["#05070f", "#0b1020"], star: 1, glass: "rgba(120,170,255,.09)", ambient: "rgba(10,16,32,.16)", planet: 1, label: "night" },
|
||||
dawn: { sky: ["#17162e", "#3a2438"], star: 0.35, glass: "rgba(251,146,60,.15)", ambient: "rgba(251,146,60,.06)", planet: 0.85, label: "dawn" },
|
||||
day: { sky: ["#0d1b2e", "#1e3a5f"], star: 0.06, glass: "rgba(147,197,253,.22)", ambient: "rgba(147,197,253,.05)", planet: 0.7, label: "day" },
|
||||
dusk: { sky: ["#21132b", "#4a2440"], star: 0.45, glass: "rgba(244,114,182,.17)", ambient: "rgba(244,114,182,.05)", planet: 0.9, label: "dusk" },
|
||||
}
|
||||
function phaseOfHour(hour) {
|
||||
const h = ((Number.isFinite(hour) ? hour : 12) % 24 + 24) % 24
|
||||
if (h >= 5 && h < 7.5) return "dawn"
|
||||
if (h >= 7.5 && h < 17) return "day"
|
||||
if (h >= 17 && h < 19.5) return "dusk"
|
||||
return "night"
|
||||
}
|
||||
function dayPhase(when) {
|
||||
let hour
|
||||
if (when instanceof Date) hour = when.getHours() + when.getMinutes() / 60
|
||||
else if (typeof when === "number" && Number.isFinite(when)) hour = when
|
||||
else { const d = new Date(); hour = d.getHours() + d.getMinutes() / 60 }
|
||||
const phase = phaseOfHour(hour)
|
||||
return { phase, hour: ((hour % 24) + 24) % 24, ...SKY_PHASES[phase] }
|
||||
}
|
||||
|
||||
// a finished worker lingers 8–30 s at a venue before drifting to another
|
||||
function activityDwell(seed) {
|
||||
return Math.round((8 + rnd(seed >>> 0, 71) * 22) * 10) / 10
|
||||
}
|
||||
|
||||
// how far the camera may zoom and pan; pan is a fraction of the canvas so
|
||||
// a corner can be inspected but the office can never be lost
|
||||
const CAMERA = { minZoom: 1, maxZoom: 4, panMargin: 0.12, smooth: 0.18 }
|
||||
|
||||
class Scene {
|
||||
constructor(canvas, opts = {}) {
|
||||
this.c = canvas
|
||||
@@ -230,16 +287,32 @@
|
||||
this.last = 0
|
||||
this.running = false
|
||||
this.first = true
|
||||
this.cam = { x: 0, y: 0, z: 1 }
|
||||
this.roomBox = null
|
||||
this.dayState = null
|
||||
this.phaseOverride = null
|
||||
this.cat = opts.cat === false ? null : { seed: 0 }
|
||||
this.reducedMotion = globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches || false
|
||||
this.stars = Array.from({ length: 140 }, (_, i) => [rnd(7, i), rnd(11, i), rnd(13, i)])
|
||||
this.resize()
|
||||
this.bindInput()
|
||||
}
|
||||
|
||||
// ---- geometry ----------------------------------------------------
|
||||
P(x, y, z = 0) {
|
||||
// rawP is the fitted room projected with no camera; P adds pan and zoom
|
||||
// about the canvas centre, so every anchor, bubble and hit test follows.
|
||||
rawP(x, y, z = 0) {
|
||||
if (this.dim === "3d") return [this.ox + (x - y) * this.s * 0.866, this.oy + (x + y) * this.s * 0.5 - z * this.s]
|
||||
return [this.ox + x * this.s, this.oy + y * this.s * 0.82 - z * this.s * 0.5]
|
||||
}
|
||||
P(x, y, z = 0) {
|
||||
const p = this.rawP(x, y, z)
|
||||
const cam = this.cam
|
||||
if (!cam || !this.W || !this.H) return p
|
||||
const zf = Number.isFinite(cam.z) && cam.z > 0 ? cam.z : 1
|
||||
const cx = this.W / 2, cy = this.H / 2
|
||||
return [cx + (p[0] - cx) * zf + (cam.x || 0), cy + (p[1] - cy) * zf + (cam.y || 0)]
|
||||
}
|
||||
depth(x, y, z = 0) {
|
||||
return this.dim === "3d" ? x + y + z * 0.001 : y + z * 0.001
|
||||
}
|
||||
@@ -258,17 +331,27 @@
|
||||
fit() {
|
||||
// the room's corners at scale 1, then scale and centre it
|
||||
this.s = 1; this.ox = 0; this.oy = 0
|
||||
const pts = []
|
||||
for (const [x, y] of [[0, 0], [ROOM.w, 0], [0, ROOM.d], [ROOM.w, ROOM.d]]) {
|
||||
pts.push(this.P(x, y, 0))
|
||||
if (x === 0 || y === 0) pts.push(this.P(x, y, this.dim === "3d" ? ROOM.wall : 0.9))
|
||||
}
|
||||
const pts = this.roomOutline().map(([x, y, z]) => this.rawP(x, y, z))
|
||||
const xs = pts.map((p) => p[0]), ys = pts.map((p) => p[1])
|
||||
const bw = Math.max(...xs) - Math.min(...xs), bh = Math.max(...ys) - Math.min(...ys)
|
||||
const pad = this.dim === "3d" ? 0.04 : 0.06
|
||||
this.s = Math.min((this.W * (1 - pad * 2)) / bw, (this.H * (1 - pad * 2)) / bh)
|
||||
this.ox = (this.W - bw * this.s) / 2 - Math.min(...xs) * this.s
|
||||
this.oy = (this.H - bh * this.s) / 2 - Math.min(...ys) * this.s + (this.dim === "3d" ? this.H * 0.02 : 0)
|
||||
// remember the fitted room so pan and zoom can be clamped around it
|
||||
const screen = this.roomOutline().map(([x, y, z]) => this.rawP(x, y, z))
|
||||
const sx = screen.map((p) => p[0]), sy = screen.map((p) => p[1])
|
||||
this.roomBox = { minX: Math.min(...sx), maxX: Math.max(...sx), minY: Math.min(...sy), maxY: Math.max(...sy) }
|
||||
this.clampCamera()
|
||||
}
|
||||
|
||||
roomOutline() {
|
||||
const pts = []
|
||||
for (const [x, y] of [[0, 0], [ROOM.w, 0], [0, ROOM.d], [ROOM.w, ROOM.d]]) {
|
||||
pts.push([x, y, 0])
|
||||
if (x === 0 || y === 0) pts.push([x, y, this.dim === "3d" ? ROOM.wall : 0.9])
|
||||
}
|
||||
return pts
|
||||
}
|
||||
|
||||
setDim(dim) {
|
||||
@@ -276,6 +359,151 @@
|
||||
this.fit()
|
||||
}
|
||||
|
||||
// ---- camera: drag to pan, wheel or two fingers to zoom -------------
|
||||
clampCamera() {
|
||||
const cam = this.cam
|
||||
if (!cam) return
|
||||
const z = Number.isFinite(cam.z) ? Math.min(CAMERA.maxZoom, Math.max(CAMERA.minZoom, cam.z)) : 1
|
||||
cam.z = z
|
||||
cam.x = Number.isFinite(cam.x) ? cam.x : 0
|
||||
cam.y = Number.isFinite(cam.y) ? cam.y : 0
|
||||
if (!this.roomBox || !this.W || !this.H) return
|
||||
const b = this.roomBox
|
||||
const mx = Math.max(0, ((b.maxX - b.minX) * z - this.W) / 2) + this.W * CAMERA.panMargin
|
||||
const my = Math.max(0, ((b.maxY - b.minY) * z - this.H) / 2) + this.H * CAMERA.panMargin
|
||||
cam.x = Math.max(-mx, Math.min(mx, cam.x))
|
||||
cam.y = Math.max(-my, Math.min(my, cam.y))
|
||||
}
|
||||
|
||||
panBy(dx, dy) {
|
||||
const cam = this.cam
|
||||
if (!cam) return this
|
||||
cam.x = (cam.x || 0) + (Number(dx) || 0)
|
||||
cam.y = (cam.y || 0) + (Number(dy) || 0)
|
||||
this.clampCamera()
|
||||
return this
|
||||
}
|
||||
|
||||
// zoom about a point of the canvas, keeping that point under the pointer
|
||||
zoomAt(px, py, factor) {
|
||||
const cam = this.cam
|
||||
if (!cam) return this
|
||||
const f = Number(factor)
|
||||
if (!Number.isFinite(f) || f <= 0) return this
|
||||
const z0 = Number.isFinite(cam.z) && cam.z > 0 ? cam.z : 1
|
||||
const z1 = Math.min(CAMERA.maxZoom, Math.max(CAMERA.minZoom, z0 * f))
|
||||
if (Math.abs(z1 - z0) < 1e-6) return this
|
||||
const cx = this.W / 2, cy = this.H / 2
|
||||
const ox = (Number.isFinite(px) ? px : cx) - cx
|
||||
const oy = (Number.isFinite(py) ? py : cy) - cy
|
||||
const r = z1 / z0
|
||||
cam.x = ox - (ox - (cam.x || 0)) * r
|
||||
cam.y = oy - (oy - (cam.y || 0)) * r
|
||||
cam.z = z1
|
||||
this.clampCamera()
|
||||
return this
|
||||
}
|
||||
|
||||
resetCamera() {
|
||||
this.cam = { x: 0, y: 0, z: 1 }
|
||||
return this
|
||||
}
|
||||
|
||||
bindInput() {
|
||||
const c = this.c
|
||||
if (!c?.addEventListener) return
|
||||
this._ptrs = new Map()
|
||||
this._drag = null
|
||||
this._pinch = null
|
||||
this._suppressClick = false
|
||||
if (c.style) c.style.touchAction = "none" // two fingers must zoom, not scroll the page
|
||||
const point = (e) => {
|
||||
const r = c.getBoundingClientRect?.() || { left: 0, top: 0 }
|
||||
return [e.clientX - r.left, e.clientY - r.top]
|
||||
}
|
||||
const down = (e) => {
|
||||
if (e.pointerType === "mouse" && e.button !== 0) return
|
||||
c.focus?.({ preventScroll: true })
|
||||
const [x, y] = point(e)
|
||||
this._ptrs.set(e.pointerId, { x, y })
|
||||
c.setPointerCapture?.(e.pointerId)
|
||||
this._suppressClick = false
|
||||
if (this._ptrs.size >= 2) {
|
||||
const [a, b] = [...this._ptrs.values()]
|
||||
this._pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2 }
|
||||
this._drag = null
|
||||
} else {
|
||||
this._drag = { x, y, sx: x, sy: y, moved: false }
|
||||
}
|
||||
}
|
||||
const move = (e) => {
|
||||
if (!this._ptrs.has(e.pointerId)) return
|
||||
const [x, y] = point(e)
|
||||
this._ptrs.set(e.pointerId, { x, y })
|
||||
if (this._ptrs.size >= 2 && this._pinch) {
|
||||
const [a, b] = [...this._ptrs.values()]
|
||||
const d = Math.hypot(a.x - b.x, a.y - b.y)
|
||||
const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2
|
||||
if (this._pinch.d > 1) this.zoomAt(mx, my, d / this._pinch.d)
|
||||
this.panBy(mx - this._pinch.mx, my - this._pinch.my)
|
||||
this._pinch = { d, mx, my }
|
||||
this._suppressClick = true
|
||||
e.preventDefault?.()
|
||||
return
|
||||
}
|
||||
const drag = this._drag
|
||||
if (!drag) return
|
||||
if (!drag.moved && Math.hypot(x - drag.sx, y - drag.sy) > 3) drag.moved = true
|
||||
if (drag.moved) {
|
||||
this.panBy(x - drag.x, y - drag.y)
|
||||
this._suppressClick = true
|
||||
if (c.style) c.style.cursor = "grabbing"
|
||||
e.preventDefault?.()
|
||||
}
|
||||
drag.x = x; drag.y = y
|
||||
}
|
||||
const up = (e) => {
|
||||
this._ptrs.delete(e.pointerId)
|
||||
if (this._ptrs.size < 2) this._pinch = null
|
||||
if (!this._ptrs.size) {
|
||||
this._drag = null
|
||||
if (c.style) c.style.cursor = ""
|
||||
// the click that follows a drag must not open the panel
|
||||
if (this._suppressClick) setTimeout(() => { this._suppressClick = false }, 0)
|
||||
}
|
||||
}
|
||||
c.addEventListener("pointerdown", down)
|
||||
c.addEventListener("pointermove", move)
|
||||
c.addEventListener("pointerup", up)
|
||||
c.addEventListener("pointercancel", up)
|
||||
c.addEventListener("wheel", (e) => {
|
||||
const before = this.cam.z
|
||||
const [x, y] = point(e)
|
||||
this.zoomAt(x, y, Math.exp(-(Number(e.deltaY) || 0) * 0.0018))
|
||||
if (this.cam.z !== before) e.preventDefault?.()
|
||||
}, { passive: false })
|
||||
// registered before the page's click handler, so a drag stays a drag
|
||||
c.addEventListener("click", (e) => {
|
||||
if (!this._suppressClick) return
|
||||
this._suppressClick = false
|
||||
e.stopImmediatePropagation?.()
|
||||
e.preventDefault?.()
|
||||
}, true)
|
||||
// 0 or Home brings the office back to its fitted view
|
||||
this._onKey = (e) => {
|
||||
if (e.defaultPrevented || !this.running || c.hidden || c.getClientRects?.().length === 0) return
|
||||
if (e.target !== c) return
|
||||
const tag = e.target?.tagName
|
||||
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || e.target?.isContentEditable) return
|
||||
if (e.key === "0" || e.key === "Home") { this.resetCamera(); e.preventDefault?.() }
|
||||
}
|
||||
globalThis.document?.addEventListener?.("keydown", this._onKey)
|
||||
}
|
||||
|
||||
dispose() {
|
||||
globalThis.document?.removeEventListener?.("keydown", this._onKey)
|
||||
}
|
||||
|
||||
// ---- drawing primitives ----------------------------------------
|
||||
poly(pts, fill, stroke) {
|
||||
const g = this.g
|
||||
@@ -329,17 +557,31 @@
|
||||
g.fillText(s, x, y)
|
||||
}
|
||||
|
||||
// the day/night palette, re-read every half minute (or overridden)
|
||||
currentPhase() {
|
||||
if (this.phaseOverride != null) return dayPhase(this.phaseOverride)
|
||||
const now = Date.now()
|
||||
if (!this._day || !this._dayAt || now - this._dayAt > 30000) {
|
||||
this._dayAt = now
|
||||
this._day = dayPhase(new Date(now))
|
||||
}
|
||||
return this._day
|
||||
}
|
||||
|
||||
// ---- the room ----------------------------------------------------
|
||||
background() {
|
||||
const g = this.g
|
||||
const day = this.dayState || dayPhase()
|
||||
const sky = g.createLinearGradient(0, 0, 0, this.H)
|
||||
sky.addColorStop(0, "#05070f")
|
||||
sky.addColorStop(1, "#0b1020")
|
||||
sky.addColorStop(0, day.sky[0])
|
||||
sky.addColorStop(1, day.sky[1])
|
||||
g.fillStyle = sky
|
||||
g.fillRect(0, 0, this.W, this.H)
|
||||
for (const [a, b, c] of this.stars) {
|
||||
if (day.star > 0.02) for (const [a, b, c] of this.stars) {
|
||||
const tw = 0.5 + 0.5 * Math.sin(this.t * (0.6 + c) + a * 40)
|
||||
g.fillStyle = `rgba(255,255,255,${0.15 + 0.55 * c * tw})`
|
||||
const alpha = (0.15 + 0.55 * c * tw) * day.star
|
||||
if (alpha < 0.02) continue
|
||||
g.fillStyle = `rgba(255,255,255,${alpha})`
|
||||
g.fillRect(a * this.W, b * this.H, c > 0.8 ? 2 : 1, c > 0.8 ? 2 : 1)
|
||||
}
|
||||
if (this.dim !== "3d") return
|
||||
@@ -355,6 +597,11 @@
|
||||
base.addColorStop(1, "#b34e1f")
|
||||
g.fillStyle = base
|
||||
g.fillRect(px - R, py - R, R * 2, R * 2)
|
||||
// dawn and dusk tint the planet's lit limb the way the room is lit
|
||||
if (day.planet < 1) {
|
||||
g.fillStyle = day.ambient
|
||||
g.fillRect(px - R, py - R, R * 2, R * 2)
|
||||
}
|
||||
const bands = ["#f6c48b", "#d9773b", "#fbe0b8", "#c85f29", "#efae6c", "#a8441b"]
|
||||
g.translate(px, py)
|
||||
g.rotate(-0.28)
|
||||
@@ -416,10 +663,25 @@
|
||||
})
|
||||
g.stroke()
|
||||
g.restore()
|
||||
// each venue's front approach: a soft ring where a worker stands
|
||||
for (const a of ACTIVITIES) {
|
||||
const [mx, my] = this.P(a.ax, a.ay, 0.012)
|
||||
const [r, gg, b] = rgb(a.color)
|
||||
const glow = 0.32 + 0.18 * Math.sin(this.t * 1.3 + a.ax * 3)
|
||||
g.save()
|
||||
g.strokeStyle = `rgba(${r},${gg},${b},${glow})`
|
||||
g.lineWidth = 1.5
|
||||
g.setLineDash([4, 4])
|
||||
g.beginPath()
|
||||
g.ellipse(mx, my, Math.max(4, this.s * 0.19), Math.max(3, this.s * 0.11), 0, 0, Math.PI * 2)
|
||||
g.stroke()
|
||||
g.restore()
|
||||
}
|
||||
}
|
||||
|
||||
walls() {
|
||||
const H = ROOM.wall
|
||||
const day = this.dayState || dayPhase()
|
||||
if (this.dim !== "3d") {
|
||||
this.box(-0.35, -0.35, 0, ROOM.w + 0.35, 0.35, 0.9, "#9aa1ad")
|
||||
this.box(-0.35, 0, 0, 0.35, ROOM.d, 0.9, "#8a919c")
|
||||
@@ -444,8 +706,8 @@
|
||||
g.fill("evenodd")
|
||||
g.restore()
|
||||
for (const [a, b] of wins) {
|
||||
// glass and frame
|
||||
this.poly(far(a, b, 1.05, H - 0.35), "rgba(120,170,255,.06)", "#7d838f")
|
||||
// glass and frame: the glass carries the local time's tint
|
||||
this.poly(far(a, b, 1.05, H - 0.35), day.glass, "#7d838f")
|
||||
this.poly(far((a + b) / 2 - 0.04, (a + b) / 2 + 0.04, 1.05, H - 0.35), "#7d838f")
|
||||
}
|
||||
this.poly(far(0, ROOM.w, 0, 0.32), "#9097a3")
|
||||
@@ -476,7 +738,7 @@
|
||||
g.transform(1, 0.577, 0, 1, 0, 0)
|
||||
g.fillStyle = "#1f2937"
|
||||
g.fillRect(-this.s * 1.5, -this.s * 0.24, this.s * 3, this.s * 0.48)
|
||||
this.text("ORBITAL STATION 7", 0, 0, Math.max(7, this.s * 0.26), "#e5e7eb", "800")
|
||||
this.text(globalThis.AgentOfficeModel?.text(this.lang)?.stationSign || "ORBITAL STATION 7", 0, 0, Math.max(7, this.s * 0.26), "#e5e7eb", "800")
|
||||
g.restore()
|
||||
}
|
||||
|
||||
@@ -490,6 +752,18 @@
|
||||
g.restore()
|
||||
}
|
||||
|
||||
// a thin wash over the room so dawn/day/dusk/night reads on the floor
|
||||
// and walls too; the workers themselves stay fully readable
|
||||
ambient() {
|
||||
const day = this.dayState || dayPhase()
|
||||
const g = this.g
|
||||
const wash = g.createLinearGradient(0, 0, 0, this.H)
|
||||
wash.addColorStop(0, day.ambient)
|
||||
wash.addColorStop(1, "rgba(0,0,0,0)")
|
||||
g.fillStyle = wash
|
||||
g.fillRect(0, 0, this.W, this.H)
|
||||
}
|
||||
|
||||
// ---- furniture: each a drawable with a depth -------------------
|
||||
props() {
|
||||
const out = []
|
||||
@@ -569,7 +843,7 @@
|
||||
S.box(x + 0.15, y + 0.15, z + 0.55, 0.3, 0.3, 0.01, "#f6c453", { line: false })
|
||||
}
|
||||
})
|
||||
// the robot dog
|
||||
// the robot dog, pacing its own open pocket by the crates
|
||||
const rx = 11.3 + Math.sin(this.t * 0.4) * 0.8
|
||||
add(rx, 10.9, 0.8, 0.5, () => {
|
||||
S.box(rx, 10.9, 0.15, 0.7, 0.45, 0.3, "#3f3f46")
|
||||
@@ -597,9 +871,147 @@
|
||||
S.box(14.1, 0.5, 0.8, 1.4, 0.35, 0.6, "#374151")
|
||||
S.onFront(14.1, 0.5, 0.8, 1.4, 0.35, 0.6, 0.1, 0.15, 0.9, 0.85, glow("#f59e0b"))
|
||||
})
|
||||
// the activity venues: coffee counter, table tennis, reading shelf,
|
||||
// whiteboard huddle, arcade cabinet, and the office cat on the shelf
|
||||
out.push(...this.activityProps())
|
||||
return out
|
||||
}
|
||||
|
||||
activityProps() {
|
||||
const out = []
|
||||
const S = this
|
||||
const add = (x, y, w, d, fn) => out.push({ k: this.depth(x + w / 2, y + d), fn })
|
||||
const glow = (c) => shade(c, 0.08 + 0.07 * Math.sin(this.t * 3))
|
||||
const by = (id) => ACTIVITIES.find((a) => a.id === id)
|
||||
|
||||
// reading nook: a tall shelf of book spines
|
||||
const shelf = by("bookshelf")
|
||||
add(shelf.x, shelf.y, shelf.w, shelf.d, () => {
|
||||
S.box(shelf.x, shelf.y, 0, shelf.w, shelf.d, 0.16, "#4a2f1b")
|
||||
S.box(shelf.x, shelf.y, 0.16, shelf.w, shelf.d, 1.62, "#6b4426")
|
||||
for (const z of [0.56, 1.02, 1.48]) S.box(shelf.x, shelf.y + shelf.d - 0.03, z, shelf.w, 0.03, 0.05, "#8a5a32", { line: false })
|
||||
const books = ["#ef4444", "#3b82f6", "#22c55e", "#f59e0b", "#a78bfa", "#ec4899", "#14b8a6", "#e5e7eb"]
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const x = shelf.x + 0.07 + i * 0.185
|
||||
S.onFront(x, shelf.y, 0.28, 0.145, shelf.d, 1.1, 0.08, 0.05, 0.92, 0.62, books[i])
|
||||
S.onFront(x, shelf.y, 0.28, 0.145, shelf.d, 1.1, 0.08, 0.66, 0.92, 0.95, books[(i + 3) % books.length])
|
||||
}
|
||||
// the shelf's led
|
||||
S.box(shelf.x + 0.05, shelf.y + shelf.d - 0.06, 1.78, shelf.w - 0.1, 0.06, 0.03, glow("#fcd34d"), { line: false })
|
||||
})
|
||||
// the cat: one slow, capped animation on top of the shelf
|
||||
if (this.cat) {
|
||||
const base = this.depth(shelf.x + shelf.w / 2, shelf.y + shelf.d) + 0.05
|
||||
out.push({ k: base, fn: () => S.catOnShelf() })
|
||||
}
|
||||
|
||||
// arcade: a cabinet whose lit screen faces the worker (east)
|
||||
const arc = by("arcade")
|
||||
add(arc.x, arc.y, arc.w, arc.d, () => {
|
||||
S.box(arc.x, arc.y, 0, arc.w, arc.d, 1.52, "#1e293b")
|
||||
S.box(arc.x, arc.y, 1.52, arc.w, arc.d, 0.1, "#0f172a")
|
||||
// marquee
|
||||
S.onRight(arc.x, arc.y, 1.18, arc.w, arc.d, 0.28, 0.08, 0.08, 0.92, 0.92, glow("#38bdf8"))
|
||||
// screen and controls on the east face
|
||||
S.onRight(arc.x, arc.y, 0.5, arc.w, arc.d, 0.55, 0.12, 0.12, 0.88, 0.88, glow("#0ea5e9"))
|
||||
S.onRight(arc.x, arc.y, 0.18, arc.w, arc.d, 0.12, 0.1, 0.1, 0.9, 0.9, "#0f172a")
|
||||
S.box(arc.x + 0.1, arc.y + 0.12, 0.1, 0.18, 0.1, 0.12, "#f43f5e", { line: false })
|
||||
S.box(arc.x + 0.52, arc.y + 0.12, 0.1, 0.18, 0.1, 0.12, "#22d3ee", { line: false })
|
||||
// a glowing top panel keeps the cabinet readable in the 2D view
|
||||
S.box(arc.x + 0.16, arc.y + 0.14, 1.52, 0.58, 0.42, 0.05, glow("#38bdf8"), { line: false })
|
||||
})
|
||||
|
||||
// whiteboard huddle: a low table and a lit whiteboard facing south
|
||||
const meet = by("meeting")
|
||||
add(meet.x, meet.y, meet.w, meet.d, () => {
|
||||
S.box(meet.x, meet.y, 0, meet.w, meet.d, 0.14, "#52525b")
|
||||
S.box(meet.x + 0.12, meet.y + 0.28, 0, 0.1, 0.1, 0.64, "#71717a", { line: false })
|
||||
S.box(meet.x + meet.w - 0.22, meet.y + 0.28, 0, 0.1, 0.1, 0.64, "#71717a", { line: false })
|
||||
S.box(meet.x, meet.y + 0.18, 0.62, meet.w, meet.d - 0.34, 0.1, "#d6d3d1")
|
||||
// the board stands on the north edge; its face looks south
|
||||
S.box(meet.x + 0.12, meet.y + 0.03, 0.1, meet.w - 0.24, 0.07, 1.28, "#e5e7eb")
|
||||
S.box(meet.x + 0.02, meet.y + 0.0, 0, meet.w - 0.04, 0.13, 0.14, "#64748b")
|
||||
S.onFront(meet.x + 0.18, meet.y + 0.03, 0.3, meet.w - 0.36, 0.07, 0.9, 0.1, 0.72, 0.52, 0.79, "#c4b5fd")
|
||||
S.onFront(meet.x + 0.18, meet.y + 0.03, 0.3, meet.w - 0.36, 0.07, 0.9, 0.16, 0.58, 0.78, 0.65, "#7dd3fc")
|
||||
S.onFront(meet.x + 0.18, meet.y + 0.03, 0.3, meet.w - 0.36, 0.07, 0.9, 0.1, 0.44, 0.44, 0.51, "#fca5a5")
|
||||
S.onFront(meet.x + 0.18, meet.y + 0.03, 0.3, meet.w - 0.36, 0.07, 0.9, 0.52, 0.3, 0.86, 0.37, "#86efac")
|
||||
// mugs and notes on the table
|
||||
for (const [mx, my, mc] of [[0.35, 0.72, "#f472b6"], [0.95, 0.74, "#fbbf24"], [1.35, 0.7, "#34d399"]]) {
|
||||
S.box(meet.x + mx, meet.y + my, 0.72, 0.09, 0.09, 0.1, mc, { line: false })
|
||||
}
|
||||
})
|
||||
|
||||
// ping-pong: green table, white net, paddles and a ball, legs and all
|
||||
const pp = by("pingpong")
|
||||
add(pp.x, pp.y, pp.w, pp.d, () => {
|
||||
for (const [lx, ly] of [[0.1, 0.1], [pp.w - 0.18, 0.1], [0.1, pp.d - 0.18], [pp.w - 0.18, pp.d - 0.18]]) {
|
||||
S.box(pp.x + lx, pp.y + ly, 0, 0.1, 0.1, 0.66, "#475569", { line: false })
|
||||
}
|
||||
S.box(pp.x, pp.y, 0.66, pp.w, pp.d, 0.09, "#1f7a4d")
|
||||
S.box(pp.x + 0.02, pp.y + 0.02, 0.75, pp.w - 0.04, pp.d - 0.04, 0.02, "#2fa96a", { line: false })
|
||||
// net across the width, dividing the two ends
|
||||
S.box(pp.x - 0.03, pp.y + pp.d / 2 - 0.03, 0.75, pp.w + 0.06, 0.06, 0.2, "#f8fafc")
|
||||
S.box(pp.x + 0.12, pp.y + pp.d / 2 - 0.015, 0.77, pp.w - 0.24, 0.03, 0.015, "#e2e8f0", { line: false })
|
||||
// paddles and a ball
|
||||
S.box(pp.x + 0.28, pp.y + 0.3, 0.78, 0.2, 0.14, 0.03, "#ef4444")
|
||||
S.box(pp.x + 1.42, pp.y + 0.62, 0.78, 0.2, 0.14, 0.03, "#3b82f6")
|
||||
S.box(pp.x + 0.95, pp.y + 0.42, 0.8, 0.05, 0.05, 0.05, "#fef08a", { line: false })
|
||||
})
|
||||
|
||||
// coffee / pantry: counter, machine, cups and a warm glow
|
||||
const cof = by("coffee")
|
||||
add(cof.x, cof.y, cof.w, cof.d, () => {
|
||||
S.box(cof.x, cof.y, 0, cof.w, cof.d, 0.92, "#8b5e3c")
|
||||
S.box(cof.x + 0.04, cof.y + 0.04, 0.92, cof.w - 0.08, cof.d - 0.08, 0.06, "#f5e6d3")
|
||||
S.box(cof.x + 0.14, cof.y + 0.1, 0.98, 0.46, 0.34, 0.5, "#334155")
|
||||
S.box(cof.x + 0.2, cof.y + 0.1, 1.14, 0.34, 0.02, 0.2, glow("#fb923c"), { line: false })
|
||||
S.box(cof.x + 0.26, cof.y + 0.58, 0.88, 0.14, 0.14, 0.1, "#e5e7eb", { line: false })
|
||||
for (let i = 0; i < 3; i++) S.box(cof.x + 0.86 + i * 0.14, cof.y + 0.34, 0.98, 0.09, 0.09, 0.13, ["#f8fafc", "#fcd34d", "#f472b6"][i], { line: false })
|
||||
// a jar shelf above the counter
|
||||
S.box(cof.x + 0.06, cof.y + 0.02, 1.7, cof.w - 0.12, 0.16, 0.06, "#6b4426")
|
||||
for (let i = 0; i < 4; i++) S.box(cof.x + 0.16 + i * 0.26, cof.y + 0.05, 1.76, 0.16, 0.12, 0.18, ["#ef4444", "#22c55e", "#f59e0b", "#3b82f6"][i], { line: false })
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// one calm cat: a slow pace along the shelf, a tail flick, a blink
|
||||
catAt() {
|
||||
const shelf = ACTIVITIES.find((a) => a.id === "bookshelf")
|
||||
const t = this.reducedMotion ? 0 : this.t
|
||||
const pace = 0.5 + 0.5 * Math.sin(t * 0.22 + (this.cat?.seed || 0))
|
||||
const x = shelf.x + 0.34 + pace * (shelf.w - 0.68)
|
||||
const y = shelf.y + shelf.d / 2
|
||||
const awake = !this.reducedMotion && Math.sin(t * 0.31) > -0.35
|
||||
return { x, y, z: 1.81, awake, tail: Math.sin(t * (awake ? 1.5 : 0.4)), pace }
|
||||
}
|
||||
|
||||
catOnShelf() {
|
||||
const cat = this.catAt()
|
||||
const { x, y, z } = cat
|
||||
// a bright cushion makes the cat readable on the dark shelf in both views
|
||||
this.box(x - 0.27, y - 0.17, z - 0.03, 0.54, 0.34, 0.05, "#f472b6")
|
||||
this.box(x - 0.21, y - 0.12, z + 0.01, 0.42, 0.24, 0.02, "#fda4af", { line: false })
|
||||
this.box(x - 0.17, y - 0.1, z, 0.34, 0.2, 0.12, "#fef3c7")
|
||||
this.box(x + 0.12, y - 0.07, z + 0.06, 0.17, 0.15, 0.13, "#fff7ed")
|
||||
this.box(x + 0.15, y - 0.05, z + 0.19, 0.04, 0.04, 0.07, "#f59e0b", { line: false })
|
||||
this.box(x + 0.25, y - 0.05, z + 0.19, 0.04, 0.04, 0.07, "#f59e0b", { line: false })
|
||||
// tabby stripes and a flicking tail
|
||||
this.box(x - 0.12, y - 0.1, z + 0.1, 0.06, 0.2, 0.025, "#f59e0b", { line: false })
|
||||
this.box(x - 0.02, y - 0.1, z + 0.1, 0.05, 0.2, 0.025, "#f59e0b", { line: false })
|
||||
this.box(x - 0.28, y + 0.02 + cat.tail * 0.04, z + 0.05, 0.13, 0.05, 0.05, "#f59e0b", { line: false })
|
||||
// closed eyes while dozing, dark slits while awake
|
||||
this.onFront(x + 0.15, y - 0.07, z + 0.06, 0.1, 0.14, 0.13, 0.2, cat.awake ? 0.42 : 0.44, 0.36, cat.awake ? 0.56 : 0.46, "#1f2937")
|
||||
this.onFront(x + 0.15, y - 0.07, z + 0.06, 0.1, 0.14, 0.13, 0.64, cat.awake ? 0.42 : 0.44, 0.8, cat.awake ? 0.56 : 0.46, "#1f2937")
|
||||
}
|
||||
|
||||
// the venues' names, in their own colours, above the furniture
|
||||
labels() {
|
||||
for (const a of ACTIVITIES) {
|
||||
const [x, y] = this.P(a.x + a.w / 2, a.y + a.d / 2, a.lz)
|
||||
this.text(globalThis.AgentOfficeModel?.text(this.lang)?.[({bookshelf:"venueReading",arcade:"venueArcade",meeting:"venueMeeting",pingpong:"venuePingpong",coffee:"venueCoffee"})[a.id]] || a.label, x, y, Math.max(7, this.s * 0.14), a.color, "800")
|
||||
}
|
||||
}
|
||||
|
||||
sofaLayer(front) {
|
||||
return { k: front ? this.depth(3.7, 11.7) : this.depth(1.1, 9.1), fn: () => {
|
||||
if (front) {
|
||||
@@ -625,9 +1037,18 @@
|
||||
} }
|
||||
}
|
||||
|
||||
// a worker's sofa slot, wherever its place came from: the old sofa kind
|
||||
// or an activity slot that happens to be a sofa seat
|
||||
sofaSlot(w) {
|
||||
if (w.kind === "sofa") return w.slot
|
||||
if (w.kind === "activity" && w.slot >= ACTIVITIES.length) return w.slot - ACTIVITIES.length
|
||||
return -1
|
||||
}
|
||||
|
||||
sofaGroup(w) {
|
||||
if (Number.isInteger(w.transit)) return w.transit >= 5 ? 1 : 0
|
||||
if (w.kind === "sofa" && !w.walking) return w.slot >= 5 ? 1 : 0
|
||||
const slot = this.sofaSlot(w)
|
||||
if (slot >= 0 && !w.walking) return slot >= 5 ? 1 : 0
|
||||
// The aisle is in front: a distant backrest must not cover its walkers.
|
||||
if (w.x >= 1.5 && w.x <= 2.5 && w.y >= 4.1 && w.y <= 9.1) return 0
|
||||
if (w.x >= 2.5 && w.x <= 4.9 && w.y >= 9.8 && w.y <= 10.55) return 1
|
||||
@@ -637,13 +1058,14 @@
|
||||
// ---- workers -------------------------------------------------------
|
||||
setAgents(list) {
|
||||
const seen = new Set()
|
||||
const used = { seat: new Set(), sofa: new Set(), zone: new Set(), err: new Set(), wander: new Set() }
|
||||
const kindOf = (a) => (a.status === "waiting" ? "zone" : a.status === "error" ? "err" : a.status === "done" ? "sofa" : "seat")
|
||||
const used = { seat: new Set(), sofa: new Set(), zone: new Set(), err: new Set(), activity: new Set(), wander: new Set() }
|
||||
const kindOf = (a) => (a.status === "waiting" ? "zone" : a.status === "error" ? "err" : a.status === "done" ? "activity" : "seat")
|
||||
const spots = {
|
||||
seat: DESKS.map((d) => [d.seat[0], d.seat[1], d.face || "n"]),
|
||||
sofa: SOFA.map(([x, y], i) => [x, y, SOFA_FACE[i]]),
|
||||
zone: ZONE_SPOTS.map(([x, y]) => [x, y, "s"]),
|
||||
err: ERROR_SPOTS.map(([x, y]) => [x, y, "s"]),
|
||||
activity: ACTIVITY_SPOTS,
|
||||
wander: WANDER.map(([x, y]) => [x, y, "s"]),
|
||||
}
|
||||
// the ones whose place is still theirs keep it
|
||||
@@ -683,6 +1105,7 @@
|
||||
used[kind].add(slot)
|
||||
w.kind = kind
|
||||
w.slot = slot
|
||||
w.lingerUntil = 0
|
||||
}
|
||||
const [tx, ty, facing] = spots[w.kind][w.slot]
|
||||
const to = tx + "," + ty
|
||||
@@ -692,6 +1115,35 @@
|
||||
if (w.x == null) { w.x = tx; w.y = ty }
|
||||
}
|
||||
for (const k of [...this.workers.keys()]) if (!seen.has(k)) this.workers.delete(k)
|
||||
// finished workers linger 8–30 s at a venue, then drift to another
|
||||
// free one; the timer is wall-clock so it only ticks in a live page
|
||||
const now = Date.now()
|
||||
for (const w of this.workers.values()) {
|
||||
if (w.kind !== "activity" || w.walking) continue
|
||||
if (!w.lingerUntil) {
|
||||
// start counting only once it has actually arrived at the venue
|
||||
if (Math.hypot(w.x - w.tx, w.y - w.ty) > 0.05) continue
|
||||
w.lingerUntil = now + activityDwell(w.a.seed || 0) * 1000
|
||||
continue
|
||||
}
|
||||
if (now < w.lingerUntil) continue
|
||||
const n = ACTIVITY_SPOTS.length
|
||||
let target = -1
|
||||
for (let i = 1; i <= n; i++) {
|
||||
const j = (w.slot + i) % n
|
||||
if (!used.activity.has(j)) { target = j; break }
|
||||
}
|
||||
if (target < 0) { w.lingerUntil = now + 4000; continue }
|
||||
used.activity.delete(w.slot)
|
||||
used.activity.add(target)
|
||||
w.slot = target
|
||||
const [tx, ty, facing] = ACTIVITY_SPOTS[target]
|
||||
w.tx = tx; w.ty = ty; w.facing = facing || "s"
|
||||
w.pathTo = tx + "," + ty
|
||||
w.path = null
|
||||
w.transit = null
|
||||
w.lingerUntil = 0
|
||||
}
|
||||
this.first = false
|
||||
this.atSeat = {}
|
||||
for (const w of this.workers.values()) if (w.kind === "seat") this.atSeat[w.slot] = w
|
||||
@@ -750,9 +1202,9 @@
|
||||
worker(w) {
|
||||
const S = this, t = this.t + w.phase, a = w.a
|
||||
const st = a.status
|
||||
const sitting = !w.walking && (w.kind === "seat" || w.kind === "sofa")
|
||||
const sitting = !w.walking && (w.kind === "seat" || this.sofaSlot(w) >= 0)
|
||||
const pose = idlePose(w, this.t, this.reducedMotion)
|
||||
const sleeping = sitting && w.kind === "sofa" && (a.idle || pose.kind === "doze")
|
||||
const sleeping = sitting && this.sofaSlot(w) >= 0 && (a.idle || pose.kind === "doze")
|
||||
const f0 = w.walking ? "s" : (w.facing || "s")
|
||||
let { x, y } = w
|
||||
let z = 0
|
||||
@@ -935,23 +1387,34 @@
|
||||
|
||||
draw() {
|
||||
const g = this.g
|
||||
this.dayState = this.currentPhase()
|
||||
g.clearRect(0, 0, this.W, this.H)
|
||||
this.background()
|
||||
this.floor()
|
||||
this.walls()
|
||||
this.ambient()
|
||||
const items = this.props()
|
||||
// a person sitting is ordered by the seat's front edge, not their
|
||||
// middle, so their legs are over the cushion and not inside it
|
||||
for (const w of this.workers.values()) {
|
||||
if (this.sofaGroup(w) >= 0) continue // boarding, seated, or alighting
|
||||
const sits = !w.walking && (w.kind === "seat" || w.kind === "sofa")
|
||||
const sits = !w.walking && (w.kind === "seat" || this.sofaSlot(w) >= 0)
|
||||
items.push({ k: this.depth(w.x, w.y + (sits ? 0.34 : 0)) + 0.02, fn: () => this.worker(w) })
|
||||
}
|
||||
items.sort((a, b) => a.k - b.k)
|
||||
for (const it of items) it.fn()
|
||||
this.labels()
|
||||
for (const w of this.workers.values()) this.bubble(w)
|
||||
const anchors = []
|
||||
for (const w of this.workers.values()) if (w.screen) anchors.push({ key: w.key, x: w.screen.x, y: w.screen.y - this.s * 0.25, r: w.screen.r, fx: w.screen.foot[0], fy: w.screen.foot[1] })
|
||||
const zoom = Number.isFinite(this.cam?.z) && this.cam.z > 0 ? this.cam.z : 1
|
||||
for (const w of this.workers.values()) if (w.screen) anchors.push({
|
||||
key: w.key,
|
||||
x: w.screen.x,
|
||||
y: w.screen.y - this.s * 0.25 * zoom,
|
||||
r: w.screen.r * zoom,
|
||||
fx: w.screen.foot[0],
|
||||
fy: w.screen.foot[1],
|
||||
})
|
||||
this.onFrame(anchors)
|
||||
}
|
||||
|
||||
@@ -983,5 +1446,10 @@
|
||||
}
|
||||
}
|
||||
|
||||
globalThis.AgentOfficeScene = { Scene, ROOM, DESKS, SOFA, ZONE, ZONE_SPOTS, NAV, BLOCKERS, SOFA_APPROACH, SOFA_FACE, DESKS, idlePose }
|
||||
globalThis.AgentOfficeScene = {
|
||||
Scene, ROOM, DESKS, SOFA, ZONE, ZONE_SPOTS, NAV, BLOCKERS, SOFA_APPROACH, SOFA_FACE, DESKS, idlePose,
|
||||
// activity venues and the new clock/camera helpers
|
||||
ACTIVITIES, POIS, POI_APPROACHES, ACTIVITY_SPOTS, SKY_PHASES, CAMERA,
|
||||
dayPhase, phaseOfHour, activityDwell,
|
||||
}
|
||||
})()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -12,15 +12,16 @@
|
||||
}
|
||||
[data-theme="dark"] { --sheet: #1c1c1f; }
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
/* the page paints no background of its own: magpie's shows through, so
|
||||
there is never a ring of a different colour at the frame's edge */
|
||||
html, body { margin: 0; height: 100%; background: transparent; color: var(--fg); }
|
||||
html, body { margin: 0; height: 100%; overflow: hidden; background: transparent; color: var(--fg); }
|
||||
/* no card around the page: it meets magpie's own background, so the
|
||||
window's inset shows no ring of a different colour */
|
||||
body { padding: 18px 24px 12px; font: 13px/1.45 var(--font); }
|
||||
button { font: inherit; color: inherit; }
|
||||
|
||||
.card { display: flex; flex-direction: column; height: 100%; min-height: 520px; }
|
||||
.card { display: flex; flex-direction: column; height: 100%; min-height: 0; }
|
||||
body.panel, .card { background: none; }
|
||||
.top { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; padding-bottom: 14px; border-bottom: 1px solid var(--line); }
|
||||
h1 { display: flex; align-items: center; gap: 10px; margin: 0; font-size: 21px; font-weight: 700; letter-spacing: -.01em; }
|
||||
@@ -37,9 +38,11 @@ h1 { display: flex; align-items: center; gap: 10px; margin: 0; font-size: 21px;
|
||||
.counts.alert .need i { animation: pulse 1.2s infinite; }
|
||||
@keyframes pulse { 50% { box-shadow: 0 0 0 5px rgba(245, 158, 11, .25); } }
|
||||
|
||||
.bar { display: flex; align-items: center; gap: 14px; padding: 14px 0; }
|
||||
.grow { flex: 1; }
|
||||
.note { color: var(--muted); font-size: 12px; }
|
||||
.bar { display: grid; grid-template-columns: max-content max-content minmax(0, 1fr) max-content; align-items: center; gap: 8px 14px; padding: 12px 0; }
|
||||
.bar > .grow { display: none; }
|
||||
.grow { flex: 1; min-width: 0; }
|
||||
.tools { display: flex; align-items: center; justify-content: flex-end; flex-wrap: nowrap; gap: 8px; margin-left: auto; }
|
||||
.note { color: var(--muted); font-size: 12px; min-width: 0; max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.seg { display: inline-flex; gap: 2px; padding: 3px; border-radius: 10px; }
|
||||
.seg button { border: 0; background: none; padding: 6px 15px; border-radius: 8px; color: var(--muted); font-size: 14px; cursor: pointer; }
|
||||
.seg.dark { background: var(--bg); border: 1px solid var(--line); }
|
||||
@@ -56,17 +59,18 @@ h1 { display: flex; align-items: center; gap: 10px; margin: 0; font-size: 21px;
|
||||
.btn.on { background: #1f1f22; color: #fff; }
|
||||
.chev { font-size: 11px; opacity: .6; margin-left: 2px; }
|
||||
.menu-wrap { position: relative; }
|
||||
.menu { position: absolute; right: 0; top: calc(100% + 6px); z-index: 20; width: 260px; padding: 8px; background: var(--bg); border: 1px solid var(--line); border-radius: 12px; box-shadow: 0 12px 30px rgba(0, 0, 0, .16); }
|
||||
.menu { position: fixed; right: auto; top: 0; z-index: 50; width: 260px; padding: 8px; background: var(--bg); border: 1px solid var(--line); border-radius: 12px; box-shadow: 0 12px 30px rgba(0, 0, 0, .16); }
|
||||
.menu .row { display: flex; align-items: center; gap: 8px; padding: 7px 8px; border-radius: 8px; cursor: pointer; }
|
||||
.menu .row:hover { background: var(--card); }
|
||||
.menu .row.col { flex-direction: column; align-items: flex-start; cursor: default; }
|
||||
.menu .row.col:hover { background: none; }
|
||||
|
||||
.stage { position: relative; flex: 1; min-height: 340px; border-radius: 14px; overflow: hidden; background: #05070f; }
|
||||
.stage { position: relative; flex: 1; min-height: 0; border-radius: 14px; overflow: hidden; background: #05070f; }
|
||||
.stage[hidden], .listview[hidden] { display: none; }
|
||||
canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
|
||||
canvas[hidden] { display: none; }
|
||||
.tags { position: absolute; inset: 0; pointer-events: none; }
|
||||
.tag { position: absolute; left: 0; top: 0; pointer-events: auto; display: inline-flex; align-items: center; gap: 6px; max-width: 220px; padding: 3px 10px 3px 4px; border: 0; border-radius: 999px; background: rgba(236, 238, 243, .9); color: #1f2937; font: 600 12px/1.3 var(--font); box-shadow: 0 2px 8px rgba(0, 0, 0, .35); cursor: pointer; white-space: nowrap; will-change: transform; transition: background .12s, box-shadow .12s; }
|
||||
.tag { position: absolute; left: 0; top: 0; pointer-events: auto; display: inline-flex; align-items: center; gap: 5px; max-width: 190px; padding: 2px 8px 2px 4px; border: 0; border-radius: 999px; background: rgba(236, 238, 243, .92); color: #1f2937; font: 600 11.5px/1.3 var(--font); box-shadow: 0 2px 8px rgba(0, 0, 0, .35); cursor: pointer; white-space: nowrap; will-change: transform; transition: background .12s, box-shadow .12s; }
|
||||
.tag[hidden] { display: none; } /* the rule above would otherwise show it */
|
||||
.tag .mark { flex: none; }
|
||||
.tag .tn { overflow: hidden; text-overflow: ellipsis; }
|
||||
@@ -158,10 +162,112 @@ footer { padding-top: 12px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.floatslot > .stage { position: absolute; inset: 0; min-height: 0; border-radius: 0; }
|
||||
.stage-slot { flex: 1; min-height: 340px; display: flex; align-items: center; justify-content: center; border: 1px dashed var(--line); border-radius: 14px; color: var(--muted); font-size: 13px; }
|
||||
|
||||
/* ---- workbench additions: grouped list, side rail, Today, transcript ---- */
|
||||
.menu.wide { width: 300px; max-height: min(72vh, 520px); overflow: auto; }
|
||||
.today-tokens { color: var(--muted); font-variant-numeric: tabular-nums; font-size: 12px; }
|
||||
.today-panel { width: min(340px, calc(100vw - 36px)); max-height: min(70vh, 480px); overflow: auto; }
|
||||
.today-big { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-bottom: 12px; }
|
||||
.today-big div { padding: 9px 10px; border: 1px solid var(--line); border-radius: 10px; }
|
||||
.today-big b { display: block; font-size: 19px; font-variant-numeric: tabular-nums; }
|
||||
.today-big span, .today-note, .today-head { font-size: 12px; color: var(--muted); }
|
||||
.today-head { margin: 12px 0 4px; font-weight: 600; }
|
||||
.today-row { display: flex; align-items: center; gap: 8px; font-size: 13px; padding: 4px 0; min-width: 0; }
|
||||
.today-row .trn { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.today-row .n { margin-left: auto; color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; font-size: 12px; }
|
||||
.today-note { margin-top: 12px; line-height: 1.5; }
|
||||
.ctx { display: flex; align-items: center; gap: 8px; font-size: 11.5px; color: var(--muted); padding: 3px 0; min-width: 0; }
|
||||
.ctx .cn { flex: none; max-width: 42%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ctx .bar { flex: 1; height: 4px; border-radius: 2px; background: var(--line); overflow: hidden; }
|
||||
.ctx .bar i { display: block; height: 100%; border-radius: 2px; background: var(--done); }
|
||||
.ctx .cp { flex: none; font-variant-numeric: tabular-nums; }
|
||||
.ctx.warn .bar i { background: var(--wait); }
|
||||
.ctx.full .bar i { background: var(--err); }
|
||||
.ctx.warn .cp { color: var(--wait); }
|
||||
.ctx.full .cp { color: var(--err); }
|
||||
|
||||
.agent-filter { display: flex; flex-direction: column; gap: 1px; max-height: 176px; overflow: auto; width: 100%; margin-top: 4px; }
|
||||
.agent-filter .af { display: flex; align-items: center; gap: 7px; padding: 4px 6px; border-radius: 7px; cursor: pointer; font-size: 12.5px; }
|
||||
.agent-filter .af:hover { background: var(--card); }
|
||||
.agent-filter .af input { margin: 0; accent-color: var(--accent); }
|
||||
.agent-filter .afn { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.agent-filter .afc { color: var(--muted); font-variant-numeric: tabular-nums; font-size: 11.5px; }
|
||||
.lang-select { width: 100%; margin-top: 6px; padding: 5px 8px; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); color: var(--fg); font: inherit; font-size: 13px; }
|
||||
|
||||
/* the list's three groups, as sticky-ish heading rows */
|
||||
tr.group td { background: var(--bg); color: var(--muted); font-size: 11px; font-weight: 700; letter-spacing: .06em; text-transform: uppercase; padding: 12px 14px 5px; border-bottom: 1px solid var(--line); }
|
||||
tr.group:hover { background: none; }
|
||||
tr.group .gcount { margin-left: 7px; font-weight: 500; color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
tr.group .gcount::before { content: "· "; }
|
||||
tr.group:hover td { background: var(--bg); }
|
||||
|
||||
/* the office's side rail: the same three groups, click to open the panel */
|
||||
.rail { position: absolute; z-index: 12; right: 26px; top: 152px; width: min(256px, 44%); max-height: calc(100% - 300px); display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--line); border-radius: 14px; background: color-mix(in srgb, var(--bg) 94%, transparent); box-shadow: 0 12px 34px rgba(0, 0, 0, .18); backdrop-filter: blur(6px); }
|
||||
.rail[hidden] { display: none; }
|
||||
.rail-head { display: flex; align-items: center; gap: 7px; padding: 8px 10px; border-bottom: 1px solid var(--line); color: var(--muted); font-size: 12px; font-weight: 600; }
|
||||
.rail-head b { color: var(--fg); font-variant-numeric: tabular-nums; }
|
||||
.rail-head .px { margin-left: 2px; }
|
||||
.rail-groups { overflow: auto; padding: 4px 6px 8px; }
|
||||
.rail-group { margin: 8px 6px 3px; color: var(--muted); font-size: 10.5px; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; }
|
||||
.rail-row { display: flex; align-items: center; gap: 7px; width: 100%; min-height: 27px; padding: 4px 6px; border: 0; border-radius: 8px; background: none; color: var(--fg); font: inherit; font-size: 12px; text-align: left; cursor: pointer; }
|
||||
.rail-row:hover { background: var(--card); }
|
||||
.rail-row .rn { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.rail-row .rs { flex: none; color: var(--muted); font-size: 10.5px; white-space: nowrap; }
|
||||
.rail-row.on { background: var(--accent-soft, rgba(79, 70, 229, .1)); }
|
||||
|
||||
/* context bar and the recent conversation inside the agent panel */
|
||||
.pctx { margin: 8px 0 2px; }
|
||||
.pconvo-h { margin: 10px 0 4px; color: #9ca3af; font-size: 11px; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; }
|
||||
.pconvo-h[hidden], .pmsgs[hidden] { display: none; }
|
||||
.pmsgs { max-height: 150px; overflow: auto; display: flex; flex-direction: column; gap: 6px; padding: 2px 0 4px; }
|
||||
.msg { font-size: 12.5px; line-height: 1.45; padding: 5px 8px; border-radius: 8px; background: #f3f4f6; color: #374151; overflow-wrap: anywhere; }
|
||||
.msg .mn { display: block; font-size: 10px; color: #9ca3af; font-weight: 700; letter-spacing: .03em; margin-bottom: 1px; text-transform: uppercase; }
|
||||
.msg .mt { float: right; color: #b0b5bd; font-size: 10px; margin-left: 6px; }
|
||||
.msg.user { background: rgba(79, 70, 229, .08); }
|
||||
.msg.assistant { background: rgba(16, 185, 129, .09); }
|
||||
.msg.tool { font-family: var(--mono); font-size: 11.5px; background: #f9fafb; color: #6b7280; }
|
||||
|
||||
/* in-page toast: magpie's frame has no Notification permission */
|
||||
.toasts { position: fixed; z-index: 80; right: 18px; bottom: 18px; display: flex; flex-direction: column; gap: 8px; max-width: min(350px, calc(100vw - 36px)); }
|
||||
.toasts:empty { display: none; }
|
||||
.toast { display: flex; align-items: center; gap: 9px; width: 100%; padding: 9px 12px; border: 1px solid var(--line); border-radius: 12px; background: var(--bg); color: var(--fg); box-shadow: 0 14px 38px rgba(0, 0, 0, .22); font: inherit; font-size: 12.5px; text-align: left; cursor: pointer; animation: toast-in .18s ease-out; }
|
||||
.toast::before { content: ""; flex: none; width: 6px; height: 6px; border-radius: 50%; background: var(--wait); }
|
||||
.toast.error::before { background: var(--err); }
|
||||
.toast .t-ico { flex: none; display: inline-flex; }
|
||||
.toast .tn { flex: 1; min-width: 0; }
|
||||
.toast .tn b { display: block; font-size: 12.5px; }
|
||||
.toast .tn span { display: block; color: var(--muted); font-size: 11.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
@keyframes toast-in { from { opacity: 0; transform: translateY(8px); } }
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.bar { grid-template-columns: max-content 1fr; }
|
||||
.tools { grid-column: 1 / -1; width: 100%; margin-left: 0; justify-content: flex-end; }
|
||||
.note { display: none; }
|
||||
.seg button { padding: 6px 11px; font-size: 13px; }
|
||||
.btn { padding: 6px 11px; font-size: 13px; }
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
body { padding: 8px; }
|
||||
.card { padding: 14px; }
|
||||
.card { padding: 0; }
|
||||
h1 { font-size: 18px; gap: 6px; flex-wrap: wrap; }
|
||||
.top { gap: 8px; padding-bottom: 8px; }
|
||||
.counts { flex-wrap: wrap; }
|
||||
.tools .btn { white-space: nowrap; }
|
||||
.counts { gap: 12px; font-size: 13px; }
|
||||
.bar { flex-wrap: wrap; }
|
||||
td.mono, th:nth-child(4), th:nth-child(5) { display: none; }
|
||||
|
||||
.menu.wide { width: min(300px, calc(100vw - 28px)); }
|
||||
}
|
||||
|
||||
@media (max-width: 440px) { .seg button { padding: 6px 8px; } .tools { justify-content: space-between; gap: 4px; } .btn { padding: 6px 8px; } .live { margin-left: 2px; } .counts { gap: 10px; } }
|
||||
|
||||
/* Detail panels use the same host theme as the page, including dark mode. */
|
||||
.pop { background: var(--bg); color: var(--fg); border: 1px solid var(--line); }
|
||||
.pop .pa, .pop .pq, .pop .pr { color: var(--fg); }
|
||||
.pop .pstep, .pop .msg, .pop .msg.tool { background: var(--card); color: var(--fg); }
|
||||
.pop .pw, .pop .pm, .pop .pc, .pop .psrc, .pop .pconvo-h, .pop .msg .mn, .pop .msg .mt { color: var(--muted); }
|
||||
.pop .msg.user { background: rgba(99, 102, 241, .12); }
|
||||
.pop .msg.assistant { background: rgba(16, 185, 129, .10); }
|
||||
.pop .pf { flex-wrap: wrap; }
|
||||
.pop .pm { flex: 1 1 120px; }
|
||||
|
||||
+3861
File diff suppressed because one or more lines are too long
@@ -43,7 +43,8 @@ function runHost(spec, options, after = "", where = "xdg") {
|
||||
const code = `const h = await import(${JSON.stringify(mod + "?privacy=" + Math.random())}); h.start(); ${after} h.stop(); h.write();`
|
||||
const env = { ...process.env, HOME: home, XDG_CONFIG_HOME: cfg, XDG_CACHE_HOME: join(home, ".cache"), MAGPIE_AGENT_OFFICE_PAGE: out }
|
||||
// an agent's own home override must not reach the sessions of the real user
|
||||
for (const k of ["CLAUDE_CONFIG_DIR", "CODEX_HOME", "DSH_HOME", "PI_CODING_AGENT_DIR", "QODER_CONFIG_DIR", "QODERCN_CONFIG_DIR", "WORKBUDDY_CONFIG_DIR", "CODEBUDDY_CONFIG_DIR", "GROK_HOME", "FACTORY_HOME_OVERRIDE", "CURSOR_CONFIG_DIR", "KIMI_CODE_HOME", "MINIMAX_DATA_DIR", "CLINE_SESSION_DATA_DIR", "CLINE_DATA_DIR", "CLINE_DIR"]) delete env[k]
|
||||
for (const k of ["CLAUDE_CONFIG_DIR", "CODEX_HOME", "DSH_HOME", "PI_CODING_AGENT_DIR", "QODER_CONFIG_DIR", "QODERCN_CONFIG_DIR", "WORKBUDDY_CONFIG_DIR", "CODEBUDDY_CONFIG_DIR", "GROK_HOME", "FACTORY_HOME_OVERRIDE", "CURSOR_CONFIG_DIR", "KIMI_CODE_HOME", "MINIMAX_DATA_DIR", "CLINE_SESSION_DATA_DIR", "CLINE_DATA_DIR", "CLINE_DIR",
|
||||
"COPILOT_HOME", "COPILOT_CONFIG_DIR", "KIMI_CODE_HOME", "KIMI_CONFIG_DIR", "GROK_HOME", "GROK_CONFIG_DIR", "OMP_HOME", "WMAD_OMP_SESSIONS_DIR"]) delete env[k]
|
||||
const r = spawnSync(process.execPath, ["-e", code], { cwd: where === "cwd" ? work : dir, env, encoding: "utf8" })
|
||||
if (r.status !== 0) throw new Error(`host run failed: ${r.stderr || r.stdout}`)
|
||||
return readFileSync(join(out, "live.js"), "utf8")
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
// The office's second dimension of life: activity venues, a camera you can
|
||||
// drag and zoom, and a room that follows the local clock. The scene's own
|
||||
// pathfinding is still the source of truth: every venue approach must be a
|
||||
// floor cell reachable from the airlock, never inside a blocker.
|
||||
import { test, expect } from 'bun:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
|
||||
const scope = {}
|
||||
new Function('globalThis', readFileSync(new URL('./page/scene.js', import.meta.url), 'utf8'))(scope)
|
||||
const S = scope.AgentOfficeScene
|
||||
const {
|
||||
Scene, ROOM, DESKS, SOFA, NAV, BLOCKERS, SOFA_APPROACH, SOFA_FACE,
|
||||
ACTIVITIES, POIS, POI_APPROACHES, ACTIVITY_SPOTS, CAMERA, dayPhase, activityDwell,
|
||||
} = S
|
||||
|
||||
const FACE = { n: [0, -1], s: [0, 1], e: [1, 0], w: [-1, 0] }
|
||||
const inside = ([x, y], [bx, by, bw, bd]) => x >= bx && x <= bx + bw && y >= by && y <= by + bd
|
||||
const door = [0.6, 2.6]
|
||||
|
||||
// every sampled point of a way must be a floor cell one may stand on
|
||||
const walkable = (pts) => {
|
||||
for (let i = 0; i < pts.length - 1; i++) {
|
||||
const [ax, ay] = pts[i], [bx, by] = pts[i + 1]
|
||||
const n = Math.max(1, Math.ceil(Math.hypot(bx - ax, by - ay) / 0.1))
|
||||
for (let k = 0; k <= n; k++) {
|
||||
const x = ax + ((bx - ax) * k) / n, y = ay + ((by - ay) * k) / n
|
||||
if (!NAV.freeAt(x, y)) return `blocked at ${x.toFixed(2)},${y.toFixed(2)}`
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
// ---- a canvas stub good enough for the real Scene ----------------------
|
||||
const fakeCtx = () => new Proxy({}, {
|
||||
get: (o, k) => (k in o ? o[k] : k === 'createLinearGradient' || k === 'createRadialGradient' ? () => ({ addColorStop() {} })
|
||||
: k === 'measureText' ? () => ({ width: 0 }) : () => {}),
|
||||
set: (o, k, v) => { o[k] = v; return true },
|
||||
})
|
||||
function fakeCanvas(w = 820, h = 620) {
|
||||
return {
|
||||
width: 0, height: 0, style: {},
|
||||
getContext: () => fakeCtx(),
|
||||
getBoundingClientRect: () => ({ width: w, height: h, left: 0, top: 0 }),
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
setPointerCapture: () => {},
|
||||
}
|
||||
}
|
||||
function newScene(dim = '3d') {
|
||||
const s = new Scene(fakeCanvas(), { dim })
|
||||
s.onFrame = () => {}
|
||||
return s
|
||||
}
|
||||
|
||||
// ---- venues -----------------------------------------------------------
|
||||
|
||||
test('the scene keeps its public API and gains the five venues', () => {
|
||||
for (const key of ['Scene', 'ROOM', 'DESKS', 'SOFA', 'ZONE', 'ZONE_SPOTS', 'NAV', 'BLOCKERS', 'SOFA_APPROACH', 'SOFA_FACE', 'idlePose']) {
|
||||
expect(S[key]).toBeDefined()
|
||||
}
|
||||
for (const key of ['ACTIVITIES', 'POIS', 'POI_APPROACHES', 'ACTIVITY_SPOTS', 'CAMERA', 'dayPhase', 'activityDwell']) {
|
||||
expect(S[key]).toBeDefined()
|
||||
}
|
||||
expect(POIS).toBe(ACTIVITIES)
|
||||
expect(ACTIVITIES.length).toBeGreaterThanOrEqual(5)
|
||||
expect(ACTIVITIES.map((a) => a.id)).toEqual(
|
||||
expect.arrayContaining(['coffee', 'pingpong', 'bookshelf', 'meeting', 'arcade']))
|
||||
// every venue is named, coloured and has one approach with a facing
|
||||
expect(POI_APPROACHES.length).toBe(ACTIVITIES.length)
|
||||
for (const a of ACTIVITIES) {
|
||||
expect(typeof a.label).toBe('string')
|
||||
expect(a.color).toMatch(/^#[0-9a-f]{6}$/i)
|
||||
expect([...'nsew']).toContain(a.face)
|
||||
expect(a.w).toBeGreaterThan(0)
|
||||
expect(a.d).toBeGreaterThan(0)
|
||||
}
|
||||
})
|
||||
|
||||
test('every venue is solid furniture with a free approach that faces it', () => {
|
||||
for (const [i, a] of ACTIVITIES.entries()) {
|
||||
// the body can't be walked through, and it is really in BLOCKERS
|
||||
expect(NAV.freeAt(a.x + a.w / 2, a.y + a.d / 2)).toBe(false)
|
||||
expect(BLOCKERS.some(([x, y, w, d]) => x === a.x && y === a.y && w === a.w && d === a.d)).toBe(true)
|
||||
// the approach is free, outside every blocker, and looks at the venue
|
||||
const [ax, ay, face] = POI_APPROACHES[i]
|
||||
expect(NAV.freeAt(ax, ay)).toBe(true)
|
||||
for (const b of BLOCKERS) expect(inside([ax, ay], b)).toBe(false)
|
||||
const v = FACE[face]
|
||||
const to = [a.x + a.w / 2 - ax, a.y + a.d / 2 - ay]
|
||||
expect(v[0] * to[0] + v[1] * to[1]).toBeGreaterThan(0.1)
|
||||
// the approach is on the camera-near side, so the worker is not hidden
|
||||
const near = ay > a.y + a.d - 0.2 || ax > a.x + a.w - 0.2
|
||||
expect(near).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
test('each venue is reachable from the airlock and from every other venue', () => {
|
||||
for (const [ax, ay] of POI_APPROACHES) {
|
||||
const pts = NAV.path(door, [ax, ay])
|
||||
expect(pts.length).toBeGreaterThan(0)
|
||||
expect(pts.at(-1).slice(0, 2)).toEqual([ax, ay])
|
||||
// no way through the furniture: the sampled floor path is all walkable
|
||||
expect(walkable([[door[0], door[1]], ...pts])).toBe('')
|
||||
}
|
||||
for (const from of POI_APPROACHES) for (const to of POI_APPROACHES) {
|
||||
if (from === to) continue
|
||||
const pts = NAV.path([from[0], from[1]], [to[0], to[1]])
|
||||
expect(pts.length).toBeGreaterThan(0)
|
||||
expect(walkable([[from[0], from[1]], ...pts])).toBe('')
|
||||
}
|
||||
// the old destinations still resolve from the door
|
||||
for (const seat of [...DESKS.map((d) => d.seat), ...SOFA_APPROACH]) {
|
||||
expect(NAV.path(door, seat).length).toBeGreaterThan(0)
|
||||
}
|
||||
})
|
||||
|
||||
test('venues do not clip the desks, sofas or other fittings', () => {
|
||||
const rects = [
|
||||
...ACTIVITIES.map((a) => [a.x, a.y, a.w, a.d]),
|
||||
...DESKS.map((d) => [d.x, d.y, d.w, d.d]),
|
||||
[0.35, 4.1, 1.2, 5.0], [2.5, 10.55, 2.4, 1.45], // sofa
|
||||
[6.3, 5.2, 1.6, 1.6], // holo table
|
||||
[1.85, 9.65, 0.9, 0.9], // drums
|
||||
[8.4, 10.5, 1.35, 1.25], // crates
|
||||
[12.65, 8.85, 1.2, 1.2], // reactor
|
||||
[14.3, 6.6, 1.2, 1.6], // broken console
|
||||
[14.0, 0.5, 1.6, 1.0], // far console
|
||||
]
|
||||
const overlap = (a, b) => a[0] < b[0] + b[2] && b[0] < a[0] + a[2] && a[1] < b[1] + b[3] && b[1] < a[1] + a[3]
|
||||
for (let i = 0; i < rects.length; i++) for (let j = i + 1; j < rects.length; j++) {
|
||||
expect(overlap(rects[i], rects[j])).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
// ---- finishing at a venue ---------------------------------------------
|
||||
|
||||
test('a finished worker takes a venue, faces it, and lingers 8–30 s', () => {
|
||||
const values = new Set()
|
||||
for (let seed = 0; seed < 300; seed++) {
|
||||
const wait = activityDwell(seed)
|
||||
expect(wait).toBeGreaterThanOrEqual(8)
|
||||
expect(wait).toBeLessThanOrEqual(30)
|
||||
values.add(wait)
|
||||
}
|
||||
expect(values.size).toBeGreaterThan(30)
|
||||
expect(activityDwell(7)).toBe(activityDwell(7))
|
||||
|
||||
for (let seed = 0; seed < ACTIVITIES.length; seed++) {
|
||||
const s = Object.create(Scene.prototype)
|
||||
Object.assign(s, { dim: '3d', workers: new Map(), first: true, t: 0, cam: undefined, reducedMotion: false })
|
||||
s.setAgents([{ key: 'p', seed, status: 'done', brand: { color: '#4f46e5' } }])
|
||||
const w = s.workers.get('p')
|
||||
expect(w.kind).toBe('activity')
|
||||
const spot = POI_APPROACHES.find(([x, y]) => x === w.tx && y === w.ty)
|
||||
expect(spot).toBeDefined()
|
||||
expect(w.facing).toBe(spot[2])
|
||||
expect(w.lingerUntil).toBeGreaterThan(Date.now())
|
||||
}
|
||||
})
|
||||
|
||||
// ---- camera ------------------------------------------------------------
|
||||
|
||||
test('the camera zooms about the pointer, pans, clamps and resets in both views', () => {
|
||||
for (const dim of ['2d', '3d']) {
|
||||
const s = newScene(dim)
|
||||
expect(s.cam).toEqual({ x: 0, y: 0, z: 1 })
|
||||
const base = s.P(8, 6)
|
||||
// zooming about the canvas centre doubles the distance from it
|
||||
s.zoomAt(s.W / 2, s.H / 2, 2)
|
||||
expect(s.cam.z).toBeCloseTo(2)
|
||||
const zoomed = s.P(8, 6)
|
||||
expect(zoomed[0] - s.W / 2).toBeCloseTo((base[0] - s.W / 2) * 2, 5)
|
||||
expect(zoomed[1] - s.H / 2).toBeCloseTo((base[1] - s.H / 2) * 2, 5)
|
||||
// panning is a screen-space shift, so anchors move with it
|
||||
s.panBy(25, -15)
|
||||
expect(s.P(8, 6)[0]).toBeCloseTo(zoomed[0] + 25, 5)
|
||||
expect(s.P(8, 6)[1]).toBeCloseTo(zoomed[1] - 15, 5)
|
||||
// a huge drag is clamped to the room, never lost off-canvas
|
||||
s.panBy(1e6, 1e6)
|
||||
const b = s.roomBox, z = s.cam.z
|
||||
const mx = Math.max(0, ((b.maxX - b.minX) * z - s.W) / 2) + s.W * CAMERA.panMargin
|
||||
const my = Math.max(0, ((b.maxY - b.minY) * z - s.H) / 2) + s.H * CAMERA.panMargin
|
||||
expect(s.cam.x).toBeCloseTo(mx, 4)
|
||||
expect(s.cam.y).toBeCloseTo(my, 4)
|
||||
// zoom is clamped, and a nonsense factor is ignored
|
||||
s.zoomAt(0, 0, 1000)
|
||||
expect(s.cam.z).toBe(CAMERA.maxZoom)
|
||||
s.zoomAt(0, 0, 0.0001)
|
||||
expect(s.cam.z).toBe(CAMERA.minZoom)
|
||||
s.zoomAt(0, 0, NaN)
|
||||
expect(s.cam.z).toBe(CAMERA.minZoom)
|
||||
// the keyboard reset and the Home key both land here
|
||||
s.resetCamera()
|
||||
expect(s.cam).toEqual({ x: 0, y: 0, z: 1 })
|
||||
expect(s.P(8, 6)[0]).toBeCloseTo(base[0], 6)
|
||||
expect(s.P(8, 6)[1]).toBeCloseTo(base[1], 6)
|
||||
}
|
||||
})
|
||||
|
||||
test('every anchor follows the camera transform', () => {
|
||||
const s = newScene('3d')
|
||||
let anchors = []
|
||||
s.onFrame = (a) => { anchors = a }
|
||||
s.setAgents([{ key: 'a', seed: 3, status: 'done', brand: { color: '#4f46e5' } }])
|
||||
s.draw()
|
||||
expect(anchors.length).toBe(1)
|
||||
const before = { ...anchors[0] }
|
||||
|
||||
s.panBy(30, 20)
|
||||
s.draw()
|
||||
expect(anchors[0].x).toBeCloseTo(before.x + 30, 5)
|
||||
expect(anchors[0].y).toBeCloseTo(before.y + 20, 5)
|
||||
expect(anchors[0].fx).toBeCloseTo(before.fx + 30, 5)
|
||||
expect(anchors[0].fy).toBeCloseTo(before.fy + 20, 5)
|
||||
|
||||
s.resetCamera()
|
||||
s.draw()
|
||||
const home = { ...anchors[0] }
|
||||
s.zoomAt(s.W / 2, s.H / 2, 1.5)
|
||||
s.draw()
|
||||
expect(anchors[0].x - s.W / 2).toBeCloseTo((home.x - s.W / 2) * 1.5, 5)
|
||||
expect(anchors[0].y - s.H / 2).toBeCloseTo((home.y - s.H / 2) * 1.5, 5)
|
||||
// the projected point under the anchor agrees with the worker
|
||||
const w = s.workers.get('a')
|
||||
expect(anchors[0].x).toBeCloseTo(w.screen.x, 5)
|
||||
expect(anchors[0].fy).toBeCloseTo(w.screen.foot[1], 5)
|
||||
})
|
||||
|
||||
// ---- local time --------------------------------------------------------
|
||||
|
||||
test('local time is a pure dawn/day/dusk/night palette', () => {
|
||||
expect(dayPhase(6).phase).toBe('dawn')
|
||||
expect(dayPhase(12).phase).toBe('day')
|
||||
expect(dayPhase(18).phase).toBe('dusk')
|
||||
expect(dayPhase(23).phase).toBe('night')
|
||||
// boundaries and wrap-around are deterministic
|
||||
expect(dayPhase(5).phase).toBe('dawn')
|
||||
expect(dayPhase(7.5).phase).toBe('day')
|
||||
expect(dayPhase(17).phase).toBe('dusk')
|
||||
expect(dayPhase(19.5).phase).toBe('night')
|
||||
expect(dayPhase(0).phase).toBe('night')
|
||||
expect(dayPhase(-1).phase).toBe('night')
|
||||
expect(dayPhase(36).phase).toBe(dayPhase(12).phase)
|
||||
// the same input always gives the same palette
|
||||
expect(dayPhase(6)).toEqual(dayPhase(6))
|
||||
const phases = ['dawn', 'day', 'dusk', 'night'].map((phase, i) => dayPhase([6, 12, 18, 23][i]))
|
||||
expect(new Set(phases.map((p) => p.phase)).size).toBe(4)
|
||||
expect(new Set(phases.map((p) => p.sky[0])).size).toBe(4)
|
||||
expect(new Set(phases.map((p) => p.glass)).size).toBe(4)
|
||||
for (const p of phases) {
|
||||
expect(p.sky).toHaveLength(2)
|
||||
expect(p.star).toBeGreaterThanOrEqual(0)
|
||||
expect(p.star).toBeLessThanOrEqual(1)
|
||||
expect(p.ambient).toMatch(/^rgba\(/)
|
||||
}
|
||||
expect(dayPhase(new Date(2026, 0, 15, 14, 30))).toMatchObject({ phase: 'day', hour: 14.5 })
|
||||
// the scene reads the clock, and an override makes its render testable
|
||||
const s = newScene('3d')
|
||||
s.phaseOverride = 12
|
||||
expect(s.currentPhase().phase).toBe('day')
|
||||
s.phaseOverride = 22
|
||||
expect(s.currentPhase().phase).toBe('night')
|
||||
})
|
||||
|
||||
// ---- drawing -----------------------------------------------------------
|
||||
|
||||
for (const dim of ['2d', '3d']) {
|
||||
test(`${dim}: venues, the cat and the clock draw without a real canvas`, () => {
|
||||
const s = newScene(dim)
|
||||
s.setAgents([
|
||||
{ key: 'done', seed: 3, status: 'done', brand: { color: '#4f46e5' }, idle: true },
|
||||
{ key: 'work', seed: 4, status: 'executing', brand: { color: '#0ea5e9' } },
|
||||
{ key: 'wait', seed: 5, status: 'waiting', brand: { color: '#f59e0b' } },
|
||||
])
|
||||
expect(() => { s.step(1 / 60); s.draw() }).not.toThrow()
|
||||
// the drawables include the five venue bodies plus every fitting
|
||||
expect(s.props().length).toBeGreaterThan(10)
|
||||
// both views project the room into the canvas
|
||||
for (const [x, y] of [[0, 0], [ROOM.w, 0], [ROOM.w, ROOM.d], [0, ROOM.d]]) {
|
||||
const [px, py] = s.P(x, y)
|
||||
expect(px).toBeGreaterThan(-s.W)
|
||||
expect(px).toBeLessThan(s.W * 2)
|
||||
expect(py).toBeGreaterThan(-s.H)
|
||||
expect(py).toBeLessThan(s.H * 2)
|
||||
}
|
||||
// every approach ring is projected inside the room's fitted box
|
||||
for (const [ax, ay] of POI_APPROACHES) {
|
||||
const [px, py] = s.P(ax, ay)
|
||||
expect(Number.isFinite(px) && Number.isFinite(py)).toBe(true)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
test('2D and isometric remain distinct projections', () => {
|
||||
const flat = newScene('2d'), iso = newScene('3d')
|
||||
expect(flat.P(4, 6)).not.toEqual(iso.P(4, 6))
|
||||
expect(flat.cam).toEqual(iso.cam)
|
||||
})
|
||||
@@ -0,0 +1,625 @@
|
||||
// Tests for the standalone 3D office renderer. These run in bun without a
|
||||
// browser, WebGL or network. Pure helpers also work without THREE; renderer
|
||||
// regressions use the bundled THREE and stub only the GPU boundary.
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { readFileSync, statSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
|
||||
const dir = import.meta.dir
|
||||
const page = join(dir, "page")
|
||||
const read = (file) => readFileSync(join(page, file), "utf8")
|
||||
|
||||
// Load the classic script the way the page does, with no THREE at all.
|
||||
const scope = {}
|
||||
new Function("globalThis", read("scene3d.js"))(scope)
|
||||
const S = scope.AgentOfficeScene3D
|
||||
|
||||
describe("bundle and registry", () => {
|
||||
test("three.js is bundled locally with its MIT notice", () => {
|
||||
const file = join(page, "three.min.js")
|
||||
const size = statSync(file).size
|
||||
const src = readFileSync(file, "utf8")
|
||||
expect(size).toBeGreaterThan(600000)
|
||||
expect(size).toBeLessThan(1000000)
|
||||
expect(src.startsWith("/*! three.js")).toBe(true)
|
||||
expect(src).toContain("MIT License")
|
||||
expect(src).toContain("Copyright © 2010-2024 three.js authors")
|
||||
expect(src).toContain("globalThis.THREE=THREE")
|
||||
expect(src).not.toMatch(/(?:src|href)\s*=\s*["']https?:/)
|
||||
// the bundled revision, checked without needing a browser
|
||||
const trio = {}
|
||||
new Function("globalThis", src)(trio)
|
||||
expect(trio.THREE.REVISION).toBe("169")
|
||||
})
|
||||
|
||||
test("scene3d.js carries the three.js license notice", () => {
|
||||
const src = read("scene3d.js")
|
||||
expect(src).toContain("three.js r169 is bundled in page/three.min.js under the MIT License")
|
||||
expect(src).toContain("Copyright © 2010-2024 three.js authors")
|
||||
})
|
||||
|
||||
test("six scenes are registered with palettes and props", () => {
|
||||
expect(S.SCENE_IDS).toEqual(["office", "station", "cafe", "castle", "pirate", "graveyard"])
|
||||
expect(Object.keys(S.SCENES).sort()).toEqual(S.SCENE_IDS.slice().sort())
|
||||
for (const id of S.SCENE_IDS) {
|
||||
const theme = S.SCENES[id]
|
||||
expect(theme.id).toBe(id)
|
||||
expect(theme.floor).toMatch(/^#[0-9a-f]{6}$/i)
|
||||
expect(theme.wall).toMatch(/^#[0-9a-f]{6}$/i)
|
||||
expect(theme.accent).toMatch(/^#[0-9a-f]{6}$/i)
|
||||
expect(Array.isArray(theme.props)).toBe(true)
|
||||
expect(theme.props.length).toBeGreaterThan(1)
|
||||
}
|
||||
for (const prop of ["coffee", "pingpong", "bookshelf", "whiteboard", "arcade"]) {
|
||||
expect(S.SCENES.office.props).toContain(prop)
|
||||
}
|
||||
})
|
||||
|
||||
test("public API is exposed", () => {
|
||||
expect(typeof S).toBe("function")
|
||||
expect(S.VERSION).toBe("1.0.0")
|
||||
for (const name of ["setAgents", "anchors", "setSelected", "resize", "dispose", "setScene", "setQuality"]) {
|
||||
expect(typeof S.prototype[name]).toBe("function")
|
||||
}
|
||||
expect(S.isSupported()).toBe(false) // bun: no document/WebGL
|
||||
})
|
||||
})
|
||||
|
||||
describe("degraded constructor", () => {
|
||||
test("no canvas, no WebGL, no throw", () => {
|
||||
const s = new S(null, { scene: "nope", quality: "nope" })
|
||||
expect(s.available).toBe(false)
|
||||
expect(s.id).toBe("office")
|
||||
expect(s.theme).toBe(S.SCENES.office)
|
||||
expect(s.anchors()).toEqual([])
|
||||
expect(() => {
|
||||
s.setAgents([null, undefined, 3, {}, { key: "" }, { key: "a" }])
|
||||
s.setSelected("a")
|
||||
s.resize()
|
||||
s.setScene("cafe")
|
||||
s.setQuality("low")
|
||||
s.setTime(new Date(2024, 0, 1, 12))
|
||||
s.dispose()
|
||||
}).not.toThrow()
|
||||
expect(s.id).toBe("cafe")
|
||||
expect(s.quality).toBe("low")
|
||||
expect(s.disposed).toBe(true)
|
||||
})
|
||||
|
||||
test("setAgents tolerates invalid lists and dedupes keys", () => {
|
||||
const s = new S()
|
||||
expect(() => s.setAgents(null)).not.toThrow()
|
||||
expect(() => s.setAgents("nope")).not.toThrow()
|
||||
s.setAgents([
|
||||
null,
|
||||
{ key: "one", status: "thinking" },
|
||||
{ key: "two" },
|
||||
{ key: "one", status: "done" },
|
||||
{ nope: true },
|
||||
{ key: 42, status: "waiting" },
|
||||
])
|
||||
expect(s.agents.map((a) => a.key)).toEqual(["one", "two", "42"])
|
||||
expect(s.agents[0].status).toBe("thinking")
|
||||
expect(s.anchors()).toEqual([])
|
||||
s.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe("layout and seats", () => {
|
||||
test("the layout is deterministic and inside the room", () => {
|
||||
expect(S.SPOTS.desk.length).toBe(8)
|
||||
expect(S.SPOTS.sofa.length).toBe(7)
|
||||
expect(S.SPOTS.zone.length).toBe(12)
|
||||
expect(S.SPOTS.error.length).toBe(4)
|
||||
expect(S.SPOTS.wander.length).toBe(9)
|
||||
for (const kind of Object.keys(S.SPOTS)) {
|
||||
for (const spot of S.SPOTS[kind]) {
|
||||
expect(spot.x).toBeGreaterThan(0.3)
|
||||
expect(spot.x).toBeLessThan(S.ROOM.w - 0.3)
|
||||
expect(spot.z).toBeGreaterThan(0.3)
|
||||
expect(spot.z).toBeLessThan(S.ROOM.d - 0.3)
|
||||
expect(["n", "s", "e", "w"]).toContain(spot.face)
|
||||
expect(Array.isArray(spot.route)).toBe(true)
|
||||
}
|
||||
}
|
||||
expect(S.seatFor("agent-one", "desk")).toBe(S.seatFor("agent-one", "desk"))
|
||||
expect(S.seatFor("agent-one", "desk").kind).toBe("desk")
|
||||
})
|
||||
|
||||
test("statuses map to the right room area", () => {
|
||||
expect(S.spotKindForStatus("thinking")).toBe("desk")
|
||||
expect(S.spotKindForStatus("executing")).toBe("desk")
|
||||
expect(S.spotKindForStatus("replying")).toBe("desk")
|
||||
expect(S.spotKindForStatus("waiting")).toBe("zone")
|
||||
expect(S.spotKindForStatus("error")).toBe("error")
|
||||
expect(S.spotKindForStatus("done")).toBe("sofa")
|
||||
expect(S.spotKindForStatus("idle")).toBe("wander")
|
||||
expect(S.spotKindForStatus("what")).toBe("wander")
|
||||
})
|
||||
|
||||
test("assignSeats never collides and follows status", () => {
|
||||
const list = []
|
||||
for (let i = 0; i < 20; i++) list.push({ key: "k" + i, status: ["thinking", "waiting", "error", "done", "idle"][i % 5] })
|
||||
const a = S.assignSeats(list)
|
||||
const b = S.assignSeats(list.slice().reverse())
|
||||
expect(a).toEqual(b)
|
||||
const ids = Object.values(a)
|
||||
expect(new Set(ids).size).toBe(ids.length)
|
||||
for (const [key, id] of Object.entries(a)) {
|
||||
const spot = S.SPOTS[S.spotKindForStatus(list.find((x) => x.key === key).status)].find((p) => p.id === id) ||
|
||||
Object.values(S.SPOTS).flat().find((p) => p.id === id)
|
||||
expect(spot).toBeTruthy()
|
||||
}
|
||||
// overflow spills over instead of stacking on one seat
|
||||
const crowd = []
|
||||
for (let i = 0; i < 14; i++) crowd.push({ key: "crowd" + i, status: "thinking" })
|
||||
const assigned = S.assignSeats(crowd)
|
||||
expect(new Set(Object.values(assigned)).size).toBe(14)
|
||||
expect(Object.keys(assigned).length).toBe(14)
|
||||
})
|
||||
|
||||
test("walk paths avoid walls, desks and props", () => {
|
||||
for (const kind of ["desk", "zone", "error", "wander"]) {
|
||||
for (const spot of S.SPOTS[kind]) {
|
||||
const hit = S.routeBlocked(spot.route)
|
||||
expect(hit, `${kind} ${spot.id} blocked at ${hit && hit.x.toFixed(2)},${hit && hit.z.toFixed(2)}`).toBeNull()
|
||||
}
|
||||
}
|
||||
// sofa routes end inside the sofa, so the last step is exempt
|
||||
for (const spot of S.SPOTS.sofa) expect(S.routeBlocked(spot.route, { ignoreLast: true })).toBeNull()
|
||||
// and a route through a desk is detected
|
||||
expect(S.routeBlocked([[4.05, 3.0], [4.05, 1.0]])).not.toBeNull()
|
||||
expect(S.routeBlocked([[1.0, 2.9], [10.0, 2.9]])).toBeNull()
|
||||
})
|
||||
|
||||
test("lane offsets keep the endpoints but separate aisle walkers", () => {
|
||||
const route = [[1, 1], [2, 1], [3, 2]]
|
||||
const shifted = S.laneRoute(route, 0.2)
|
||||
expect(shifted[0]).toEqual([1, 1])
|
||||
expect(shifted[shifted.length - 1]).toEqual([3, 2])
|
||||
expect(shifted[1]).not.toEqual([2, 1])
|
||||
expect(S.laneRoute(route, 0)).toEqual(route)
|
||||
})
|
||||
})
|
||||
|
||||
describe("pure math helpers", () => {
|
||||
test("camera zoom and polar clamps", () => {
|
||||
expect(S.clampZoom(0)).toBe(0.55)
|
||||
expect(S.clampZoom(99)).toBe(3)
|
||||
expect(S.clampZoom("x")).toBe(1.05)
|
||||
expect(S.clampPolar(-1)).toBe(0.35)
|
||||
expect(S.clampPolar(9)).toBe(1.42)
|
||||
expect(S.wrapAzimuth(0)).toBe(0)
|
||||
expect(S.wrapAzimuth(Math.PI * 3)).toBeCloseTo(-Math.PI, 5)
|
||||
expect(Math.abs(S.wrapAzimuth(-Math.PI * 3))).toBeCloseTo(Math.PI, 5)
|
||||
})
|
||||
|
||||
test("colour parsing and mixing", () => {
|
||||
expect(S.mixColor("#000000", "#ffffff", 0.5)).toBe("#808080")
|
||||
expect(S.mixColor("#ff0000", "#00ff00", 0)).toBe("#ff0000")
|
||||
expect(S.mixColor("#ff0000", "#00ff00", 1)).toBe("#00ff00")
|
||||
expect(S.mixColor("not-a-colour", "#ffffff", 1)).toBe("#ffffff")
|
||||
expect(S.colorToHex("hsl(0 100% 50%)")).toBe("#ff0000")
|
||||
expect(S.colorToHex("rgb(0, 128, 255)")).toBe("#0080ff")
|
||||
expect(S.colorToHex("nope", "#123456")).toBe("#123456")
|
||||
expect(S.parseColor("#abc")).toEqual([170, 187, 204])
|
||||
})
|
||||
|
||||
test("local time drives sky, sun and window tints", () => {
|
||||
const noon = S.timeOfDay(new Date(2024, 0, 1, 12, 0))
|
||||
const night = S.timeOfDay(new Date(2024, 0, 1, 2, 0))
|
||||
expect(noon.dayFactor).toBeGreaterThan(0.9)
|
||||
expect(night.dayFactor).toBeLessThan(0.1)
|
||||
expect(noon.sunIntensity).toBeGreaterThan(night.sunIntensity)
|
||||
expect(noon.sky).not.toBe(night.sky)
|
||||
expect(noon.window).not.toBe(night.window)
|
||||
expect(noon.hour).toBe(12)
|
||||
expect(night.phase).toBe("night")
|
||||
expect(S.timeOfDay("not a date").label).toBeTruthy()
|
||||
})
|
||||
|
||||
test("projectToScreen does the NDC -> CSS pixel math", () => {
|
||||
const project = (p) => ({ x: p.x, y: p.y, z: p.z })
|
||||
const center = S.projectToScreen({ x: 0, y: 0, z: 0 }, project, 1000, 500)
|
||||
expect(center).toEqual({ x: 500, y: 250, visible: true })
|
||||
const corner = S.projectToScreen({ x: 1, y: -1, z: 0.5 }, project, 1000, 500)
|
||||
expect(corner).toEqual({ x: 1000, y: 500, visible: true })
|
||||
const off = S.projectToScreen({ x: 0, y: 0, z: 2 }, project, 1000, 500)
|
||||
expect(off.visible).toBe(false)
|
||||
const outside = S.projectToScreen({ x: 2, y: 0, z: 0.5 }, project, 1000, 500)
|
||||
expect(outside.visible).toBe(false)
|
||||
expect(S.projectToScreen({ x: 0, y: 0, z: 0 }, { project: () => ({ x: NaN, y: 0, z: 0 }) }, 10, 10).visible).toBe(false)
|
||||
expect(S.projectToScreen(null, project, 10, 10)).toEqual({ x: 0, y: 0, visible: false })
|
||||
// a camera-like object works too
|
||||
const fakeCamera = { project: (p) => ({ x: p.x * 0.5, y: p.y * 0.5, z: 0 }) }
|
||||
expect(S.projectToScreen({ x: 0.5, y: 0.5, z: 0 }, fakeCamera, 200, 100)).toEqual({ x: 125, y: 37.5, visible: true })
|
||||
})
|
||||
})
|
||||
|
||||
// Exercise the shipped THREE scene graph, geometry, materials and projection.
|
||||
// Only the GPU boundary is stubbed; no renderer methods are bypassed.
|
||||
function threeFixture({ hidden = false, failRender = false, failInit = false } = {}) {
|
||||
class Events {
|
||||
constructor() { this.listeners = new Map() }
|
||||
addEventListener(type, fn) {
|
||||
if (!this.listeners.has(type)) this.listeners.set(type, new Set())
|
||||
this.listeners.get(type).add(fn)
|
||||
}
|
||||
removeEventListener(type, fn) { this.listeners.get(type)?.delete(fn) }
|
||||
emit(type, event = {}) { for (const fn of this.listeners.get(type) || []) fn(event) }
|
||||
}
|
||||
const canvas = new Events()
|
||||
Object.assign(canvas, {
|
||||
width: 300, height: 150, clientWidth: 800, clientHeight: 600,
|
||||
style: { touchAction: "auto" },
|
||||
getContext: () => ({}),
|
||||
getBoundingClientRect() { return { width: this.clientWidth, height: this.clientHeight } },
|
||||
setPointerCapture() {}, releasePointerCapture() {},
|
||||
})
|
||||
const document = new Events()
|
||||
document.hidden = hidden
|
||||
const ctx = new Proxy({}, { get(target, key) { return target[key] || (() => {}) }, set(target, key, value) { target[key] = value; return true } })
|
||||
document.createElement = () => ({ getContext: () => ctx })
|
||||
const callbacks = new Map()
|
||||
let serial = 0
|
||||
const world = new Events()
|
||||
Object.assign(world, {
|
||||
document, devicePixelRatio: 2,
|
||||
requestAnimationFrame(fn) { const id = ++serial; callbacks.set(id, fn); return id },
|
||||
cancelAnimationFrame(id) { callbacks.delete(id) },
|
||||
})
|
||||
new Function("globalThis", read("three.min.js"))(world)
|
||||
const T = world.THREE
|
||||
class Renderer {
|
||||
constructor(options) {
|
||||
this.options = options
|
||||
this.shadowMap = {}
|
||||
this.renders = 0
|
||||
this.dpr = 1
|
||||
this.disposed = false
|
||||
}
|
||||
getContext() { if (failInit) throw new Error("init failed"); return {} }
|
||||
setPixelRatio(dpr) { this.dpr = dpr }
|
||||
setSize(w, h) { canvas.width = Math.floor(w * this.dpr); canvas.height = Math.floor(h * this.dpr) }
|
||||
render(scene, camera) {
|
||||
if (failRender) throw new Error("render failed")
|
||||
this.renders++
|
||||
scene.updateMatrixWorld(true)
|
||||
camera.updateMatrixWorld(true)
|
||||
// Mirror renderer submissions: an InstancedMesh with one material is
|
||||
// one group, regardless of instance count. Hidden pose graphs submit none.
|
||||
this.workerDrawGroups = 0
|
||||
this.workerShadowGroups = 0
|
||||
this.workerInstances = 0
|
||||
scene.getObjectByName("workers").traverseVisible((object) => {
|
||||
if (!object.isMesh || (object.isInstancedMesh && object.count === 0)) return
|
||||
const groups = Array.isArray(object.material) ? object.geometry.groups.length : 1
|
||||
this.workerDrawGroups += groups
|
||||
if (object.castShadow) this.workerShadowGroups += groups
|
||||
this.workerInstances += object.isInstancedMesh ? object.count : 1
|
||||
})
|
||||
}
|
||||
dispose() { this.disposed = true }
|
||||
forceContextLoss() { this.lost = true }
|
||||
}
|
||||
world.THREE = { ...T, WebGLRenderer: Renderer }
|
||||
new Function("globalThis", "document", read("scene3d.js"))(world, document)
|
||||
const scene = new world.AgentOfficeScene3D(canvas)
|
||||
const frame = (now = 1000) => {
|
||||
const queued = [...callbacks.values()]
|
||||
callbacks.clear()
|
||||
for (const fn of queued) fn(now)
|
||||
}
|
||||
return { scene, canvas, document, callbacks, frame, T, world }
|
||||
}
|
||||
|
||||
function requireThree(fixture) {
|
||||
expect(fixture.scene.error).toBeNull()
|
||||
expect(fixture.scene.available).toBe(true)
|
||||
expect(fixture.scene.env.children.length).toBeGreaterThan(10)
|
||||
return fixture
|
||||
}
|
||||
|
||||
describe("THREE renderer path", () => {
|
||||
test("visibility resumes only an enabled renderer, including a queued stale frame", () => {
|
||||
const f = requireThree(threeFixture())
|
||||
let labels = 0
|
||||
f.scene.onFrame = () => labels++
|
||||
f.frame()
|
||||
expect(labels).toBe(1)
|
||||
const stale = [...f.callbacks.values()][0]
|
||||
f.scene.stop()
|
||||
f.document.hidden = true
|
||||
f.document.emit("visibilitychange")
|
||||
f.document.hidden = false
|
||||
f.document.emit("visibilitychange")
|
||||
stale(1100)
|
||||
expect(f.callbacks.size).toBe(0)
|
||||
expect(labels).toBe(1)
|
||||
f.scene.start()
|
||||
stale(1200)
|
||||
expect(f.callbacks.size).toBe(1)
|
||||
f.document.hidden = true
|
||||
f.document.emit("visibilitychange")
|
||||
expect(f.callbacks.size).toBe(0)
|
||||
f.document.hidden = false
|
||||
f.document.emit("visibilitychange")
|
||||
expect(f.callbacks.size).toBe(1)
|
||||
f.scene.dispose()
|
||||
f.document.emit("visibilitychange")
|
||||
expect(f.callbacks.size).toBe(0)
|
||||
})
|
||||
|
||||
test("initial hidden state and hidden resizes preserve CSS dimensions at DPR two", () => {
|
||||
const f = requireThree(threeFixture({ hidden: true }))
|
||||
expect(f.callbacks.size).toBe(0)
|
||||
expect(f.canvas.width).toBe(1600)
|
||||
f.canvas.clientWidth = f.canvas.clientHeight = 0
|
||||
for (let i = 0; i < 8; i++) f.scene.resize()
|
||||
expect([f.scene.width, f.scene.height]).toEqual([800, 600])
|
||||
expect([f.canvas.width, f.canvas.height]).toEqual([1600, 1200])
|
||||
f.scene.setQuality("low")
|
||||
expect([f.canvas.width, f.canvas.height]).toEqual([800, 600])
|
||||
expect(f.scene.renderer.options.antialias).toBe(true)
|
||||
expect(f.scene._lights.sun.shadow.mapSize.x).toBe(512)
|
||||
f.canvas.clientWidth = 640
|
||||
f.canvas.clientHeight = 480
|
||||
f.scene.setQuality("high")
|
||||
expect([f.canvas.width, f.canvas.height]).toEqual([1280, 960])
|
||||
expect(f.scene._lights.sun.shadow.mapSize.x).toBe(2048)
|
||||
f.scene.dispose()
|
||||
})
|
||||
|
||||
test("context loss suspends frames and restoration respects an intervening mode switch", () => {
|
||||
const f = requireThree(threeFixture())
|
||||
let prevented = false
|
||||
f.canvas.emit("webglcontextlost", { cancelable: true, preventDefault() { prevented = true } })
|
||||
expect(prevented).toBe(true)
|
||||
expect(f.callbacks.size).toBe(0)
|
||||
f.canvas.emit("webglcontextrestored")
|
||||
expect(f.callbacks.size).toBe(1)
|
||||
f.frame()
|
||||
expect(f.scene.renderer.renders).toBe(1)
|
||||
f.canvas.emit("webglcontextlost", { cancelable: false })
|
||||
f.scene.stop()
|
||||
f.canvas.emit("webglcontextrestored")
|
||||
expect(f.callbacks.size).toBe(0)
|
||||
const renderer = f.scene.renderer
|
||||
f.scene.dispose()
|
||||
expect(renderer.disposed).toBe(true)
|
||||
expect([...f.canvas.listeners.values()].every((set) => set.size === 0)).toBe(true)
|
||||
expect(f.canvas.style.touchAction).toBe("auto")
|
||||
})
|
||||
|
||||
test("GPU initialization and rendering failures release resources or stop scheduling", () => {
|
||||
const failed = threeFixture({ failInit: true })
|
||||
expect(failed.scene.available).toBe(false)
|
||||
expect(failed.scene.error.message).toBe("init failed")
|
||||
expect(failed.callbacks.size).toBe(0)
|
||||
expect(failed.scene.disposed).toBe(true)
|
||||
const f = requireThree(threeFixture({ failRender: true }))
|
||||
f.frame()
|
||||
expect(f.scene.error.message).toBe("render failed")
|
||||
expect(f.callbacks.size).toBe(0)
|
||||
f.scene.dispose()
|
||||
})
|
||||
|
||||
test("worker draw groups stay bounded for 32 articulated workers and retain colors and shadows", () => {
|
||||
const f = requireThree(threeFixture())
|
||||
const statuses = Object.keys(S.STATUS_COLORS)
|
||||
const crowd = Array.from({ length: 32 }, (_, i) => ({ key: `batch-${i}`, status: statuses[i % statuses.length], brand: { color: i % 2 ? "#ff2200" : "#2255ff" } }))
|
||||
f.scene.setAgents(crowd.slice(0, 1))
|
||||
f.frame(1000)
|
||||
expect(f.scene.renderer.workerDrawGroups).toBe(3)
|
||||
expect(f.scene.renderer.workerInstances).toBe(19)
|
||||
const only = f.scene._map.get("batch-0")
|
||||
const onlyBody = new f.T.Vector3(only.pos.x, 0.95, only.pos.z).project(f.scene.camera)
|
||||
expect(f.scene.hit((onlyBody.x + 1) * f.scene.width / 2, (1 - onlyBody.y) * f.scene.height / 2)).toBe("batch-0")
|
||||
expect(f.scene.anchors().map((a) => a.key)).toEqual(["batch-0"])
|
||||
f.scene.setAgents([{ ...crowd[0], status: "error" }])
|
||||
expect(f.scene._workerBatches.get("badge:" + new f.T.Color(S.STATUS_COLORS.thinking).getHexString()).count).toBe(0)
|
||||
const errorBadge = f.scene._workerBatches.get("badge:" + new f.T.Color(S.STATUS_COLORS.error).getHexString())
|
||||
expect(errorBadge.count).toBe(1)
|
||||
expect(errorBadge.material.emissive.getHexString()).toBe(new f.T.Color(S.STATUS_COLORS.error).getHexString())
|
||||
f.scene.setAgents(crowd)
|
||||
f.frame(1100)
|
||||
expect(f.scene.renderer.workerDrawGroups).toBe(2 + statuses.length)
|
||||
expect(f.scene.renderer.workerDrawGroups).toBeLessThan(10)
|
||||
expect(f.scene.renderer.workerShadowGroups).toBe(1)
|
||||
expect(f.scene.renderer.workerInstances).toBe(32 * 19)
|
||||
const matrix = new f.T.Matrix4(), color = new f.T.Color()
|
||||
const offsets = new Map()
|
||||
for (const rt of f.scene._map.values()) {
|
||||
expect(rt.group.visible).toBe(false)
|
||||
for (const mesh of rt.meshes) {
|
||||
const badge = mesh === rt.parts.badge
|
||||
const key = badge ? "badge:" + mesh.material.color.getHexString() : (mesh.castShadow ? "body" : "detail")
|
||||
const index = offsets.get(key) || 0
|
||||
offsets.set(key, index + 1)
|
||||
const batch = f.scene._workerBatches.get(key)
|
||||
expect(batch.isInstancedMesh).toBe(true)
|
||||
expect(batch.receiveShadow).toBe(mesh.receiveShadow)
|
||||
expect(batch.castShadow).toBe(mesh.castShadow)
|
||||
batch.getMatrixAt(index, matrix)
|
||||
matrix.elements.forEach((v, i) => expect(v).toBeCloseTo(mesh.matrixWorld.elements[i], 5))
|
||||
if (badge) {
|
||||
expect(batch.material).toBe(mesh.material)
|
||||
expect(batch.material.emissive.getHexString()).toBe(mesh.material.color.getHexString())
|
||||
expect(batch.material.emissiveIntensity).toBe(0.5)
|
||||
} else {
|
||||
expect(batch.material.color.getHexString()).toBe("ffffff")
|
||||
batch.getColorAt(index, color)
|
||||
expect(color.r).toBeCloseTo(mesh.material.color.r, 6)
|
||||
expect(color.g).toBeCloseTo(mesh.material.color.g, 6)
|
||||
expect(color.b).toBeCloseTo(mesh.material.color.b, 6)
|
||||
}
|
||||
}
|
||||
}
|
||||
const rt = f.scene._map.get("batch-0")
|
||||
const body = f.scene._workerBatches.get("body")
|
||||
const before = Array.from(body.instanceMatrix.array.slice(0, 16))
|
||||
const legBefore = rt.parts.legL.rotation.x
|
||||
const version = body.instanceMatrix.version
|
||||
f.frame(1200)
|
||||
expect(Array.from(body.instanceMatrix.array.slice(0, 16))).not.toEqual(before)
|
||||
expect(rt.parts.legL.rotation.x).not.toBe(legBefore)
|
||||
expect(body.instanceMatrix.version).toBeGreaterThan(version)
|
||||
body.getMatrixAt(0, matrix)
|
||||
matrix.elements.forEach((v, i) => expect(v).toBeCloseTo(rt.meshes[0].matrixWorld.elements[i], 5))
|
||||
expect(f.scene.anchors().length).toBe(32)
|
||||
const projected = new f.T.Vector3(rt.pos.x, 0.95, rt.pos.z).project(f.scene.camera)
|
||||
expect(f.scene.hit((projected.x + 1) * f.scene.width / 2, (1 - projected.y) * f.scene.height / 2)).toBeTruthy()
|
||||
f.scene.dispose()
|
||||
})
|
||||
|
||||
test("instance capacity grows for overlapping crowds and all instance resources dispose once", () => {
|
||||
const f = requireThree(threeFixture())
|
||||
const crowd = (prefix) => Array.from({ length: 32 }, (_, i) => ({ key: `${prefix}-${i}`, status: "waiting" }))
|
||||
f.scene.setAgents(crowd("old"))
|
||||
const replaced = f.scene._workerBatches.get("body")
|
||||
let replacementDisposals = 0
|
||||
replaced.addEventListener("dispose", () => replacementDisposals++)
|
||||
f.scene.setAgents(crowd("new"))
|
||||
expect(replacementDisposals).toBe(1)
|
||||
f.frame()
|
||||
expect(f.scene.renderer.workerInstances).toBe(64 * 19)
|
||||
expect(f.scene.renderer.workerDrawGroups).toBe(3)
|
||||
for (let i = 0; i < 500; i++) f.scene._updateWorkers(0.05)
|
||||
f.frame(1100)
|
||||
expect(f.scene.renderer.workerInstances).toBe(32 * 19)
|
||||
f.scene.setAgents([])
|
||||
for (let i = 0; i < 500; i++) f.scene._updateWorkers(0.05)
|
||||
f.frame(1200)
|
||||
expect(f.scene.renderer.workerDrawGroups).toBe(0)
|
||||
const resources = [...f.scene._workerBatches.values(), ...f.scene._sharedGeo, ...f.scene._sharedMat]
|
||||
const disposed = new Map(resources.map((r) => [r, 0]))
|
||||
for (const resource of resources) resource.addEventListener("dispose", () => disposed.set(resource, disposed.get(resource) + 1))
|
||||
const group = f.scene.workerGroup
|
||||
f.scene.dispose()
|
||||
f.scene.dispose()
|
||||
expect([...disposed.values()].every((count) => count === 1)).toBe(true)
|
||||
expect(group.children.length).toBe(0)
|
||||
expect(group.parent).toBeNull()
|
||||
expect(f.scene._workerBatches.size).toBe(0)
|
||||
expect(f.scene.workerGroup).toBeNull()
|
||||
expect(f.callbacks.size).toBe(0)
|
||||
})
|
||||
|
||||
test("32 workers receive distinct spots, walk to them, change status and leave", () => {
|
||||
const f = requireThree(threeFixture())
|
||||
const agents = Array.from({ length: 32 }, (_, i) => ({ key: `worker-${i}`, status: "executing" }))
|
||||
f.scene.setAgents(agents)
|
||||
expect(f.scene._map.size).toBe(32)
|
||||
expect(f.scene._taken.size).toBe(32)
|
||||
expect([...f.scene._map.values()].every((rt) => rt.spot && rt.group.children.length > 10)).toBe(true)
|
||||
for (let i = 0; i < 400; i++) f.scene._updateWorkers(0.05)
|
||||
const workers = [...f.scene._map.values()]
|
||||
expect(workers.every((rt) => rt.mode !== "walk")).toBe(true)
|
||||
expect(new Set(workers.map((rt) => `${rt.pos.x},${rt.pos.z}`)).size).toBe(32)
|
||||
expect(workers.every((rt) => rt.pos.x !== S.Layout.ENTRY[0] || rt.pos.z !== S.Layout.ENTRY[1])).toBe(true)
|
||||
f.scene.setAgents([{ key: "worker-0", status: "error" }])
|
||||
expect(f.scene._map.get("worker-0").spot.kind).toBe("error")
|
||||
expect(f.scene._taken.size).toBe(1)
|
||||
for (let i = 0; i < 500; i++) f.scene._updateWorkers(0.05)
|
||||
expect(f.scene._map.size).toBe(1)
|
||||
expect(f.scene._taken.size).toBe(1)
|
||||
f.frame()
|
||||
expect(f.scene.anchors().map((a) => a.key)).toEqual(["worker-0"])
|
||||
f.scene.dispose()
|
||||
expect(f.scene._sharedGeo.size).toBe(0)
|
||||
expect(f.scene._envTex.size).toBe(0)
|
||||
})
|
||||
|
||||
test("a full crowd can be replaced before departing workers finish leaving", () => {
|
||||
const f = requireThree(threeFixture())
|
||||
const crowd = (prefix) => Array.from({ length: 32 }, (_, i) => ({ key: `${prefix}-${i}`, status: "waiting" }))
|
||||
f.scene.setAgents(crowd("old"))
|
||||
for (let i = 0; i < 400; i++) f.scene._updateWorkers(0.05)
|
||||
f.scene.setAgents(crowd("new"))
|
||||
expect(f.scene._taken.size).toBe(32)
|
||||
const active = [...f.scene._map.values()].filter((rt) => !rt.leaving)
|
||||
expect(active.length).toBe(32)
|
||||
expect(active.every((rt) => rt.spot)).toBe(true)
|
||||
for (let i = 0; i < 500; i++) f.scene._updateWorkers(0.05)
|
||||
expect(f.scene._map.size).toBe(32)
|
||||
expect([...f.scene._map.values()].every((rt) => rt.mode !== "walk")).toBe(true)
|
||||
f.scene.dispose()
|
||||
})
|
||||
|
||||
test("six THREE environments keep decorations off seats and walking routes", () => {
|
||||
const f = requireThree(threeFixture())
|
||||
for (const id of S.SCENE_IDS) {
|
||||
const previous = f.scene.env
|
||||
f.scene.setScene(id)
|
||||
expect(previous.parent).toBeNull()
|
||||
expect(f.scene.env.children.length).toBeGreaterThan(10)
|
||||
for (const prop of S.SCENES[id].props) {
|
||||
const group = f.scene.env.getObjectByName("props:" + prop)
|
||||
expect(group.children.length).toBeGreaterThan(0)
|
||||
expect(group.children.every((object) => object.visible), `${id} retains ${prop}`).toBe(true)
|
||||
}
|
||||
f.scene.env.updateMatrixWorld(true)
|
||||
let checked = 0
|
||||
f.scene.env.traverse((object) => {
|
||||
if (!object.userData.decoration || !object.visible) return
|
||||
const bounds = new f.T.Box3()
|
||||
object.traverse((mesh) => {
|
||||
if (!mesh.isMesh) return
|
||||
const b = new f.T.Box3().setFromObject(mesh)
|
||||
if (b.max.y > 0.06 && b.min.y < 1.7) bounds.union(b)
|
||||
})
|
||||
checked++
|
||||
for (const pool of Object.values(S.SPOTS)) for (const spot of pool) {
|
||||
for (let i = 1; i < spot.route.length; i++) {
|
||||
const a = spot.route[i - 1], b = spot.route[i]
|
||||
const n = Math.max(1, Math.ceil(Math.hypot(a[0] - b[0], a[1] - b[1]) / 0.1))
|
||||
for (let j = 0; j <= n; j++) {
|
||||
const x = a[0] + (b[0] - a[0]) * j / n, z = a[1] + (b[1] - a[1]) * j / n
|
||||
const hit = x > bounds.min.x - 0.3 && x < bounds.max.x + 0.3 && z > bounds.min.z - 0.3 && z < bounds.max.z + 0.3
|
||||
if (hit) throw new Error(`${id} decoration intersects ${spot.id} route at ${x},${z}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
expect(checked).toBeGreaterThan(4)
|
||||
}
|
||||
f.scene.dispose()
|
||||
})
|
||||
|
||||
test("wheel consumes scrolling only when the active renderer can change zoom", () => {
|
||||
const f = requireThree(threeFixture())
|
||||
let prevented = 0
|
||||
const wheel = { deltaY: -100, deltaMode: 0, cancelable: true, preventDefault() { prevented++ } }
|
||||
f.scene.stop()
|
||||
f.canvas.emit("wheel", wheel)
|
||||
expect(prevented).toBe(0)
|
||||
f.scene.start().setZoom(3)
|
||||
f.canvas.emit("wheel", wheel)
|
||||
expect(prevented).toBe(0)
|
||||
f.canvas.emit("wheel", { ...wheel, deltaY: 100 })
|
||||
expect(prevented).toBe(1)
|
||||
expect(f.scene.zoom).toBeLessThan(3)
|
||||
f.scene.dispose()
|
||||
})
|
||||
|
||||
test("touch pinch zooms, single pointers orbit within the open walls, and cancellation resets", () => {
|
||||
const f = requireThree(threeFixture())
|
||||
const pointer = (pointerId, clientX, clientY = 100) => ({ pointerId, clientX, clientY, button: 0 })
|
||||
f.canvas.emit("pointerdown", pointer(1, 100))
|
||||
f.canvas.emit("pointerdown", pointer(2, 200))
|
||||
f.canvas.emit("pointermove", pointer(2, 300))
|
||||
expect(f.scene.zoom).toBeCloseTo(2.1)
|
||||
expect(f.scene.dragged).toBe(true)
|
||||
f.canvas.emit("pointerup", pointer(2, 300))
|
||||
f.canvas.emit("pointermove", pointer(1, 10000))
|
||||
expect(f.scene.azimuth).toBeGreaterThan(0)
|
||||
expect(f.scene.azimuth).toBeLessThan(Math.PI / 2)
|
||||
f.canvas.emit("pointermove", pointer(1, -10000))
|
||||
expect(f.scene.azimuth).toBeGreaterThan(0)
|
||||
expect(f.scene.azimuth).toBeLessThan(Math.PI / 2)
|
||||
f.canvas.emit("pointercancel", pointer(1, -10000))
|
||||
expect(f.scene._pointers.size).toBe(0)
|
||||
expect(f.scene._drag).toBeNull()
|
||||
f.scene.dispose()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
// Synthetic, local-only scan benchmark; no real agent logs or model calls.
|
||||
// bun scripts/bench-scan.mjs [size-in-MiB=100] [session-count=1]
|
||||
import { appendFileSync, closeSync, mkdtempSync, openSync, readSync, rmSync, statSync, writeSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join, resolve } from "node:path"
|
||||
import { performance } from "node:perf_hooks"
|
||||
import { createScanner } from "../lib/scan.mjs"
|
||||
const mib=Number(process.argv[2]||100),count=Number(process.argv[3]||1)
|
||||
if(!Number.isInteger(mib)||mib<1||mib>512||!Number.isInteger(count)||count<1||count>8)throw new Error("Use 1..512 MiB and 1..8 sessions")
|
||||
const root=mkdtempSync(join(tmpdir(),"office-scan-bench-")),paths=[]
|
||||
let bytes=0,calls=0
|
||||
const iso=new Date().toISOString(),json=x=>JSON.stringify(x)+"\n"
|
||||
const body=json({type:"assistant",timestamp:iso,message:{role:"assistant",content:[{type:"text",text:"x".repeat(3950)}],stop_reason:"end_turn"}})
|
||||
const block=Buffer.from(body.repeat(64))
|
||||
try {
|
||||
for(let i=0;i<count;i++) {
|
||||
const path=join(root,`session-${i}.jsonl`),fd=openSync(path,"w")
|
||||
try {for(let size=0;size<mib*1024*1024;size+=writeSync(fd,block)) {}}finally{closeSync(fd)}
|
||||
paths.push(path)
|
||||
}
|
||||
const scanner=createScanner({sources:[{agent:"claude",kind:"claude",root,depth:0,match:n=>n.endsWith(".jsonl")}],readSync(fd,b,o,l,p){const n=readSync(fd,b,o,l,p);bytes+=n;calls++;return n}})
|
||||
const sample=()=>{bytes=0;calls=0;const t=performance.now();const sessions=scanner.scan();return {ms:+(performance.now()-t).toFixed(3),bytes,calls,sessions:sessions.length}}
|
||||
const initial=sample(),unchanged=sample(),appends=[]
|
||||
for(let i=0;i<5;i++) {
|
||||
let expectedBytes=0
|
||||
for(const path of paths){const next=json({type:"user",timestamp:iso,message:{role:"user",content:`append-${i} `+"q".repeat(3900)}});appendFileSync(path,next);expectedBytes+=Buffer.byteLength(next)}
|
||||
const observed=sample();if(observed.bytes<expectedBytes||observed.bytes>expectedBytes+128*count)throw new Error(`Append read ${observed.bytes}, expected ${expectedBytes} + bounded guards`)
|
||||
appends.push({...observed,appendedBytes:expectedBytes,guardBytes:observed.bytes-expectedBytes})
|
||||
}
|
||||
console.log(JSON.stringify({sizeMiB:mib,sessionCount:count,totalBytes:paths.reduce((n,p)=>n+statSync(p).size,0),initial,unchanged,appends},null,2))
|
||||
} finally {
|
||||
const target=resolve(root),prefix=resolve(tmpdir())+"/office-scan-bench-"
|
||||
if(!target.startsWith(prefix))throw new Error("Unexpected benchmark cleanup path")
|
||||
rmSync(target,{recursive:true,force:true})
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Stamp local static URLs after changing browser files. magpie's page
|
||||
// entry is revalidated; content-addressed dependencies cannot mix an old
|
||||
// stylesheet or renderer with a new index after a same-version update.
|
||||
import {createHash} from 'node:crypto'
|
||||
import {readFileSync,writeFileSync} from 'node:fs'
|
||||
import {join} from 'node:path'
|
||||
const page=join(import.meta.dir,'../page'),file=join(page,'index.html')
|
||||
const html=readFileSync(file,'utf8')
|
||||
const next=html.replace(/(\b(?:src|href)=")([^"?]+\.(?:js|css))(?:\?v=[a-f0-9]+)?(")/g,(all,start,name,end)=>{
|
||||
if(name.startsWith('_magpie/'))return all
|
||||
const hash=createHash('sha256').update(readFileSync(join(page,name))).digest('hex').slice(0,12)
|
||||
return start+name+'?v='+hash+end
|
||||
})
|
||||
if(process.argv.includes('--check')) {
|
||||
if(next!==html){console.error('Page asset stamps are stale: bun scripts/stamp-page.mjs');process.exit(1)}
|
||||
} else if(next!==html)writeFileSync(file,next)
|
||||
@@ -0,0 +1,115 @@
|
||||
// Run against magpie web with this plugin installed from the checkout.
|
||||
// OFFICE_PLAYWRIGHT=/path/to/playwright/index.mjs OFFICE_HOST_URL='http://127.0.0.1:4571/?k=...' bun test/browser.mjs
|
||||
// Uses real host navigation, bridge, theme and sandbox. Only live.js is
|
||||
// replaced with synthetic prompts; no user sessions or model calls needed.
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdirSync } from 'node:fs'
|
||||
const { chromium, webkit } = await import(process.env.OFFICE_PLAYWRIGHT || 'playwright')
|
||||
const host=process.env.OFFICE_HOST_URL
|
||||
if(!host) throw new Error('Set OFFICE_HOST_URL to an authenticated magpie web URL')
|
||||
const output=process.env.OFFICE_QA_OUTPUT || '/tmp/agent-office-browser-qa'
|
||||
mkdirSync(output,{recursive:true})
|
||||
const now=Date.now(),marker='SECRET-PROMPT-123'
|
||||
const snapshot={v:2,written:now,text:true,sessions:Array.from({length:12},(_,i)=>({
|
||||
key:`qa|${i}`,agent:'claude',session:`qa-${i}`,source:'files',phase:i===0?'error':i===1?'thinking':'done',
|
||||
title:`${marker} 布局回归测试 ${i}`,query:`${marker} user`,reply:`${marker} reply`,error:i===0?`${marker} error`:'',
|
||||
project:'fixture',cwd:'/fixture',model:'fixture-model',updated:now-(i===0?2*3600e3:i*100),touched:now-(i===0?2*3600e3:i*100),
|
||||
turns:1,messages:[{role:'user',text:marker,at:now},{role:'assistant',text:marker,at:now}],
|
||||
}))}
|
||||
function overlap(a,b){return Math.min(a.right,b.right)-Math.max(a.left,b.left)>.5 && Math.min(a.bottom,b.bottom)-Math.max(a.top,b.top)>.5}
|
||||
for(const engine of (process.env.OFFICE_BROWSERS||'chromium,webkit').split(',')) {
|
||||
const type=engine==='webkit'?webkit:chromium
|
||||
const browser=await type.launch({headless:true,timeout:30000,...(engine==='chromium'?{executablePath:process.env.OFFICE_CHROME||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',args:['--use-angle=swiftshader','--enable-unsafe-swiftshader']}: {})})
|
||||
try {
|
||||
for(const [width,height] of [[600,620],[820,650],[1440,1000]]) {
|
||||
console.log(`START ${engine} ${width}x${height}`)
|
||||
const page=await browser.newPage({viewport:{width,height},deviceScaleFactor:2,colorScheme:'dark'})
|
||||
const errors=[];page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(m.type()==='error')errors.push(m.text())})
|
||||
await page.route('**/live.js*',route=>route.fulfill({contentType:'text/javascript',body:`globalThis.AgentOfficeLive=${JSON.stringify(snapshot)};`}))
|
||||
// magpie 0.1.2305 web emits scheme-less numeric-host CSP sources.
|
||||
// Chromium accepts them; WebKit rejects every resource. Optional test-only
|
||||
// normalization adds the existing response URL's scheme, keeping the same
|
||||
// exact host/path allowlist. It does not change the bridge or sandbox.
|
||||
if(engine==='webkit' && process.env.OFFICE_NORMALIZE_WEBKIT_CSP==='1') {
|
||||
await page.route('**/_magpie/plugin/**/index.html',async route=>{
|
||||
const response=await route.fetch()
|
||||
const headers=response.headers()
|
||||
const origin=new URL(route.request().url())
|
||||
headers['content-security-policy']=(headers['content-security-policy']||'').replaceAll(origin.host+'/_magpie/',origin.origin+'/_magpie/')
|
||||
await route.fulfill({response,headers})
|
||||
})
|
||||
console.log('WebKit test-only CSP URL-scheme normalization enabled')
|
||||
}
|
||||
await page.goto(host)
|
||||
await page.waitForTimeout(1000)
|
||||
await page.getByText('Agent 办公室',{exact:true}).click()
|
||||
await page.waitForSelector('iframe')
|
||||
let frame
|
||||
for(let attempt=0;attempt<5;attempt++) {
|
||||
const iframe=await page.waitForSelector('iframe')
|
||||
frame=await iframe.contentFrame()
|
||||
try {await frame.waitForFunction(()=>document.querySelector('#nDone')?.textContent==='10',{timeout:30000});break}
|
||||
catch(e){if(attempt===4||!e.message.includes('detached'))throw e;console.log('reacquire reloaded plugin frame')}
|
||||
}
|
||||
await frame.locator('#settingsBtn').click();await frame.locator('#optText').check();await frame.locator('#settingsBtn').click()
|
||||
const dimensions=await frame.evaluate(()=>({width:innerWidth,height:innerHeight,scroll:document.documentElement.scrollWidth,docHeight:document.documentElement.scrollHeight}))
|
||||
assert(dimensions.scroll<=dimensions.width+1,JSON.stringify(dimensions))
|
||||
assert(dimensions.docHeight<=dimensions.height+1,JSON.stringify(dimensions))
|
||||
for(const id of ['settings','todayMenu']) {
|
||||
await frame.locator(id==='settings'?'#settingsBtn':'#todayBtn').click()
|
||||
const bounds=await frame.locator('#'+id).evaluate(e=>{const r=e.getBoundingClientRect();return {left:r.left,right:r.right,top:r.top,bottom:r.bottom,w:innerWidth,h:innerHeight}})
|
||||
assert(bounds.left>=0&&bounds.right<=bounds.w+1&&bounds.top>=0&&bounds.bottom<=bounds.h+1,`${engine} menu ${JSON.stringify(bounds)}`)
|
||||
await page.screenshot({path:`${output}/${engine}-${width}-${id}.png`})
|
||||
await frame.locator(id==='settings'?'#settingsBtn':'#todayBtn').click()
|
||||
}
|
||||
// ISO/2D/list/3D plus background/foreground must not reactivate a hidden renderer.
|
||||
for(const dim of ['iso','2d','3d']) {
|
||||
await frame.locator(`[data-dim="${dim}"]`).click()
|
||||
await frame.evaluate(()=>{
|
||||
Object.defineProperty(document,'hidden',{value:true,configurable:true});document.dispatchEvent(new Event('visibilitychange'))
|
||||
Object.defineProperty(document,'hidden',{value:false,configurable:true});document.dispatchEvent(new Event('visibilitychange'))
|
||||
})
|
||||
await page.waitForTimeout(250)
|
||||
const boxes=await frame.locator('.tag:visible').evaluateAll(es=>es.map(e=>{const r=e.getBoundingClientRect();return {left:r.left,right:r.right,top:r.top,bottom:r.bottom}}))
|
||||
for(let i=0;i<boxes.length;i++)for(let j=i+1;j<boxes.length;j++)assert(!overlap(boxes[i],boxes[j]),`${engine} ${width} ${dim} label overlap`)
|
||||
}
|
||||
if(width===1440) {
|
||||
await frame.locator('#settingsBtn').click()
|
||||
for(const scene of ['office','station','cafe','castle','pirate','graveyard']) {
|
||||
await frame.locator('#optScene').selectOption(scene)
|
||||
for(const quality of ['low','medium','high']) {
|
||||
await frame.locator('#optQuality').selectOption(quality)
|
||||
await page.waitForTimeout(80)
|
||||
}
|
||||
}
|
||||
await frame.locator('#optScene').selectOption('office')
|
||||
await frame.locator('#optQuality').selectOption('medium')
|
||||
await frame.locator('#settingsBtn').click()
|
||||
}
|
||||
await frame.locator('[data-mode="list"]').click()
|
||||
const buffer=await frame.locator('#office3d').evaluate(e=>[e.width,e.height])
|
||||
await frame.evaluate(()=>{for(let i=0;i<5;i++)dispatchEvent(new Event('resize'));document.dispatchEvent(new Event('visibilitychange'))})
|
||||
assert.deepEqual(await frame.locator('#office3d').evaluate(e=>[e.width,e.height]),buffer)
|
||||
await frame.locator('[data-mode="office"]').click()
|
||||
await frame.locator('#settingsBtn').click();await frame.locator('[data-hide="1h"]').click();await frame.locator('[data-hide="6h"]').click();await frame.locator('#settingsBtn').click()
|
||||
assert.equal(await frame.locator('.toast').count(),0,'filtering must not replay old alerts')
|
||||
await frame.evaluate(()=>{const real=Date.now;Date.now=()=>real()+11*60e3})
|
||||
await frame.waitForFunction(()=>document.querySelector('#rows').textContent.includes(AgentOfficeModel.text(document.documentElement.lang).noProgress))
|
||||
if(!(await frame.locator('#rail').isVisible())) await frame.locator('#sideBtn').click()
|
||||
await frame.locator('.rail-row').first().click()
|
||||
assert(await frame.locator('#pop').innerText().then(t=>t.includes(marker)))
|
||||
await frame.locator('#settingsBtn').click()
|
||||
await frame.locator('#optText').uncheck()
|
||||
await frame.locator('#settingsBtn').click()
|
||||
const leak=await frame.locator('body').evaluate((body,marker)=>({text:body.textContent.includes(marker),attrs:[...body.querySelectorAll('*')].some(n=>[...n.attributes].some(a=>a.value.includes(marker)))}),marker)
|
||||
assert(!leak.text&&!leak.attrs,`${engine} stale private DOM ${JSON.stringify(leak)}`)
|
||||
await page.screenshot({path:`${output}/${engine}-${width}-privacy.png`})
|
||||
await frame.locator('#pop .px').click()
|
||||
assert(!(await frame.locator('#pop').textContent()).includes(marker),'closed panel retains no private messages')
|
||||
assert.deepEqual(errors,[],`${engine} page errors`)
|
||||
console.log(`${engine} ${width}x${height} DPR2 iframe ${dimensions.width}x${dimensions.height}: menus, labels, modes, privacy PASS`)
|
||||
await page.waitForTimeout(2800)
|
||||
await page.close()
|
||||
}
|
||||
} finally {await browser.close()}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Agent Office 3D — standalone harness</title>
|
||||
<style>
|
||||
:root { color-scheme: dark; --accent: #3b82f6; --panel: rgba(10, 16, 30, .82); --line: rgba(148, 163, 184, .22); }
|
||||
* { box-sizing: border-box; }
|
||||
html, body { height: 100%; margin: 0; }
|
||||
body {
|
||||
background: #05070f; color: #e5edf8; overflow: hidden;
|
||||
font: 13px/1.4 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
|
||||
}
|
||||
#stage { position: fixed; inset: 0; }
|
||||
canvas#office { position: absolute; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; touch-action: none; outline: none; }
|
||||
.tags { position: absolute; inset: 0; pointer-events: none; overflow: hidden; }
|
||||
.tag {
|
||||
position: absolute; left: 0; top: 0; pointer-events: auto; display: inline-flex; align-items: center; gap: 6px;
|
||||
max-width: 210px; padding: 3px 10px 3px 4px; border: 0; border-radius: 999px;
|
||||
background: rgba(236, 238, 243, .92); color: #1f2937; font: 600 12px/1.3 inherit;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, .4); cursor: pointer; white-space: nowrap;
|
||||
transform: translate(-50%, -100%); transition: background .12s, box-shadow .12s, opacity .12s;
|
||||
}
|
||||
.tag[hidden] { display: none; }
|
||||
.tag .mark { width: 20px; height: 20px; flex: none; display: grid; place-items: center; border-radius: 50%; background: var(--c, #64748b); color: #fff; font-size: 10px; font-weight: 800; }
|
||||
.tag .tn { overflow: hidden; text-overflow: ellipsis; }
|
||||
.tag .td { width: 6px; height: 6px; flex: none; border-radius: 50%; background: var(--c, #64748b); }
|
||||
.tag.on { background: #fff; box-shadow: 0 0 0 2px #fff, 0 0 0 4px var(--accent), 0 2px 8px rgba(0, 0, 0, .4); z-index: 3; }
|
||||
.tag[data-status="waiting"]:not(.on) { box-shadow: 0 0 0 2px #f59e0b, 0 2px 8px rgba(0,0,0,.4); }
|
||||
.tag[data-status="error"]:not(.on) { box-shadow: 0 0 0 2px #ef4444, 0 2px 8px rgba(0,0,0,.4); }
|
||||
|
||||
.panel {
|
||||
position: fixed; left: 16px; top: 16px; width: min(330px, calc(100vw - 32px)); padding: 14px;
|
||||
background: var(--panel); border: 1px solid var(--line); border-radius: 14px; backdrop-filter: blur(10px);
|
||||
box-shadow: 0 12px 34px rgba(0, 0, 0, .4); z-index: 10;
|
||||
}
|
||||
.panel h1 { margin: 0 0 2px; font-size: 15px; letter-spacing: .01em; }
|
||||
.panel p { margin: 0 0 10px; color: #94a3b8; font-size: 11.5px; }
|
||||
.row { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 7px; }
|
||||
.row.scenes { margin-top: 10px; }
|
||||
.btn {
|
||||
appearance: none; border: 1px solid var(--line); background: rgba(148, 163, 184, .08); color: #dbe5f3;
|
||||
border-radius: 8px; padding: 5px 9px; font: inherit; font-size: 11.5px; cursor: pointer;
|
||||
}
|
||||
.btn:hover { background: rgba(148, 163, 184, .16); }
|
||||
.btn.on { background: var(--accent); border-color: var(--accent); color: #fff; }
|
||||
.sep { height: 1px; background: var(--line); margin: 11px 0 3px; }
|
||||
.hint { position: fixed; left: 50%; bottom: 14px; transform: translateX(-50%); color: #9fb0c7; font-size: 11.5px; background: rgba(8, 13, 24, .74); border: 1px solid var(--line); padding: 6px 12px; border-radius: 999px; z-index: 10; }
|
||||
.badge { display: inline-flex; align-items: center; gap: 6px; color: #94a3b8; font-size: 11px; }
|
||||
.dot { width: 7px; height: 7px; border-radius: 50%; }
|
||||
#err {
|
||||
position: fixed; inset: 0; display: none; place-items: center; z-index: 20;
|
||||
background: radial-gradient(circle at 50% 35%, #16233d, #05070f 70%); text-align: center; padding: 24px;
|
||||
}
|
||||
#err.show { display: grid; }
|
||||
#err strong { display: block; margin-bottom: 6px; font-size: 16px; }
|
||||
#err span { color: #9fb0c7; font-size: 12.5px; max-width: 520px; }
|
||||
@media (max-width: 640px) { .panel { padding: 10px; } .panel p { display: none; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="stage">
|
||||
<canvas id="office" aria-label="3D agent office"></canvas>
|
||||
<div class="tags" id="tags"></div>
|
||||
</div>
|
||||
|
||||
<div class="panel">
|
||||
<h1>Agent Office <span style="color:#64748b;font-weight:500">3D harness</span></h1>
|
||||
<p>Procedural three.js office · offline · mock live data</p>
|
||||
<div class="row scenes" id="scenes"></div>
|
||||
<div class="sep"></div>
|
||||
<div class="row">
|
||||
<button class="btn" type="button" data-quality="high">High</button>
|
||||
<button class="btn" type="button" data-quality="medium">Medium</button>
|
||||
<button class="btn" type="button" data-quality="low">Low</button>
|
||||
<button class="btn" type="button" id="reset">Reset view</button>
|
||||
<button class="btn" type="button" id="night">Night</button>
|
||||
<button class="btn" type="button" id="day">Noon</button>
|
||||
</div>
|
||||
<div class="row" style="margin-top:10px;justify-content:space-between">
|
||||
<span class="badge"><i class="dot" style="background:#f59e0b"></i> waiting</span>
|
||||
<span class="badge"><i class="dot" style="background:#3b82f6"></i> working</span>
|
||||
<span class="badge"><i class="dot" style="background:#22a35a"></i> done</span>
|
||||
<span class="badge"><i class="dot" style="background:#ef4444"></i> error</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="hint">drag to orbit · wheel / pinch to zoom · double-click to reset · click a name tag</div>
|
||||
<div id="err"><div><strong>WebGL unavailable</strong><span id="errmsg">This harness needs a WebGL-capable browser.</span></div></div>
|
||||
|
||||
<script src="../page/three.min.js"></script>
|
||||
<script src="../page/scene3d.js"></script>
|
||||
<script>
|
||||
(function () {
|
||||
"use strict"
|
||||
var STATUS = { thinking: "#8b6cf6", executing: "#3b82f6", replying: "#10b981", waiting: "#f59e0b", done: "#22a35a", error: "#ef4444", idle: "#9ca3af" }
|
||||
var ICON = { done: "✓", error: "!", waiting: "?", thinking: "…", executing: "⟳", replying: "✎", idle: "·" }
|
||||
var MOCK = [
|
||||
{ key: "claude:7f2a", agent: "claude", brand: { name: "Claude", color: "#d97757" }, status: "thinking", sub: "", title: "Refactor the scene bridge", project: "agent-office", at: Date.now() - 12000, step: "reading page/scene.js", query: "factor the office renderer", reply: "" },
|
||||
{ key: "codex:2b91", agent: "codex", brand: { name: "Codex", color: "#10a37f" }, status: "executing", sub: "", title: "Run the acceptance checks", project: "magpie", at: Date.now() - 9000, step: "bun test scene3d.test.mjs", query: "", reply: "" },
|
||||
{ key: "dsh:ff03", agent: "deepseek-harness", brand: { name: "DeepSeek", color: "#4d6bfe" }, status: "replying", sub: "", title: "Draft the release note", project: "harness", at: Date.now() - 4000, step: "", query: "", reply: "All six rooms now render…" },
|
||||
{ key: "gemini:aa14", agent: "gemini-cli", brand: { name: "Gemini", color: "#4285f4" }, status: "waiting", sub: "approval", title: "Waiting to deploy the preview", project: "site", at: Date.now() - 60000, step: "bun run deploy --preview", query: "", reply: "" },
|
||||
{ key: "qwen:88cd", agent: "qwen-code", brand: { name: "Qwen", color: "#7c3aed" }, status: "done", sub: "", title: "Polish the animations", project: "office", at: Date.now() - 700000, step: "", query: "", reply: "Done — 18 poses tuned.", idle: false },
|
||||
{ key: "pi:104e", agent: "pi", brand: { name: "Pi", color: "#0ea5e9" }, status: "error", sub: "stuck", title: "Migrate the renderer", project: "legacy", at: Date.now() - 150000, step: "bun run migrate", error: "ETIMEDOUT after 120s" },
|
||||
{ key: "qoder:5f6g", agent: "qoder", brand: { name: "Qoder", color: "#f97316" }, status: "waiting", sub: "ask", title: "Pick a palette for the café", project: "office", at: Date.now() - 30000, step: "", query: "Warm amber or sage green?" },
|
||||
{ key: "buddy:7h8i", agent: "workbuddy", brand: { name: "WorkBuddy", color: "#14b8a6" }, status: "done", sub: "stopped", title: "Tidy the tag layout", project: "page", at: Date.now() - 3600000, idle: true },
|
||||
{ key: "omp:9j0k", agent: "omp", brand: { name: "omp", color: "#a855f7" }, status: "thinking", sub: "", title: "Measure the render budget", project: "perf", at: Date.now() - 20000, step: "profiling frame time" }
|
||||
]
|
||||
|
||||
var canvas = document.getElementById("office")
|
||||
var tagsEl = document.getElementById("tags")
|
||||
var scene = null
|
||||
var tags = new Map()
|
||||
var selected = null
|
||||
var scenes = document.getElementById("scenes")
|
||||
var sceneIds = (window.AgentOfficeScene3D && window.AgentOfficeScene3D.SCENE_IDS) || ["office"]
|
||||
var labels = { office: "Office", station: "Station", cafe: "Café", castle: "Castle", pirate: "Pirate", graveyard: "Graveyard" }
|
||||
|
||||
function fail(err) {
|
||||
document.getElementById("err").classList.add("show")
|
||||
document.getElementById("errmsg").textContent = String(err && err.message || err || "no WebGL") +
|
||||
" — page/scene3d.js still exposes pure helpers, but this harness needs a GPU context."
|
||||
}
|
||||
|
||||
try {
|
||||
if (!window.AgentOfficeScene3D) throw new Error("scene3d.js did not load")
|
||||
scene = new window.AgentOfficeScene3D(canvas, { scene: "office", quality: "high", agents: MOCK })
|
||||
window.scene3d = scene
|
||||
if (!scene.available) throw scene.error || new Error("WebGL context could not be created")
|
||||
} catch (err) {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
|
||||
for (var i = 0; i < sceneIds.length; i++) {
|
||||
(function (id) {
|
||||
var b = document.createElement("button")
|
||||
b.type = "button"
|
||||
b.className = "btn" + (id === "office" ? " on" : "")
|
||||
b.textContent = labels[id] || id
|
||||
b.dataset.scene = id
|
||||
b.addEventListener("click", function () {
|
||||
scene.setScene(id)
|
||||
var all = scenes.querySelectorAll("button")
|
||||
for (var k = 0; k < all.length; k++) all[k].classList.toggle("on", all[k] === b)
|
||||
})
|
||||
scenes.appendChild(b)
|
||||
})(sceneIds[i])
|
||||
}
|
||||
|
||||
var qualityButtons = document.querySelectorAll("[data-quality]")
|
||||
for (var q = 0; q < qualityButtons.length; q++) {
|
||||
qualityButtons[q].addEventListener("click", function (e) {
|
||||
scene.setQuality(e.target.dataset.quality)
|
||||
for (var k = 0; k < qualityButtons.length; k++) qualityButtons[k].classList.toggle("on", qualityButtons[k] === e.target)
|
||||
})
|
||||
qualityButtons[q].classList.toggle("on", qualityButtons[q].dataset.quality === "high")
|
||||
}
|
||||
document.getElementById("reset").addEventListener("click", function () {
|
||||
scene.azimuth = 0.82; scene.polar = 0.96; scene.zoom = 1.05; scene._applyCamera()
|
||||
})
|
||||
document.getElementById("night").addEventListener("click", function () { scene.setTime(new Date(2024, 0, 1, 2, 30)) })
|
||||
document.getElementById("day").addEventListener("click", function () { scene.setTime(new Date(2024, 0, 1, 12, 0)) })
|
||||
|
||||
var agents = new Map()
|
||||
for (var m = 0; m < MOCK.length; m++) agents.set(MOCK[m].key, MOCK[m])
|
||||
|
||||
function ensureTag(agent) {
|
||||
var e = tags.get(agent.key)
|
||||
if (e) return e
|
||||
e = document.createElement("button")
|
||||
e.type = "button"
|
||||
e.className = "tag"
|
||||
e.hidden = true
|
||||
e.dataset.key = agent.key
|
||||
var mark = document.createElement("span")
|
||||
mark.className = "mark"
|
||||
mark.textContent = (agent.brand && agent.brand.name || agent.agent || "?").slice(0, 1).toUpperCase()
|
||||
var name = document.createElement("span")
|
||||
name.className = "tn"
|
||||
name.textContent = (agent.brand && agent.brand.name || agent.agent || agent.key)
|
||||
var dot = document.createElement("i")
|
||||
dot.className = "td"
|
||||
e.append(mark, name, dot)
|
||||
e.style.setProperty("--c", (agent.brand && agent.brand.color) || STATUS[agent.status] || "#64748b")
|
||||
e.dataset.status = agent.status
|
||||
e.addEventListener("click", function () { selectTag(agent.key) })
|
||||
tagsEl.appendChild(e)
|
||||
tags.set(agent.key, e)
|
||||
return e
|
||||
}
|
||||
|
||||
function selectTag(key) {
|
||||
selected = selected === key ? null : key
|
||||
scene.setSelected(selected)
|
||||
tags.forEach(function (e, k) { e.classList.toggle("on", k === selected) })
|
||||
}
|
||||
|
||||
function frame() {
|
||||
requestAnimationFrame(frame)
|
||||
var anchors = scene.anchors()
|
||||
var shown = new Set()
|
||||
for (var i = 0; i < anchors.length; i++) {
|
||||
var a = anchors[i]
|
||||
var agent = agents.get(a.key)
|
||||
if (!agent) continue
|
||||
var e = ensureTag(agent)
|
||||
shown.add(a.key)
|
||||
e.hidden = !a.visible
|
||||
if (!a.visible) continue
|
||||
e.style.transform = "translate(" + Math.round(a.x) + "px," + Math.round(a.y) + "px) translate(-50%, -100%)"
|
||||
}
|
||||
tags.forEach(function (e, k) { if (!shown.has(k)) e.hidden = true })
|
||||
}
|
||||
requestAnimationFrame(frame)
|
||||
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+1
-1
@@ -107,7 +107,7 @@
|
||||
{ "package": "@magpie-community/page-chat", "name": "Chat", "kind": "page", "community": true,
|
||||
"summary": { "en": "A chat page in magpie's window by Magic_zero: talk to magpie's own models with your MCP servers, instructions and skills, images and LaTeX. Runs a local service on 127.0.0.1 that only its own page can use.", "zh": "Magic_zero 做的 magpie 窗口内「对话」页面:用 magpie 自己的模型聊天,带上你的 MCP 服务器、指令和技能,支持图片与 LaTeX。本地服务只在 127.0.0.1,只给自己的页面用。" } },
|
||||
{ "package": "@magpie-community/page-agent-office", "name": "Agent Office", "kind": "page", "community": true,
|
||||
"summary": { "en": "Reads the session files of Claude Code, Codex, DeepSeek Harness, Gemini CLI, Qwen Code, Pi, omp, Qoder, WorkBuddy and CodeBuddy on this computer (prompts, replies and tool commands; text can be turned off) and shows each session as a worker in a voxel space-station office (3D/2D) or a live list, with approvals, current steps and resume commands.", "zh": "读取本机 Claude Code、Codex、DeepSeek Harness、Gemini CLI、Qwen Code、Pi、omp、Qoder、WorkBuddy、CodeBuddy 的会话文件(含提问、回复与工具命令,可关闭文本),把每个会话画成方块太空站办公室里的小人(3D/2D)或实时列表,显示批准、当前步骤与续接命令。" } },
|
||||
"summary": { "en": "Reads the session files of Claude Code, Codex, Copilot CLI, Kimi Code, DeepSeek Harness, Gemini CLI, Qwen Code, Pi, omp, Qoder, WorkBuddy, CodeBuddy and Grok Build on this computer (prompts, replies and tool commands; text can be turned off). Shows them in a real WebGL 3D office with six scenes, an isometric/2D office, or a grouped workbench with Today usage, recent conversations and approvals.", "zh": "读取本机 Claude Code、Codex、Copilot CLI、Kimi Code、DeepSeek Harness、Gemini CLI、Qwen Code、Pi、omp、Qoder、WorkBuddy、CodeBuddy、Grok Build 的会话文件(含提问、回复与工具命令,可关闭文本),用真 3D 办公室(六种场景)、等距/2D 办公室或分组工作台展示,带今日用量、最近对话与批准状态。" } },
|
||||
{"package": "@magpie-community/agent-kimi-desktop", "name": "Kimi", "kind": "agent", "community": true, "summary": {"en": "Kimi desktop Work on Magpie's Agents page: select a model from Magpie, then disconnect to restore the original service. Not Kimi Code CLI.", "zh": "把普通 Kimi 桌面版 Work 接入 Magpie Agent 页,使用已配置的模型;断开恢复原连接。不是 Kimi Code CLI。"}},
|
||||
{ "package": "@magpie-community/hooks-mail-watch", "name": "Mail Watch", "kind": "middleware", "community": true,
|
||||
"summary": { "en": "Email alerts when a provider call fails or a quota window runs out: your own SMTP account, your own words in the mail, and your own list of what to watch, with cooldowns and an hourly cap so a bad hour stays bounded — plus an optional periodic usage digest.", "zh": "供应商调用失败或额度窗口用尽时发邮件提醒:用你自己的 SMTP 账号、自己的邮件文案、自己勾选的监控事项;同类事件冷却合并,另有每小时上限,糟糕的一小时不会失控;另可开启定期用量摘要。" } },
|
||||
|
||||
Reference in New Issue
Block a user