officepals 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/web/index.html ADDED
@@ -0,0 +1,2947 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
6
+ <title>officepals</title>
7
+ <style>
8
+ :root {
9
+ --panel: rgba(255, 255, 255, 0.62);
10
+ --line: rgba(120, 100, 160, 0.14);
11
+ --text: #3b3552;
12
+ --muted: #8a84a3;
13
+ --amber: #e8912d;
14
+ --red: #e5484d;
15
+ --mono: "SF Mono", "JetBrains Mono", Menlo, monospace;
16
+ }
17
+ * { box-sizing: border-box; margin: 0; padding: 0; }
18
+ html, body {
19
+ height: 100%;
20
+ overflow: hidden;
21
+ color: var(--text);
22
+ font-family: -apple-system, "SF Pro Rounded", "PingFang SC", "Helvetica Neue", sans-serif;
23
+ -webkit-font-smoothing: antialiased;
24
+ background:
25
+ radial-gradient(ellipse at 20% 10%, #fff3e3 0%, transparent 55%),
26
+ radial-gradient(ellipse at 85% 90%, #d9ecff 0%, transparent 55%),
27
+ linear-gradient(160deg, #ffe7d4 0%, #f3dcff 48%, #d3e8ff 100%);
28
+ }
29
+ /* Evening and night: a dusky layer over the page background (--night, 0–1). */
30
+ body::before {
31
+ content: ''; position: fixed; inset: 0; pointer-events: none;
32
+ background: linear-gradient(160deg, #8a84c4 0%, #9a88c2 48%, #7f98c8 100%);
33
+ opacity: calc(var(--night, 0) * 0.3);
34
+ }
35
+ #app { position: fixed; inset: 0; }
36
+ .hud { position: fixed; z-index: 10; pointer-events: none; }
37
+ .panel {
38
+ background: var(--panel);
39
+ backdrop-filter: blur(16px) saturate(160%);
40
+ -webkit-backdrop-filter: blur(16px) saturate(160%);
41
+ border: 1px solid rgba(255, 255, 255, 0.7);
42
+ border-radius: 18px;
43
+ box-shadow: 0 10px 30px rgba(110, 80, 160, 0.12);
44
+ }
45
+
46
+ #title { top: 22px; left: 26px; }
47
+ #title h1 { font-size: 22px; font-weight: 700; letter-spacing: 0.02em; }
48
+ #title h1 .dot { color: #a07bff; }
49
+ #title button, #pip-back {
50
+ pointer-events: auto; cursor: pointer; margin: 10px 0 0 6px; padding: 3px 10px; font-size: 11px; font-weight: 600;
51
+ border-radius: 999px; border: 1px solid rgba(160, 123, 255, 0.35); background: rgba(255, 255, 255, 0.7); color: #a07bff;
52
+ }
53
+ #title button:hover, #pip-back:hover { background: #fff; }
54
+ #title button:disabled { opacity: 0.45; cursor: not-allowed; }
55
+ #title button.on { color: #2f9e5b; border-color: rgba(47, 158, 91, 0.35); }
56
+ #pip-note { left: 50%; top: 50%; transform: translate(-50%, -50%); padding: 22px 28px; text-align: center; pointer-events: auto; }
57
+ #pip-back { font-size: 13px; padding: 6px 16px; margin-top: 12px; }
58
+ #pip-chip {
59
+ position: fixed; top: 8px; left: 8px; z-index: 10; padding: 4px 10px; border-radius: 999px; font-size: 12px; font-weight: 700;
60
+ background: rgba(255, 255, 255, 0.8); color: var(--muted); box-shadow: 0 3px 10px rgba(90, 60, 140, 0.15); pointer-events: none;
61
+ }
62
+ #pip-chip.alert { color: var(--red); background: rgba(255, 238, 238, 0.92); }
63
+ /* ?mini: the compact window browsers without Document Picture-in-Picture get. */
64
+ body.mini .hud { display: none !important; }
65
+ /* Small windows (?mini, the pop-out, a narrow main window): no text labels
66
+ over heads, so you can see what everyone is doing. */
67
+ body.compact .tag { display: none !important; }
68
+ /* The card for a coworker you clicked. */
69
+ #card { position: absolute; top: 112px; right: 26px; width: 300px; max-height: calc(100% - 280px); overflow: auto;
70
+ padding: 14px 16px 12px; z-index: 20; pointer-events: auto; font-size: 12.5px; }
71
+ #card .head { display: flex; align-items: center; gap: 7px; font-weight: 700; font-size: 14px; }
72
+ #card .head .dot { width: 9px; height: 9px; border-radius: 50%; flex: none; }
73
+ #card .head .nm { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
74
+ #card .head .proj { font-weight: 400; font-size: 11px; color: var(--muted); white-space: nowrap; }
75
+ #card .x { margin-left: auto; border: 0; background: none; font-size: 18px; line-height: 1; color: var(--muted); cursor: pointer; padding: 0 2px; }
76
+ #card .now { margin-top: 8px; color: #4a4560; }
77
+ #card .now.waiting { color: var(--amber); font-weight: 600; }
78
+ #card .task { margin-top: 3px; color: #7a6aa8; font-size: 12px; }
79
+ #card .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px 12px; margin-top: 11px; }
80
+ #card .k { display: block; font-size: 10.5px; color: var(--muted); }
81
+ #card .v { font-weight: 600; font-variant-numeric: tabular-nums; }
82
+ #card .steps { height: 4px; border-radius: 3px; background: #eee7f6; margin-top: 4px; overflow: hidden; }
83
+ #card .steps i { display: block; height: 100%; border-radius: 3px; }
84
+ #card .tools-title { margin-top: 12px; }
85
+ #card .chips { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 5px; }
86
+ #card .chip { padding: 2px 8px; border-radius: 999px; background: rgba(143, 134, 184, 0.13); font-size: 11.5px; white-space: nowrap; }
87
+ #card .chip b { font-weight: 600; color: var(--muted); margin-left: 3px; }
88
+ #card .none { color: var(--muted); font-size: 11.5px; margin-top: 4px; }
89
+ /* A narrow main window: below the title bar. The pop-out and ?mini have none. */
90
+ body.compact #card { top: 96px; right: 8px; left: 8px; width: auto; max-height: calc(100% - 104px); padding: 10px 12px; font-size: 11.5px; }
91
+ body.mini #card, body.pip #card { top: 8px; max-height: calc(100% - 16px); }
92
+ #title p { margin-top: 4px; font-size: 12.5px; color: var(--muted); }
93
+ #title .badge {
94
+ display: inline-block; margin-top: 10px; padding: 3px 10px; font-size: 11px; border-radius: 999px;
95
+ background: rgba(255, 255, 255, 0.7); color: var(--amber); border: 1px solid rgba(232, 145, 45, 0.25);
96
+ }
97
+
98
+ #stats { top: 22px; right: 26px; display: flex; gap: 10px; }
99
+ .stat { padding: 12px 16px; min-width: 104px; }
100
+ .stat .sub { font-size: 10.5px; color: var(--muted); margin-top: 2px; white-space: nowrap; }
101
+ .stat .sub:empty { display: none; }
102
+ .stat .k { font-size: 11px; color: var(--muted); }
103
+ .stat .v { margin-top: 4px; font-size: 24px; font-weight: 700; font-variant-numeric: tabular-nums; }
104
+ .stat .v small { font-size: 13px; font-weight: 600; color: var(--muted); cursor: help; }
105
+ .stat.alert { background: rgba(255, 236, 236, 0.8); border-color: rgba(229, 72, 77, 0.35); }
106
+ .stat.alert .v { color: var(--red); }
107
+
108
+ #log { left: 26px; bottom: 24px; width: 370px; padding: 14px 16px; }
109
+ #log h2, #approvals h2 { font-size: 12px; font-weight: 600; color: var(--muted); }
110
+ #log ul { list-style: none; margin-top: 6px; }
111
+ #log li {
112
+ font-size: 12px; line-height: 1.85; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
113
+ animation: in 0.35s ease-out;
114
+ }
115
+ #log li .t { color: #b3adc8; margin-right: 8px; font-family: var(--mono); font-size: 11px; }
116
+ @keyframes in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
117
+
118
+ #approvals { right: 26px; bottom: 24px; width: 320px; padding: 14px 16px; pointer-events: auto; }
119
+ #approvals .empty { margin-top: 8px; font-size: 12.5px; color: var(--muted); }
120
+ .req {
121
+ margin-top: 10px; padding: 10px 12px; border-radius: 14px; background: rgba(255, 255, 255, 0.75);
122
+ border: 1px solid rgba(232, 145, 45, 0.25);
123
+ display: grid; grid-template-columns: 1fr auto; gap: 3px 10px; align-items: center;
124
+ }
125
+ .req.hot { border-color: rgba(229, 72, 77, 0.5); background: rgba(255, 240, 240, 0.85); }
126
+ .req .who { font-size: 13px; font-weight: 700; }
127
+ .req .what { font-size: 11.5px; color: var(--muted); font-family: var(--mono); }
128
+ .req .waited { font-size: 11.5px; color: var(--amber); font-variant-numeric: tabular-nums; }
129
+ .risk { font-size: 11.5px; font-weight: 600; justify-self: start; padding: 1px 8px; border-radius: 999px; }
130
+ .risk.high { color: #c4383d; background: rgba(229, 72, 77, 0.12); }
131
+ .risk.medium { color: #b06a10; background: rgba(232, 145, 45, 0.14); }
132
+ .risk.low { color: #3f8f55; background: rgba(76, 175, 110, 0.13); }
133
+ #card .risk { display: inline-block; margin-top: 4px; }
134
+ .req.hot .waited { color: var(--red); }
135
+ .req button {
136
+ grid-column: 2; grid-row: 1 / span 3; cursor: pointer; border: 0; border-radius: 12px;
137
+ padding: 9px 16px; font-size: 13px; font-weight: 700; color: #fff;
138
+ background: linear-gradient(135deg, #ff9ec7, #a58bff);
139
+ box-shadow: 0 6px 16px rgba(165, 139, 255, 0.35); transition: transform 0.15s;
140
+ }
141
+ .req button:hover { transform: translateY(-1px) scale(1.03); }
142
+
143
+ @media (max-width: 1000px) {
144
+ #title h1 { font-size: 17px; }
145
+ #title p { display: none; }
146
+ #stats { top: auto; bottom: 18px; left: 18px; right: auto; }
147
+ .stat { padding: 8px 12px; min-width: 76px; }
148
+ .stat .v { font-size: 18px; }
149
+ #log { display: none; }
150
+ #approvals { width: 270px; right: 18px; bottom: 18px; }
151
+ }
152
+
153
+ #title .badge.live { color: #2f9e5b; border-color: rgba(47, 158, 91, 0.3); }
154
+ #title .badge.down { color: var(--red); border-color: rgba(229, 72, 77, 0.3); }
155
+ #empty { left: 50%; top: 50%; transform: translate(-50%, -50%); padding: 22px 28px; text-align: center; max-width: 420px; }
156
+ #empty b { font-size: 16px; }
157
+ #empty p { margin-top: 8px; font-size: 13px; color: var(--muted); line-height: 1.6; }
158
+ #empty .hint { font-size: 12px; }
159
+ #empty code { font-family: var(--mono); font-size: 11.5px; background: rgba(255, 255, 255, 0.7); padding: 1px 6px; border-radius: 6px; }
160
+ .req .go { grid-column: 2; grid-row: 1 / span 3; font-size: 12px; color: var(--muted); white-space: nowrap; }
161
+
162
+ /* Labels over the scene (CSS2DRenderer positions them with `transform`). */
163
+ .tag {
164
+ padding: 5px 10px 6px; border-radius: 12px; min-width: 96px; pointer-events: none;
165
+ background: rgba(255, 255, 255, 0.86); box-shadow: 0 4px 14px rgba(90, 60, 140, 0.16);
166
+ border: 1.5px solid transparent;
167
+ }
168
+ /* Lifted clear of another label: a thin line back down to its coworker. */
169
+ .tag.lifted::after {
170
+ content: ''; position: absolute; left: 50%; top: 100%; width: 1.5px; height: var(--lift, 0px);
171
+ background: linear-gradient(rgba(143, 134, 184, 0.55), rgba(143, 134, 184, 0.15)); transform: translateX(-50%);
172
+ }
173
+ /* In a crowd: just the name and what it's doing. */
174
+ .tag.squeezed { min-width: 0; padding: 3px 8px 4px; }
175
+ .tag.squeezed .task, .tag.squeezed .proj { display: none; }
176
+ .tag .name { font-size: 12px; font-weight: 700; display: flex; align-items: center; gap: 5px; }
177
+ .tag .dot { width: 7px; height: 7px; border-radius: 50%; }
178
+ .tag .status { font-size: 11px; color: var(--muted); white-space: nowrap; margin-top: 1px; max-width: 240px; display: flex; gap: 8px; }
179
+ .tag .status .st { overflow: hidden; text-overflow: ellipsis; min-width: 0; }
180
+ .tag .status .turn { margin-left: auto; flex: none; font-size: 10px; color: #b3adc8; font-variant-numeric: tabular-nums; }
181
+ .tag .status .turn.long { color: var(--amber); font-weight: 600; }
182
+ /* Which agent tool a coworker is (shown for anything but Claude Code). */
183
+ .prov { flex: none; font-size: 9.5px; font-weight: 700; letter-spacing: 0.02em; color: #2f7d6d; background: rgba(79, 190, 160, 0.16); padding: 0 5px; border-radius: 6px; }
184
+ .tag .nm { max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
185
+ .tag .proj { margin-left: auto; font-weight: 400; color: var(--muted); font-size: 10px; white-space: nowrap; max-width: 90px; overflow: hidden; text-overflow: ellipsis; }
186
+ .tag .task { font-size: 10.5px; color: #7a6aa8; white-space: nowrap; margin-top: 2px; max-width: 220px; overflow: hidden; text-overflow: ellipsis; }
187
+ .tag .bar { display: none; height: 4px; border-radius: 3px; background: #eee7f6; margin-top: 5px; overflow: hidden; }
188
+ .tag .bar i { display: block; height: 100%; border-radius: 3px; }
189
+ .tag.waiting { border-color: rgba(232, 145, 45, 0.45); }
190
+ .tag.waiting .bar { display: block; }
191
+ .tag.waiting .status { color: var(--amber); font-weight: 600; }
192
+ .tag.steaming, .tag.strike { border-color: rgba(229, 72, 77, 0.6); }
193
+ .tag.steaming .status, .tag.strike .status { color: var(--red); }
194
+ .tag.sub { min-width: 0; padding: 2px 7px; font-size: 10px; color: var(--muted); }
195
+ </style>
196
+ <script type="importmap">
197
+ { "imports": { "three": "/vendor/three/three.module.min.js" } }
198
+ </script>
199
+ </head>
200
+ <body>
201
+ <div id="app"></div>
202
+
203
+ <div id="title" class="hud">
204
+ <h1><span data-t="brand"></span> <span class="dot">·</span> officepals</h1>
205
+ <p data-t="subtitle"></p>
206
+ <span class="badge" id="mode-badge" data-t="connecting"></span>
207
+ <button id="lang-toggle" title="Language / 语言"></button>
208
+ <button id="alert-toggle"></button>
209
+ <button id="time-toggle"></button>
210
+ <button id="pip-toggle"></button>
211
+ </div>
212
+ <div id="stats" class="hud">
213
+ <div class="stat panel"><div class="k" data-t="statRun"></div><div class="v" id="s-run">0</div></div>
214
+ <div class="stat panel" id="s-wait-tile"><div class="k" data-t="statWait"></div><div class="v" id="s-wait">0</div></div>
215
+ <div class="stat panel" id="s-total-tile"><div class="k" data-t="statTotal"></div><div class="v" id="s-total">0</div><div class="sub" id="s-total-sub"></div></div>
216
+ </div>
217
+ <div id="log" class="hud panel"><h2 data-t="logTitle"></h2><ul id="log-list"></ul></div>
218
+ <div id="approvals" class="hud panel"><h2 data-t="approvalsTitle"></h2><div id="req-list"></div></div>
219
+ <div id="pip-note" class="hud panel" hidden>
220
+ <b data-t="pipActive"></b>
221
+ <p><button id="pip-back" data-t="pipBack"></button></p>
222
+ </div>
223
+ <div id="empty" class="hud panel" hidden>
224
+ <b data-t="emptyTitle"></b>
225
+ <p data-t="emptyBody"></p>
226
+ <p class="hint"><span data-t="emptyHint"></span> <code>npx officepals status</code></p>
227
+ </div>
228
+
229
+ <script type="module">
230
+ // three.js ships with the package (web/vendor/three), so the office works
231
+ // offline and loads nothing from third parties.
232
+ const THREE = await import('three');
233
+ const { kindOfTool, STAY_KINDS } = await import('/tool-kinds.js');
234
+
235
+ // ── Language: ?lang=en|zh, then the toggle's saved choice, then the browser ──
236
+ const LANG = (() => {
237
+ const q = new URLSearchParams(location.search).get('lang');
238
+ const saved = (localStorage.getItem('officepals-lang') ?? localStorage.getItem('cozy-agents-lang'));
239
+ const pick = q || saved || (navigator.language || 'en');
240
+ return pick.toLowerCase().startsWith('zh') ? 'zh' : 'en';
241
+ })();
242
+ const STRINGS = {
243
+ zh: {
244
+ brand: 'AI 小办公室',
245
+ subtitle: '每个 Claude Code 会话,都是办公室里的一位同事',
246
+ connecting: '连接中…', live: '● 实时 · 已连接', down: '● 连接断开,重连中…', demo: '演示数据 · 时间 ×8 加速',
247
+ statRun: '在岗', statWait: '等你中', statTotal: '今日干等',
248
+ logTitle: '办公室动态', approvalsTitle: '等你处理',
249
+ emptyTitle: '办公室还空着', emptyBody: '在终端里启动 Claude Code,你的 AI 同事就会来上班。', emptyHint: '已启动但没人来?确认 hooks 已安装:',
250
+ nameplate: '你的工位', strike: '罢工!',
251
+ mood: { calm: '✋ 等你批准', antsy: '💦 老板,在吗?', steaming: '💢 快点啊老板!', strike: '🪧 罢工中…' },
252
+ askCalm: '❓ 有个问题想问你',
253
+ tools: { Read: '📖 读', Grep: '🔍 搜', Glob: '🔍 找', LS: '📂 看目录', Edit: '⌨️ 改', MultiEdit: '⌨️ 改', Write: '📝 写', NotebookEdit: '⌨️ 改', Bash: '🖥 执行', BashOutput: '🖥 看输出', WebFetch: '🌐 查阅', WebSearch: '🌐 搜索', Task: '🧑‍🤝‍🧑 派活', Agent: '🧑‍🤝‍🧑 派活', TodoWrite: '🗒 列计划' },
254
+ cmds: { test: '🧪 跑测试', git: '🌿 git', install: '📦 装依赖', build: '🔨 构建', look: '👀 查看' },
255
+ kinds: { note: '🗒 更新任务清单', sum: '📋 写总结', ui: '🪟 整理窗口', msg: '💬 发消息', file: '📎 发文件给你', skill: '🧩 查技能',
256
+ stop: '🛑 停掉任务', watch: '👀 盯着输出', shot: '📸 截图', browse: '🌐 操作网页', repo: '🌿 处理 PR/Issue', db: '🗄 查数据库',
257
+ term: '🖥 终端', docs: '🌐 查资料', files: '📂 翻文件', session: '🧑‍🤝‍🧑 安排会话', bugs: '🐞 查线上报错', design: '🎨 看设计稿', other: '🔌 用工具' },
258
+ turnFor: (d) => `这一轮已经干了 ${d}`,
259
+ card: { turn: '这一轮', lastTurn: '上一轮用时', steps: '待办进度', waited: '等过你', onDuty: '在岗', tools: '这一轮用过的工具',
260
+ noTools: '这一轮还没用过工具', times: (n, d) => `${n} 次 · 共 ${d}`, never: '还没等过', none: '—', close: '关闭(Esc)',
261
+ waitingNow: (what, d) => `⏳ ${what} · 已等 ${d}` },
262
+ hours: (h, m) => `${h}小时${m ? m + '分' : ''}`,
263
+ statSub: (n, d) => `${n} 次 · 最长 ${d}`,
264
+ risk: { delete: '会删除文件', 'force-push': '强制推送,会覆盖远程历史', push: '推送到远程仓库', discard: '会丢掉没提交的改动',
265
+ publish: '会发布出去', sudo: '要管理员权限', 'pipe-shell': '下载脚本直接运行', perms: '改文件权限', kill: '结束进程',
266
+ 'db-drop': '删数据库表', deploy: '部署到线上', network: '联网', install: '安装依赖', 'read-only': '只是查看,不改东西',
267
+ git: 'git 操作', 'runs-code': '运行项目代码', 'sensitive-write': '改密钥或配置文件', 'sensitive-read': '读密钥或配置文件',
268
+ 'outside-write': '改项目外的文件', 'outside-read': '读项目外的文件', edit: '改项目里的文件', read: '读项目里的文件', web: '上网查资料' },
269
+ statTip: (turns, work) => `今天:等了你 ${'{w}'};完成 ${turns} 轮,干活 ${work}(重启也不清零)`,
270
+ writingPlan: '📝 在白板上写计划', goingHome: '👋 下班啦',
271
+ timeOffice: '🕘 办公室时间', timeReal: '🕰 现实时间', timeHint: '昼夜跟着什么走:办公室墙上的钟(1 分钟 = 1 小时,24 分钟一整天),或你电脑的真实时间。点一下切换',
272
+ idleActs: { sip: '☕ 喝杯咖啡,等你的下一个指令', lounge: '🛋 在沙发上歇会儿', stretch: '🙆 在窗边伸个懒腰', chat: '💬 和同事闲聊', doze: '💤 等太久,打个盹' }, boardCols: ['待办', '进行中', '已完成'],
273
+ testPass: (n) => `🧪 ${n} 的测试通过了 ✓`, testFail: (n) => `🧪 ${n} 的测试没通过 ✗`,
274
+ secs: (s) => `${s}秒`, mins: (m, s) => `${m}分${s ? s + '秒' : ''}`,
275
+ doneTitle: (n) => `${n} 干完了 ✅`, doneBody: (d) => `用时 ${d}`, doneLog: (n, d) => `✅ ${n} 干完了(用时 ${d})`,
276
+ justArrived: '刚到岗', thinking: '💭 思考中', newTask: '📝 接到新任务', idle: '☕ 等你的下一个指令', cheer: '🎉 好嘞,继续干活',
277
+ ask: { question: '有问题想问你', plan: '请你审批计划', permission: '需要你批准' },
278
+ gaveUp: (n, d) => `${n} 不等了(等了 ${d})`,
279
+ resolved: (kind, n, d) => `✓ 你${kind === 'question' ? '回答了' : '批准了'} ${n}(它等了 ${d})`,
280
+ allGood: '大家都在安心干活 ☕', waited: (d, m) => `已等 ${d} · ${m}`, goTerminal: '去终端处理 ↗', btnAnswer: '回答', btnApprove: '批准',
281
+ arrived: '来上班了 👋', left: '下班了', helper: '小助手', spawned: (t) => `派出小助手${t ? '「' + t + '」' : ''}`,
282
+ overflow: (n) => `另有 ${n} 个会话在排队,等空出位置`, planLabel: '审批计划', questionLabel: '回答问题',
283
+ demoHello: '☀️ 早上好!3 位 AI 同事已到岗', demoQuestion: '用 WebGL 还是 Canvas 2D?', demoSearch: 'three.js 阴影',
284
+ toggle: 'EN',
285
+ alertsOn: '🔔 提醒已开', alertsOff: '🔕 开启提醒', alertsSoundOnly: '🔔 提醒已开(仅声音)',
286
+ alertsHint: 'Agent 等你时提示音提醒;页面不在眼前时再弹系统通知',
287
+ notifyTitle: (n) => `${n} 在等你`, strikeTitle: (n) => `${n} 罢工了 🪧`, strikeBody: '已经等了 3 分钟,快去终端看看吧',
288
+ titleWaiting: (n) => `(${n}) 等你中 · officepals`,
289
+ pip: '⧉ 悬浮小窗', pipClose: '⧉ 收回小窗', pipUnsupported: '悬浮小窗需要 Chrome 或 Edge 116 以上版本',
290
+ pipHint: '把办公室缩成一个置顶小窗,写代码时余光就能看到', pipFallback: '这个浏览器不支持置顶,将在一个小窗口里打开(可以拖到屏幕角落)', pipActive: '办公室正在悬浮小窗里', pipBack: '收回到这里',
291
+ pipChip: (n) => (n ? `${n} 位在等你` : '大家都在干活'),
292
+ },
293
+ en: {
294
+ brand: 'Agent Office',
295
+ subtitle: 'Every Claude Code session is a coworker in your office',
296
+ connecting: 'Connecting…', live: '● Live', down: '● Disconnected, reconnecting…', demo: 'Demo data · time ×8',
297
+ statRun: 'On duty', statWait: 'Waiting on you', statTotal: 'Kept waiting',
298
+ logTitle: 'Office feed', approvalsTitle: 'Needs you',
299
+ emptyTitle: 'The office is empty', emptyBody: 'Start Claude Code in a terminal and your AI coworkers will clock in.', emptyHint: 'Started it and nobody came? Check the hooks:',
300
+ nameplate: 'YOUR DESK', strike: 'STRIKE!',
301
+ mood: { calm: '✋ Waiting for approval', antsy: '💦 Boss? You there?', steaming: '💢 Come ON, boss!', strike: '🪧 On strike…' },
302
+ askCalm: '❓ Got a question for you',
303
+ tools: { Read: '📖 Reading', Grep: '🔍 Searching', Glob: '🔍 Finding', LS: '📂 Listing', Edit: '⌨️ Editing', MultiEdit: '⌨️ Editing', Write: '📝 Writing', NotebookEdit: '⌨️ Editing', Bash: '🖥 Running', BashOutput: '🖥 Checking', WebFetch: '🌐 Reading', WebSearch: '🌐 Searching', Task: '🧑‍🤝‍🧑 Delegating', Agent: '🧑‍🤝‍🧑 Delegating', TodoWrite: '🗒 Planning' },
304
+ cmds: { test: '🧪 Testing', git: '🌿 git', install: '📦 Installing', build: '🔨 Building', look: '👀 Looking' },
305
+ kinds: { note: '🗒 Updating the plan', sum: '📋 Writing a summary', ui: '🪟 Arranging windows', msg: '💬 Messaging', file: '📎 Sending you a file',
306
+ skill: '🧩 Looking up a skill', stop: '🛑 Stopping a task', watch: '👀 Watching output', shot: '📸 Screenshot', browse: '🌐 Using a web page',
307
+ repo: '🌿 PRs & issues', db: '🗄 Querying a database', term: '🖥 Terminal', docs: '🌐 Reading docs', files: '📂 Going through files',
308
+ session: '🧑‍🤝‍🧑 Organising sessions', bugs: '🐞 Checking error reports', design: '🎨 Reading a design', other: '🔌 Using a tool' },
309
+ turnFor: (d) => `Working on this for ${d}`,
310
+ card: { turn: 'This turn', lastTurn: 'Last turn took', steps: 'To-do progress', waited: 'Waited on you', onDuty: 'On duty', tools: 'Tools used this turn',
311
+ noTools: 'No tools yet this turn', times: (n, d) => `${n}× · ${d} in all`, never: 'Never yet', none: '—', close: 'Close (Esc)',
312
+ waitingNow: (what, d) => `⏳ ${what} · waiting ${d}` },
313
+ hours: (h, m) => `${h}h${m ? ' ' + m + 'm' : ''}`,
314
+ statSub: (n, d) => `${n}× · longest ${d}`,
315
+ risk: { delete: 'Deletes files', 'force-push': 'Force-push: rewrites remote history', push: 'Pushes to the remote', discard: 'Throws away uncommitted changes',
316
+ publish: 'Publishes', sudo: 'Needs admin rights', 'pipe-shell': 'Runs a downloaded script', perms: 'Changes file permissions', kill: 'Stops a process',
317
+ 'db-drop': 'Drops a database table', deploy: 'Deploys to production', network: 'Goes online', install: 'Installs packages', 'read-only': 'Just looks, changes nothing',
318
+ git: 'A git command', 'runs-code': "Runs the project's code", 'sensitive-write': 'Edits keys or config', 'sensitive-read': 'Reads keys or config',
319
+ 'outside-write': 'Edits a file outside the project', 'outside-read': 'Reads a file outside the project', edit: 'Edits a project file', read: 'Reads a project file', web: 'Looks something up online' },
320
+ statTip: (turns, work) => `Today: kept waiting ${'{w}'}; ${turns} turns finished, ${work} of work (kept across restarts)`,
321
+ writingPlan: '📝 Writing the plan on the board', goingHome: '👋 Heading home',
322
+ timeOffice: '🕘 Office time', timeReal: '🕰 Real time', timeHint: "What day and night follow: the office's wall clock (a minute an hour, a day in 24 minutes) or your computer's time. Click to switch",
323
+ idleActs: { sip: '☕ Coffee, waiting for your next prompt', lounge: '🛋 Taking a break on the sofa', stretch: '🙆 Stretching by the window', chat: '💬 Chatting with a coworker', doze: '💤 Waited so long it dozed off' }, boardCols: ['To do', 'Doing', 'Done'],
324
+ testPass: (n) => `🧪 ${n}'s tests passed ✓`, testFail: (n) => `🧪 ${n}'s tests failed ✗`,
325
+ secs: (s) => `${s}s`, mins: (m, s) => `${m}m${s ? ' ' + s + 's' : ''}`,
326
+ doneTitle: (n) => `${n} is done ✅`, doneBody: (d) => `Took ${d}`, doneLog: (n, d) => `✅ ${n} finished (took ${d})`,
327
+ justArrived: 'Just arrived', thinking: '💭 Thinking', newTask: '📝 New task', idle: '☕ Waiting for your next prompt', cheer: '🎉 Thanks! Back to work',
328
+ ask: { question: 'has a question for you', plan: 'wants a plan approved', permission: 'needs your approval' },
329
+ gaveUp: (n, d) => `${n} stopped waiting (after ${d})`,
330
+ resolved: (kind, n, d) => `✓ You ${kind === 'question' ? 'answered' : 'approved'} ${n} (kept waiting ${d})`,
331
+ allGood: 'Everyone is busy working ☕', waited: (d, m) => `Waiting ${d} · ${m}`, goTerminal: 'Answer in your terminal ↗', btnAnswer: 'Answer', btnApprove: 'Approve',
332
+ arrived: 'clocked in 👋', left: 'clocked out', helper: 'Helper', spawned: (t) => `sent out a helper${t ? ' (' + t + ')' : ''}`,
333
+ overflow: (n) => `${n} more session${n > 1 ? 's are' : ' is'} queuing for a free seat`, planLabel: 'Approve the plan', questionLabel: 'Answer a question',
334
+ demoHello: '☀️ Good morning! 3 AI coworkers have clocked in', demoQuestion: 'WebGL or Canvas 2D?', demoSearch: 'three.js shadows',
335
+ toggle: '中',
336
+ alertsOn: '🔔 Alerts on', alertsOff: '🔕 Turn on alerts', alertsSoundOnly: '🔔 Alerts on (sound only)',
337
+ alertsHint: 'A chime when an agent waits on you, plus a system notification when this page is out of sight',
338
+ notifyTitle: (n) => `${n} needs you`, strikeTitle: (n) => `${n} went on strike 🪧`, strikeBody: 'Kept waiting for 3 minutes — check your terminal',
339
+ titleWaiting: (n) => `(${n}) waiting · officepals`,
340
+ pip: '⧉ Pop out', pipClose: '⧉ Bring back', pipUnsupported: 'Pop-out needs Chrome or Edge 116+',
341
+ pipHint: 'Shrink the office into an always-on-top window you can glance at while you code', pipFallback: "This browser can't keep a window on top, so this opens a small window you can park in a corner", pipActive: 'The office is in the pop-out window', pipBack: 'Bring it back here',
342
+ pipChip: (n) => (n ? `${n} waiting on you` : 'Everyone is working'),
343
+ },
344
+ };
345
+ const T = STRINGS[LANG];
346
+ document.documentElement.lang = LANG === 'zh' ? 'zh-CN' : 'en';
347
+ document.querySelectorAll('[data-t]').forEach((el) => (el.textContent = T[el.dataset.t]));
348
+ const langToggle = document.getElementById('lang-toggle');
349
+ langToggle.textContent = T.toggle;
350
+ langToggle.addEventListener('click', () => {
351
+ localStorage.setItem('officepals-lang', LANG === 'zh' ? 'en' : 'zh');
352
+ const url = new URL(location.href);
353
+ url.searchParams.delete('lang');
354
+ location.href = url.toString();
355
+ });
356
+ const { OrbitControls } = await import('/vendor/three/OrbitControls.js');
357
+ const { RoundedBoxGeometry } = await import('/vendor/three/RoundedBoxGeometry.js');
358
+ const { CSS2DRenderer, CSS2DObject } = await import('/vendor/three/CSS2DRenderer.js');
359
+
360
+ // ── Renderer, camera, light ─────────────────────────────────────
361
+ const app = document.getElementById('app');
362
+ const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
363
+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
364
+ renderer.setSize(innerWidth, innerHeight);
365
+ renderer.shadowMap.enabled = true;
366
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
367
+ renderer.toneMapping = THREE.NeutralToneMapping;
368
+ renderer.toneMappingExposure = 1.05;
369
+ app.appendChild(renderer.domElement);
370
+
371
+ const labels = new CSS2DRenderer();
372
+ labels.setSize(innerWidth, innerHeight);
373
+ Object.assign(labels.domElement.style, { position: 'absolute', inset: '0', pointerEvents: 'none' });
374
+ app.appendChild(labels.domElement);
375
+
376
+ const scene = new THREE.Scene();
377
+ // The canvas follows the main window, or the pop-out window while it is open.
378
+ let viewW = innerWidth, viewH = innerHeight;
379
+ const aspect = () => viewW / viewH;
380
+ // Frustum height: enough for the room's height, and its width on narrow screens.
381
+ const view = () => Math.max(13.5, 21 / aspect());
382
+ const camera = new THREE.OrthographicCamera((-view() * aspect()) / 2, (view() * aspect()) / 2, view() / 2, -view() / 2, 0.1, 200);
383
+ const target = new THREE.Vector3(0, 0.6, 0.2);
384
+ const sph = new THREE.Spherical(40, 1.13, Math.PI / 4);
385
+ camera.position.setFromSpherical(sph).add(target);
386
+ camera.lookAt(target);
387
+ camera.zoom = 0.55;
388
+ camera.updateProjectionMatrix();
389
+
390
+ const controls = new OrbitControls(camera, renderer.domElement);
391
+ controls.target.copy(target);
392
+ controls.enablePan = false;
393
+ controls.minAzimuthAngle = -0.05;
394
+ controls.maxAzimuthAngle = Math.PI / 2 + 0.05;
395
+ controls.minPolarAngle = 0.55;
396
+ controls.maxPolarAngle = 1.25;
397
+ controls.minZoom = 0.6;
398
+ controls.maxZoom = 2.4;
399
+ let userTook = false;
400
+ controls.addEventListener('start', () => (userTook = true));
401
+
402
+ function fitTo(w, h) {
403
+ viewW = w;
404
+ viewH = h;
405
+ camera.left = (-view() * aspect()) / 2;
406
+ camera.right = (view() * aspect()) / 2;
407
+ camera.top = view() / 2;
408
+ camera.bottom = -view() / 2;
409
+ camera.updateProjectionMatrix();
410
+ renderer.setSize(w, h);
411
+ labels.setSize(w, h);
412
+ applyQuality(w);
413
+ }
414
+ // Below this width the labels over heads would cover the room.
415
+ const COMPACT_BELOW_PX = 760;
416
+ addEventListener('resize', () => {
417
+ document.body.classList.toggle('compact', MINI || innerWidth < COMPACT_BELOW_PX);
418
+ if (!pipWindow) fitTo(innerWidth, innerHeight);
419
+ });
420
+
421
+ const hemi = new THREE.HemisphereLight(0xfff3e6, 0xc8b6ff, 1.25);
422
+ scene.add(hemi);
423
+ const sun = new THREE.DirectionalLight(0xfff1dd, 2.4);
424
+ sun.position.set(9, 16, 7);
425
+ sun.castShadow = true;
426
+ sun.shadow.mapSize.set(2048, 2048);
427
+ Object.assign(sun.shadow.camera, { left: -12, right: 12, top: 12, bottom: -12, near: 1, far: 50 });
428
+ sun.shadow.bias = -0.0006;
429
+ sun.shadow.normalBias = 0.02;
430
+ scene.add(sun);
431
+ const fill = new THREE.DirectionalLight(0xc6dcff, 0.7);
432
+ fill.position.set(-9, 7, 4);
433
+ scene.add(fill);
434
+
435
+ // ── Building blocks ─────────────────────────────────────────────
436
+ const mat = (color, extra = {}) => new THREE.MeshStandardMaterial({ color, roughness: 0.78, metalness: 0, ...extra });
437
+ function shade(mesh) {
438
+ mesh.traverse((o) => { if (o.isMesh) { o.castShadow = true; o.receiveShadow = true; } });
439
+ return mesh;
440
+ }
441
+ function rbox(w, h, d, r, color, extra) {
442
+ return shade(new THREE.Mesh(new RoundedBoxGeometry(w, h, d, 4, Math.min(r, w / 2, h / 2, d / 2)), mat(color, extra)));
443
+ }
444
+ function cyl(rt, rb, h, color, seg = 24) {
445
+ return shade(new THREE.Mesh(new THREE.CylinderGeometry(rt, rb, h, seg), mat(color)));
446
+ }
447
+ function ball(r, color, extra) {
448
+ return shade(new THREE.Mesh(new THREE.SphereGeometry(r, 28, 20), mat(color, extra)));
449
+ }
450
+ function at(obj, x, y, z, ry = 0, parent = scene) {
451
+ obj.position.set(x, y, z);
452
+ obj.rotation.y = ry;
453
+ parent.add(obj);
454
+ return obj;
455
+ }
456
+ function textTexture(text, bg, fg, w = 256, h = 128, size = 64) {
457
+ const c = document.createElement('canvas');
458
+ c.width = w; c.height = h;
459
+ const g = c.getContext('2d');
460
+ g.fillStyle = bg;
461
+ g.beginPath(); g.roundRect(6, 6, w - 12, h - 12, 18); g.fill();
462
+ g.fillStyle = fg;
463
+ g.font = `800 ${size}px -apple-system, "PingFang SC", sans-serif`;
464
+ g.textAlign = 'center'; g.textBaseline = 'middle';
465
+ g.fillText(text, w / 2, h / 2 + 4);
466
+ const t = new THREE.CanvasTexture(c);
467
+ t.colorSpace = THREE.SRGBColorSpace;
468
+ return t;
469
+ }
470
+ function label(html, className) {
471
+ const div = document.createElement('div');
472
+ div.className = className;
473
+ div.innerHTML = html;
474
+ return new CSS2DObject(div);
475
+ }
476
+
477
+ // ── The room ────────────────────────────────────────────────────
478
+ at(rbox(15.4, 0.8, 11.4, 0.3, 0xf2dcc4), 0, -0.42, 0); // island slab
479
+ at(rbox(14.8, 0.1, 10.8, 0.04, 0xe9c79e), 0, -0.02, 0); // wooden floor
480
+ for (let i = -6; i <= 6; i++) { // floor boards
481
+ const b = new THREE.Mesh(new THREE.BoxGeometry(0.02, 0.012, 10.7), mat(0xd8b083));
482
+ b.receiveShadow = true;
483
+ at(b, i * 1.1, 0.035, 0);
484
+ }
485
+ at(rbox(15.4, 3.6, 0.45, 0.15, 0xfaf1e7), 0, 1.75, -5.45); // back wall
486
+ // Left wall, with a doorway (z DOOR_Z ± DOOR_W/2) between the globe and the coffee corner.
487
+ const DOOR_Z = 2.45, DOOR_W = 1.0, DOOR_H = 2.25;
488
+ {
489
+ const z0 = DOOR_Z - DOOR_W / 2, z1 = DOOR_Z + DOOR_W / 2, back = -5.7, front = 5.7;
490
+ at(rbox(0.45, 3.6, z0 - back, 0.15, 0xf6ebe0), -7.45, 1.75, (back + z0) / 2); // left wall, back part
491
+ at(rbox(0.45, 3.6, front - z1, 0.15, 0xf6ebe0), -7.45, 1.75, (z1 + front) / 2); // front part
492
+ // Over the door: wider than the gap, so it covers the rounded ends of the two parts.
493
+ at(rbox(0.45, 3.6 - DOOR_H, DOOR_W + 0.6, 0.15, 0xf6ebe0), -7.45, DOOR_H + (3.6 - DOOR_H) / 2 - 0.05, DOOR_Z);
494
+ }
495
+ at(rbox(15.2, 0.24, 0.12, 0.05, 0xe7cdb2), 0, 0.12, -5.2); // skirting
496
+ for (const [z0, z1] of [[-5.6, DOOR_Z - DOOR_W / 2], [DOOR_Z + DOOR_W / 2, 5.6]]) {
497
+ at(rbox(0.12, 0.24, z1 - z0, 0.05, 0xe7cdb2), -7.2, 0.12, (z0 + z1) / 2); // skirting either side of the door
498
+ }
499
+ at(rbox(10.6, 0.04, 4.4, 0.02, 0xcfd9ff), 0, 0.04, 0); // rug under the desks
500
+ at(rbox(3.6, 0.04, 2.6, 0.02, 0xffd6e3), 3.6, 0.04, 3.4); // rug under your desk
501
+
502
+ // Window: the view outside is painted on the glass (sky with drifting clouds,
503
+ // and the city across the street), so it stays outside, inside the frame.
504
+ let skyTex, drawSky, drawCity;
505
+
506
+ // ── Day and night, by the local clock (or ?time=21 to preview an hour) ──
507
+ // Keyframes through the day; everything in between is blended.
508
+ const DAY_KEYS = [
509
+ [0, { top: '#2e3870', bottom: '#5f5f9a', cloud: 'rgba(160,165,205,0.55)', dark: 1 }],
510
+ [5, { top: '#2e3870', bottom: '#5f5f9a', cloud: 'rgba(160,165,205,0.55)', dark: 1 }],
511
+ [6.5, { top: '#9fb3e8', bottom: '#ffcfa6', cloud: 'rgba(255,233,220,0.9)', dark: 0.35 }],
512
+ [8, { top: '#8ec9ff', bottom: '#dcefff', cloud: 'rgba(255,255,255,0.95)', dark: 0 }],
513
+ [16.5, { top: '#8ec9ff', bottom: '#dcefff', cloud: 'rgba(255,255,255,0.95)', dark: 0 }],
514
+ [18.2, { top: '#8fa6e6', bottom: '#ffb889', cloud: 'rgba(255,227,210,0.9)', dark: 0.25 }],
515
+ [19.5, { top: '#4b4f8f', bottom: '#f29a83', cloud: 'rgba(201,179,201,0.75)', dark: 0.7 }],
516
+ [21, { top: '#2e3870', bottom: '#5f5f9a', cloud: 'rgba(160,165,205,0.55)', dark: 1 }],
517
+ [24, { top: '#2e3870', bottom: '#5f5f9a', cloud: 'rgba(160,165,205,0.55)', dark: 1 }],
518
+ ];
519
+ const TIME_PARAM = new URLSearchParams(location.search).get('time');
520
+ // Which clock the office follows: its own wall clock ("office", the default:
521
+ // one hour a real minute, a whole day in 24 minutes, carrying on across
522
+ // reloads) or your computer's ("real"). The toggle remembers the choice.
523
+ const OFFICE_HOUR_MS = 60_000;
524
+ let timeMode = (localStorage.getItem('officepals-time') ?? localStorage.getItem('cozy-agents-time')) === 'real' ? 'real' : 'office';
525
+ /** Hours since midnight (fractional) on the clock the office follows. */
526
+ function localHour() {
527
+ if (TIME_PARAM !== null && Number.isFinite(+TIME_PARAM)) return ((+TIME_PARAM % 24) + 24) % 24;
528
+ if (timeMode === 'office') return (Date.now() / OFFICE_HOUR_MS) % 24;
529
+ const d = new Date();
530
+ return d.getHours() + d.getMinutes() / 60 + d.getSeconds() / 3600;
531
+ }
532
+ const mixHex = (a, b, k) => '#' + new THREE.Color(a).lerp(new THREE.Color(b), k).getHexString();
533
+ function mixRgba(a, b, k) {
534
+ const pa = a.match(/[\d.]+/g).map(Number), pb = b.match(/[\d.]+/g).map(Number);
535
+ const v = pa.map((x, i) => x + (pb[i] - x) * k);
536
+ return `rgba(${v.slice(0, 3).map(Math.round).join(',')},${v[3].toFixed(2)})`;
537
+ }
538
+ /** The look of the sky at an hour: colours and how dark it is (0 day … 1 night). */
539
+ function daylight(hour) {
540
+ const i = DAY_KEYS.findIndex(([h], n) => n < DAY_KEYS.length - 1 && hour >= h && hour < DAY_KEYS[n + 1][0]);
541
+ const [h0, a] = DAY_KEYS[Math.max(0, i)], [h1, b] = DAY_KEYS[Math.max(0, i) + 1];
542
+ const k = Math.min(1, Math.max(0, (hour - h0) / (h1 - h0)));
543
+ return { top: mixHex(a.top, b.top, k), bottom: mixHex(a.bottom, b.bottom, k), cloud: mixRgba(a.cloud, b.cloud, k), dark: a.dark + (b.dark - a.dark) * k };
544
+ }
545
+ {
546
+ const W = 512, H = 256;
547
+ const c = document.createElement('canvas');
548
+ c.width = W; c.height = H;
549
+ const g = c.getContext('2d');
550
+ // Sky colours, clouds and stars for a time of day (see daylight()).
551
+ drawSky = (look) => {
552
+ const sky = g.createLinearGradient(0, 0, 0, H);
553
+ sky.addColorStop(0, look.top);
554
+ sky.addColorStop(1, look.bottom);
555
+ g.fillStyle = sky;
556
+ g.fillRect(0, 0, W, H);
557
+ if (look.dark > 0.55) {
558
+ // Stars: the same ones every night.
559
+ let seed = 3;
560
+ const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
561
+ g.fillStyle = `rgba(255, 250, 230, ${((look.dark - 0.55) / 0.45).toFixed(2)})`;
562
+ for (let i = 0; i < 46; i++) {
563
+ const r = rnd() < 0.2 ? 1.6 : 1;
564
+ g.fillRect(rnd() * W, rnd() * H * 0.75, r, r);
565
+ }
566
+ }
567
+ // Clouds drawn three times across so they wrap seamlessly as they drift.
568
+ g.fillStyle = look.cloud;
569
+ for (const [x, y, r] of [[70, 70, 26], [250, 46, 20], [400, 96, 30]]) {
570
+ for (const dx of [-W, 0, W]) {
571
+ for (const [ox, oy, k] of [[0, 0, 1], [r * 0.9, -r * 0.35, 1.15], [r * 1.9, 0, 0.9], [r * 0.9, r * 0.25, 1]]) {
572
+ g.beginPath();
573
+ g.arc(x + dx + ox, y + oy, r * k, 0, Math.PI * 2);
574
+ g.fill();
575
+ }
576
+ }
577
+ }
578
+ if (skyTex) skyTex.needsUpdate = true;
579
+ };
580
+ drawSky(daylight(12));
581
+ skyTex = new THREE.CanvasTexture(c);
582
+ skyTex.colorSpace = THREE.SRGBColorSpace;
583
+ skyTex.wrapS = THREE.RepeatWrapping;
584
+ skyTex.repeat.x = 0.62; // the window shows a slice of the panorama
585
+
586
+ at(rbox(3.4, 2.0, 0.14, 0.06, 0xffffff), 0.9, 2.05, -5.18); // frame
587
+ const pane = new THREE.Mesh(new THREE.PlaneGeometry(3.1, 1.7), new THREE.MeshBasicMaterial({ map: skyTex }));
588
+ at(pane, 0.9, 2.05, -5.105);
589
+ // The city across the street: a still layer in front of the drifting sky,
590
+ // pale and soft so it reads as far away.
591
+ {
592
+ const CW = 620, CH = 340;
593
+ const cc = document.createElement('canvas');
594
+ cc.width = CW; cc.height = CH;
595
+ const cg = cc.getContext('2d');
596
+ let cityTex = null;
597
+ // The same buildings every time (a fixed seed); at night, some windows light up.
598
+ drawCity = (dark) => {
599
+ cg.clearRect(0, 0, CW, CH);
600
+ let seed = 7;
601
+ const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
602
+ const lit = `rgba(255, 221, 140, ${(0.25 + 0.75 * dark).toFixed(2)})`;
603
+ const row = (base, minH, maxH, body, win, minW, maxW) => {
604
+ let x = -10;
605
+ while (x < CW) {
606
+ const w = minW + rnd() * (maxW - minW);
607
+ const h = minH + rnd() * (maxH - minH);
608
+ cg.fillStyle = body;
609
+ cg.fillRect(x, base - h, w, h + 2);
610
+ if (rnd() < 0.25) cg.fillRect(x + w * 0.35, base - h - 10, w * 0.3, 10); // rooftop box
611
+ for (let wy = base - h + 8; wy < base - 8; wy += 14) {
612
+ for (let wx = x + 6; wx < x + w - 9; wx += 12) {
613
+ cg.fillStyle = dark > 0.3 && rnd() < 0.38 ? lit : win;
614
+ cg.fillRect(wx, wy, 6, 7);
615
+ }
616
+ }
617
+ x += w + 4 + rnd() * 10;
618
+ }
619
+ };
620
+ row(CH, 90, 170, mixHex('#d3deec', '#4d5680', dark), mixHex('#e4ecf6', '#5b6590', dark), 40, 80); // far
621
+ row(CH, 50, 110, mixHex('#b9c9de', '#3a4268', dark), mixHex('#d6e2f0', '#474f78', dark), 50, 95); // near
622
+ if (cityTex) cityTex.needsUpdate = true;
623
+ };
624
+ drawCity(0);
625
+ cityTex = new THREE.CanvasTexture(cc);
626
+ cityTex.colorSpace = THREE.SRGBColorSpace;
627
+ const city = new THREE.Mesh(new THREE.PlaneGeometry(3.1, 1.7), new THREE.MeshBasicMaterial({ map: cityTex, transparent: true }));
628
+ at(city, 0.9, 2.05, -5.103);
629
+ }
630
+ // A faint glass sheen.
631
+ const glass = new THREE.Mesh(new THREE.PlaneGeometry(3.1, 1.7), new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.12 }));
632
+ at(glass, 0.9, 2.05, -5.1);
633
+ at(rbox(0.07, 1.8, 0.1, 0.03, 0xffffff), 0.9, 2.05, -5.08); // mullions
634
+ at(rbox(3.2, 0.07, 0.1, 0.03, 0xffffff), 0.9, 2.05, -5.08);
635
+ at(rbox(3.7, 0.08, 0.34, 0.03, 0xffffff), 0.9, 1.03, -5.08); // sill
636
+ at(cyl(0.09, 0.07, 0.14, 0xf1a36a), -0.3, 1.14, -5.06); // a little cactus on the sill
637
+ at(ball(0.08, 0x6fbf7f), -0.3, 1.27, -5.06).scale.set(0.9, 1.5, 0.9);
638
+ }
639
+
640
+ // Wall clock, between the bookshelf and the window
641
+ {
642
+ const CX = -1.75, CY = 2.55, CZ = -5.18;
643
+ const rim = at(cyl(0.44, 0.44, 0.08, 0xc9976a, 40), CX, CY, CZ);
644
+ rim.rotation.x = Math.PI / 2;
645
+ const face = at(cyl(0.38, 0.38, 0.09, 0xffffff, 40), CX, CY, CZ + 0.01);
646
+ face.rotation.x = Math.PI / 2;
647
+ for (let i = 0; i < 12; i++) {
648
+ const a = (i / 12) * Math.PI * 2;
649
+ const tick = new THREE.Mesh(new THREE.CircleGeometry(i % 3 ? 0.017 : 0.03, 10), new THREE.MeshBasicMaterial({ color: 0x8f86b8 }));
650
+ at(tick, CX + Math.sin(a) * 0.3, CY + Math.cos(a) * 0.3, CZ + 0.06);
651
+ }
652
+ // Hands pivot at the centre: each is a group whose child points up.
653
+ const hand = (len, w, z) => {
654
+ const pivot = at(new THREE.Group(), CX, CY, CZ + z);
655
+ at(rbox(w, len, 0.02, 0.008, 0x5b5470), 0, len / 2 - 0.03, 0, 0, pivot);
656
+ return pivot;
657
+ };
658
+ window.__clockHour = hand(0.18, 0.045, 0.07);
659
+ window.__clockHand = hand(0.27, 0.03, 0.085);
660
+ at(cyl(0.03, 0.03, 0.03, 0xff8f70), CX, CY, CZ + 0.09).rotation.x = Math.PI / 2;
661
+ }
662
+
663
+ function plant(x, z, s = 1) {
664
+ const g = new THREE.Group();
665
+ at(cyl(0.28 * s, 0.22 * s, 0.5 * s, 0xf1a36a), 0, 0.25 * s, 0, 0, g);
666
+ for (let i = 0; i < 6; i++) {
667
+ const leaf = ball(0.22 * s, i % 2 ? 0x7cc58a : 0x5fb27a);
668
+ leaf.scale.set(0.7, 1.4, 0.7);
669
+ const a = (i / 6) * Math.PI * 2;
670
+ at(leaf, Math.cos(a) * 0.15 * s, 0.75 * s + (i % 3) * 0.08 * s, Math.sin(a) * 0.15 * s, 0, g);
671
+ leaf.rotation.z = Math.cos(a) * 0.5;
672
+ leaf.rotation.x = Math.sin(a) * 0.5;
673
+ }
674
+ return at(g, x, 0, z);
675
+ }
676
+ plant(-6.6, -4.6, 1.2);
677
+ plant(6.6, 4.6, 1.1);
678
+ plant(-6.65, 3.45, 0.9);
679
+ plant(2.6, -4.7, 0.8);
680
+
681
+ /** An office chair facing -z (its backrest on +z): seat, backrest with a
682
+ * little post, gas lift, and a five-star base on casters. */
683
+ function officeChair(color, w = 0.7) {
684
+ const g = new THREE.Group();
685
+ const dark = 0x5b5470;
686
+ at(rbox(w, 0.12, w, 0.06, color), 0, 0.5, 0, 0, g); // seat
687
+ at(rbox(w, 0.62, 0.12, 0.06, color), 0, 0.98, w / 2 + 0.02, 0, g); // backrest
688
+ at(rbox(0.08, 0.3, 0.06, 0.03, dark), 0, 0.6, w / 2 + 0.0, 0, g); // backrest post
689
+ at(cyl(0.12, 0.14, 0.06, dark), 0, 0.42, 0, 0, g); // seat plate
690
+ at(cyl(0.045, 0.045, 0.3, 0xb7b0cc), 0, 0.26, 0, 0, g); // gas lift
691
+ at(cyl(0.07, 0.07, 0.06, dark), 0, 0.12, 0, 0, g); // hub
692
+ const spoke = w * 0.42;
693
+ for (let i = 0; i < 5; i++) {
694
+ const a = (i / 5) * Math.PI * 2 + 0.3;
695
+ const leg = at(rbox(spoke, 0.05, 0.07, 0.02, dark), Math.cos(a) * spoke / 2, 0.11, Math.sin(a) * spoke / 2, -a, g);
696
+ leg.castShadow = false;
697
+ at(ball(0.04, 0x2f2b3d), Math.cos(a) * spoke, 0.04, Math.sin(a) * spoke, 0, g); // caster
698
+ }
699
+ return g;
700
+ }
701
+
702
+ // Agent desks (agents sit behind them, facing you)
703
+ // Agent desks: two rows back to back (pods). The back row faces you, so it
704
+ // fills first; the front row sits facing it. Each desk's agent stands in
705
+ // front of its chair, facing its monitor.
706
+ const DESK_ROW_Z = 0.6; // desk centres at z = ∓0.6
707
+ /** Lines of "code" for the monitors; each desk scrolls its own copy. */
708
+ const codeCanvas = (() => {
709
+ const c = document.createElement('canvas');
710
+ c.width = 128; c.height = 128;
711
+ const g = c.getContext('2d');
712
+ g.fillStyle = '#1f2338';
713
+ g.fillRect(0, 0, 128, 128);
714
+ const ink = ['#7cc8ff', '#ff9ec7', '#b8e986', '#ffd36b', '#c7a8ff', '#e9e4f0'];
715
+ for (let y = 6; y < 128; y += 9) {
716
+ let x = 6 + ((y * 7) % 4) * 6;
717
+ while (x < 118) {
718
+ const w = 6 + ((x * 13 + y * 3) % 22);
719
+ g.fillStyle = ink[(x + y) % ink.length];
720
+ g.fillRect(x, y, Math.min(w, 122 - x), 4);
721
+ x += w + 5;
722
+ if ((x + y) % 5 === 0) break;
723
+ }
724
+ }
725
+ return c;
726
+ })();
727
+ const DESK_SPOT = 0.95; // where the agent stands, from the desk centre
728
+ const MUG_COLORS = [0xff9ec7, 0x9fd3ff, 0xb8e986, 0xffd36b, 0xc7a8ff, 0xff8f70];
729
+ const DESKS = [
730
+ // Fill order: the two ends first, then the middle, so labels don't overlap.
731
+ ...[-3.3, 3.3, 0].map((x) => ({ x, row: 'back' })),
732
+ ...[-3.3, 3.3, 0].map((x) => ({ x, row: 'front' })),
733
+ ].map(({ x, row }, i) => {
734
+ const back = row === 'back';
735
+ const z = back ? -DESK_ROW_Z : DESK_ROW_Z;
736
+ const g = new THREE.Group();
737
+ at(rbox(2.3, 0.12, 1.15, 0.05, 0xfffaf3), 0, 0.82, 0, 0, g);
738
+ for (const [lx, lz] of [[-1, -0.45], [1, -0.45], [-1, 0.45], [1, 0.45]]) at(cyl(0.05, 0.05, 0.8, 0xd9c8b4), lx, 0.4, lz, 0, g);
739
+ at(rbox(1.1, 0.66, 0.08, 0.04, 0x40445a), 0, 1.3, 0.18, 0, g);
740
+ at(cyl(0.04, 0.04, 0.3, 0x40445a), 0, 1.0, 0.18, 0, g);
741
+ const logo = new THREE.Mesh(new THREE.CircleGeometry(0.09, 24), new THREE.MeshBasicMaterial({ color: 0xffffff }));
742
+ at(logo, 0, 1.3, 0.225, 0, g);
743
+ at(rbox(0.7, 0.04, 0.25, 0.02, 0xe9e4f0), 0, 0.9, -0.2, 0, g); // keyboard
744
+ const mug = at(cyl(0.08, 0.07, 0.16, MUG_COLORS[i % MUG_COLORS.length]), 0.8, 0.96, -0.2, 0, g);
745
+ const codeTex = new THREE.CanvasTexture(codeCanvas);
746
+ codeTex.colorSpace = THREE.SRGBColorSpace;
747
+ codeTex.wrapT = THREE.RepeatWrapping;
748
+ codeTex.repeat.y = 0.55;
749
+ const screen = new THREE.Mesh(new THREE.PlaneGeometry(1.0, 0.56), new THREE.MeshBasicMaterial({ map: codeTex, color: 0x4a4f66 }));
750
+ at(screen, 0, 1.3, 0.135, Math.PI, g); // faces the agent
751
+ at(officeChair(0x8f86b8, 0.7), 0, 0, -1.0, Math.PI, g);
752
+ // The desk is built for an agent on its -z side; the front row turns round.
753
+ at(g, x, 0, z, back ? 0 : Math.PI);
754
+ const face = back ? 0 : Math.PI;
755
+ return { x, row, logo, mug, screen, face, spot: new THREE.Vector3(x, 0, back ? z - DESK_SPOT : z + DESK_SPOT) };
756
+ });
757
+
758
+ // Bookshelf
759
+ {
760
+ const g = new THREE.Group();
761
+ at(rbox(2.5, 2.5, 0.1, 0.04, 0xb9875c), 0, 1.25, -0.26, 0, g); // back
762
+ for (const sx of [-1.2, 1.2]) at(rbox(0.1, 2.5, 0.62, 0.04, 0xc9976a), sx, 1.25, 0, 0, g);
763
+ at(rbox(2.5, 0.1, 0.62, 0.04, 0xc9976a), 0, 2.45, 0, 0, g);
764
+ at(rbox(2.5, 0.1, 0.62, 0.04, 0xc9976a), 0, 0.05, 0, 0, g);
765
+ const colors = [0xff9ec7, 0x9fd3ff, 0xffd36b, 0xb8e986, 0xc7a8ff, 0xff8f70];
766
+ for (let row = 0; row < 3; row++) {
767
+ at(rbox(2.3, 0.05, 0.5, 0.02, 0xa87a52), 0, 0.45 + row * 0.72, 0.05, 0, g);
768
+ let x = -1.05;
769
+ while (x < 1.0) {
770
+ const w = 0.1 + Math.random() * 0.12;
771
+ const h = 0.42 + Math.random() * 0.18;
772
+ at(rbox(w, h, 0.36, 0.02, colors[Math.floor(Math.random() * colors.length)]), x + w / 2, 0.47 + row * 0.72 + h / 2, 0.08, 0, g);
773
+ x += w + 0.02;
774
+ }
775
+ }
776
+ at(g, -4.4, 0, -4.85);
777
+ }
778
+
779
+ // Server rack (the terminal)
780
+ const LEDS = [];
781
+ {
782
+ const g = new THREE.Group();
783
+ at(rbox(1.2, 2.3, 0.85, 0.08, 0x474b63), 0, 1.15, 0, 0, g);
784
+ for (let row = 0; row < 6; row++) {
785
+ at(rbox(1.0, 0.26, 0.04, 0.02, 0x5c617d), 0, 0.45 + row * 0.32, 0.43, 0, g);
786
+ for (let k = 0; k < 4; k++) {
787
+ const led = new THREE.Mesh(new THREE.SphereGeometry(0.03, 8, 8), new THREE.MeshBasicMaterial({ color: k % 2 ? 0x6dffb3 : 0x7cc8ff }));
788
+ at(led, -0.38 + k * 0.1, 0.45 + row * 0.32, 0.46, 0, g);
789
+ LEDS.push(led);
790
+ }
791
+ }
792
+ at(rbox(0.95, 0.04, 0.36, 0.02, 0x5c617d), 0, 0.93, 0.6, 0, g); // keyboard tray
793
+ at(rbox(0.7, 0.03, 0.22, 0.015, 0xe9e4f0), 0, 0.965, 0.62, 0, g); // keyboard
794
+ at(g, 5.5, 0, -4.7);
795
+ }
796
+
797
+ // Globe (the web)
798
+ let globe;
799
+ {
800
+ const g = new THREE.Group();
801
+ at(cyl(0.3, 0.38, 0.12, 0xc9976a), 0, 0.06, 0, 0, g);
802
+ at(cyl(0.05, 0.05, 0.75, 0xc9976a), 0, 0.45, 0, 0, g);
803
+ const geo = new THREE.IcosahedronGeometry(0.55, 3);
804
+ const colors = [];
805
+ const p = geo.attributes.position;
806
+ for (let i = 0; i < p.count; i++) {
807
+ const n = Math.sin(p.getX(i) * 5.1) + Math.sin(p.getY(i) * 4.3 + 1) + Math.sin(p.getZ(i) * 6.2 + 2);
808
+ const c = new THREE.Color(n > 0.6 ? 0x8fd18a : 0x7cc0ff);
809
+ colors.push(c.r, c.g, c.b);
810
+ }
811
+ geo.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
812
+ globe = shade(new THREE.Mesh(geo, mat(0xffffff, { vertexColors: true, flatShading: true })));
813
+ at(globe, 0, 1.35, 0, 0, g);
814
+ const ring = shade(new THREE.Mesh(new THREE.TorusGeometry(0.66, 0.025, 8, 48), mat(0xc9976a)));
815
+ ring.rotation.x = Math.PI / 2.6;
816
+ at(ring, 0, 1.35, 0, 0, g);
817
+ at(g, -6.4, 0, 1.4);
818
+ }
819
+
820
+ // The door: hinged on the coffee-corner side, swinging out into the hallway
821
+ // when someone comes or goes. Outside, a bit of hallway to walk in from.
822
+ const DOOR_OUT = new THREE.Vector3(-8.35, 0, DOOR_Z); // in the hallway, out of sight
823
+ const DOOR_IN = new THREE.Vector3(-6.6, 0, DOOR_Z); // just inside
824
+ let doorLeaf;
825
+ {
826
+ const z0 = DOOR_Z - DOOR_W / 2, z1 = DOOR_Z + DOOR_W / 2;
827
+ // frame on the room side
828
+ for (const z of [z0 - 0.04, z1 + 0.04]) at(rbox(0.1, DOOR_H + 0.08, 0.1, 0.03, 0xffffff), -7.2, (DOOR_H + 0.08) / 2, z);
829
+ at(rbox(0.1, 0.1, DOOR_W + 0.18, 0.03, 0xffffff), -7.2, DOOR_H + 0.05, DOOR_Z);
830
+ // the leaf, on a hinge at the z1 end
831
+ doorLeaf = at(new THREE.Group(), -7.23, 0, z1 - 0.02);
832
+ at(rbox(0.06, DOOR_H - 0.04, DOOR_W - 0.04, 0.03, 0x9fd3c7), 0, (DOOR_H - 0.04) / 2, -(DOOR_W - 0.04) / 2, 0, doorLeaf);
833
+ at(rbox(0.02, 0.62, 0.5, 0.02, 0x86c1b4), 0.035, 1.5, -(DOOR_W - 0.04) / 2, 0, doorLeaf); // panels
834
+ at(rbox(0.02, 0.62, 0.5, 0.02, 0x86c1b4), 0.035, 0.65, -(DOOR_W - 0.04) / 2, 0, doorLeaf);
835
+ at(ball(0.045, 0xffd36b), 0.07, 1.05, -(DOOR_W - 0.04) + 0.12, 0, doorLeaf); // knob
836
+ // hallway: a strip of floor and a far wall, seen through the open door
837
+ at(rbox(1.3, 0.1, 1.8, 0.04, 0xe2c29a), -8.3, -0.05, DOOR_Z);
838
+ at(rbox(0.1, 2.6, 1.8, 0.04, 0xe9dff5), -8.95, 1.3, DOOR_Z);
839
+ }
840
+ /** Open the door while anyone is in the doorway or about to pass through. */
841
+ function updateDoor(dt) {
842
+ const near = agents.concat(subs).some((a) => a.pos.x < -6.0 && Math.abs(a.pos.z - DOOR_Z) < 0.9);
843
+ const to = near ? Math.PI * 0.48 : 0; // swings out into the hallway, so it never hides the doorway
844
+ doorLeaf.rotation.y += (to - doorLeaf.rotation.y) * (1 - Math.exp(-dt * (near ? 7 : 4)));
845
+ }
846
+
847
+ // Whiteboard on the left wall: everyone's to-do lists as sticky notes, in
848
+ // three columns (to do, doing, done), each agent's notes in its own colour.
849
+ // Seen from the room, the board's +z end is on the left.
850
+ const board = new THREE.Group();
851
+ {
852
+ at(rbox(0.08, 1.45, 2.6, 0.04, 0xd9d2e6), 0, 0, 0, 0, board); // frame
853
+ at(rbox(0.04, 1.33, 2.48, 0.02, 0xffffff), 0.03, 0, 0, 0, board); // board
854
+ at(rbox(0.12, 0.05, 1.2, 0.02, 0xd9d2e6), 0.06, -0.74, 0, 0, board); // marker tray
855
+ for (const [c, z] of [[0xff8f70, -0.3], [0x7cc8ff, -0.15]]) at(rbox(0.05, 0.04, 0.12, 0.015, c), 0.1, -0.7, z, 0, board);
856
+ for (const z of [-0.41, 0.41]) at(rbox(0.01, 1.02, 0.015, 0.005, 0xb3adc8), 0.055, -0.08, z, 0, board);
857
+ // Column headings, written across the top.
858
+ const c = document.createElement('canvas');
859
+ c.width = 1024; c.height = 90;
860
+ const g = c.getContext('2d');
861
+ g.fillStyle = '#ffffff';
862
+ g.fillRect(0, 0, c.width, c.height);
863
+ g.fillStyle = '#8f86b8';
864
+ g.font = `700 46px -apple-system, "PingFang SC", sans-serif`;
865
+ g.textAlign = 'center';
866
+ g.textBaseline = 'middle';
867
+ T.boardCols.forEach((label, i) => g.fillText(label, (c.width / 6) * (1 + 2 * i), c.height / 2 + 2));
868
+ const tex = new THREE.CanvasTexture(c);
869
+ tex.colorSpace = THREE.SRGBColorSpace;
870
+ tex.anisotropy = 4;
871
+ const heading = new THREE.Mesh(new THREE.PlaneGeometry(2.4, 0.21), new THREE.MeshBasicMaterial({ map: tex }));
872
+ heading.position.set(0.052, 0.53, 0);
873
+ heading.rotation.y = Math.PI / 2;
874
+ board.add(heading);
875
+ at(board, -7.17, 2.0, -2.2);
876
+ }
877
+ const BOARD_COL = { pending: 0, in_progress: 1, completed: 2 };
878
+ const BOARD_COL_Z = [0.82, 0, -0.82]; // to do on the left, as seen from the room
879
+ const BOARD_PER_COL = 12; // 3 across, 4 down
880
+ const boardNotes = new Map(); // key -> note mesh
881
+ function boardSlot(col, n) {
882
+ return { y: 0.3 - Math.floor(n / 3) * 0.25, z: BOARD_COL_Z[col] + [0.25, 0, -0.25][n % 3] };
883
+ }
884
+ /** Lay the notes out from everyone's lists; notes glide when a step moves column. */
885
+ function updateBoard(dt) {
886
+ const want = new Map();
887
+ const counts = [0, 0, 0];
888
+ for (const a of agents) {
889
+ (a.steps ?? []).forEach((status, i) => {
890
+ const col = BOARD_COL[status] ?? 0;
891
+ const n = counts[col]++;
892
+ if (n < BOARD_PER_COL) want.set(`${a.session ?? a.name}:${a.planGen ?? 0}:${i}`, { col, n, color: a.shirt });
893
+ });
894
+ }
895
+ for (const [key, m] of boardNotes) {
896
+ if (want.has(key)) continue;
897
+ board.remove(m);
898
+ m.geometry.dispose();
899
+ boardNotes.delete(key);
900
+ }
901
+ const k = 1 - Math.exp(-dt * 8);
902
+ for (const [key, w] of want) {
903
+ const { y, z } = boardSlot(w.col, w.n);
904
+ let m = boardNotes.get(key);
905
+ if (!m) {
906
+ m = rbox(0.02, 0.2, 0.2, 0.01, w.color);
907
+ m.castShadow = false;
908
+ m.rotation.x = (((key.length * 37 + w.n * 13) % 9) - 4) * 0.03;
909
+ m.position.set(0.068, y, z);
910
+ board.add(m);
911
+ boardNotes.set(key, m);
912
+ }
913
+ m.position.y += (y - m.position.y) * k;
914
+ m.position.z += (z - m.position.z) * k;
915
+ }
916
+ }
917
+
918
+ // A little lounge on the right: a sofa facing you and a round coffee table
919
+ {
920
+ const g = new THREE.Group(); // built facing +z
921
+ const c = 0x9fd3c7, d = 0x86c1b4, L = 1.5;
922
+ at(rbox(L, 0.3, 0.85, 0.1, c), 0, 0.3, 0, 0, g); // seat base
923
+ at(rbox(L, 0.75, 0.3, 0.12, d), 0, 0.6, -0.3, 0, g); // back
924
+ for (const x of [-(L / 2 - 0.1), L / 2 - 0.1]) at(rbox(0.2, 0.5, 0.85, 0.08, d), x, 0.42, 0, 0, g); // arms
925
+ for (const x of [-0.32, 0.32]) at(rbox(0.6, 0.12, 0.55, 0.08, 0xb5e3d8), x, 0.5, 0.08, 0, g); // cushions
926
+ at(rbox(0.32, 0.32, 0.12, 0.06, 0xffd36b), 0.4, 0.68, -0.08, 0, g).rotation.z = 0.25; // pillow
927
+ for (const [x, z] of [[-0.6, -0.33], [0.6, -0.33], [-0.6, 0.33], [0.6, 0.33]]) at(cyl(0.04, 0.03, 0.15, 0x8a5a3a), x, 0.075, z, 0, g);
928
+ at(g, 6.55, 0, -0.5);
929
+ at(cyl(0.32, 0.32, 0.05, 0xfffaf3), 6.55, 0.45, 0.9); // coffee table
930
+ at(cyl(0.04, 0.04, 0.43, 0xd9c8b4), 6.55, 0.22, 0.9);
931
+ at(cyl(0.18, 0.22, 0.03, 0xd9c8b4), 6.55, 0.015, 0.9);
932
+ at(cyl(0.07, 0.06, 0.13, 0xff9ec7), 6.45, 0.54, 0.85); // a mug
933
+ }
934
+
935
+ // Test bench (shell commands that run tests): a signal tower shows the result
936
+ const testLamps = {};
937
+ {
938
+ const g = new THREE.Group();
939
+ at(rbox(1.5, 0.08, 0.6, 0.03, 0xfffaf3), 0, 0.82, 0, 0, g);
940
+ for (const [lx, lz] of [[-0.68, -0.24], [0.68, -0.24], [-0.68, 0.24], [0.68, 0.24]]) at(cyl(0.04, 0.04, 0.8, 0xd9c8b4), lx, 0.4, lz, 0, g);
941
+ at(rbox(0.6, 0.4, 0.05, 0.03, 0x40445a), -0.1, 1.12, -0.12, 0, g); // console
942
+ const scr = new THREE.Mesh(new THREE.PlaneGeometry(0.52, 0.32), new THREE.MeshBasicMaterial({ color: 0x2b3a33 }));
943
+ at(scr, -0.1, 1.12, -0.093, 0, g);
944
+ for (let i = 0; i < 4; i++) { // a few lines of "test output"
945
+ const line = new THREE.Mesh(new THREE.PlaneGeometry(0.12 + (i % 3) * 0.1, 0.025), new THREE.MeshBasicMaterial({ color: i === 3 ? 0x7ee2a0 : 0xb8c4bf }));
946
+ at(line, -0.28 + (0.06 + (i % 3) * 0.05), 1.22 - i * 0.06, -0.09, 0, g);
947
+ }
948
+ for (const [i, c] of [[0, 0x8fd3ff], [1, 0xffb3c9], [2, 0xb8e986]]) { // test tubes in a rack
949
+ at(cyl(0.025, 0.025, 0.22, 0xffffff), -0.62 + i * 0.08, 0.98, 0.05, 0, g);
950
+ at(cyl(0.022, 0.022, 0.1, c), -0.62 + i * 0.08, 0.93, 0.05, 0, g);
951
+ }
952
+ at(rbox(0.3, 0.05, 0.1, 0.02, 0xc9976a), -0.54, 0.89, 0.05, 0, g);
953
+ // Signal tower on the right end, tall enough to show over whoever stands there.
954
+ at(cyl(0.12, 0.14, 0.05, 0x5b5470), 0.55, 0.885, -0.05, 0, g);
955
+ at(cyl(0.03, 0.03, 0.95, 0x5b5470), 0.55, 1.35, -0.05, 0, g);
956
+ for (const [k, c, y] of [['red', 0xff5a5a, 2.16], ['yellow', 0xffc94a, 1.98], ['green', 0x4fd67a, 1.8]]) {
957
+ const lamp = at(ball(0.09, c, { emissive: c, emissiveIntensity: 0 }), 0.55, y, -0.05, 0, g);
958
+ lamp.userData.on = new THREE.Color(c);
959
+ lamp.userData.off = new THREE.Color(c).multiplyScalar(0.28); // unlit: dark glass
960
+ testLamps[k] = lamp;
961
+ }
962
+ at(g, 3.7, 0, -4.75);
963
+ }
964
+
965
+ // Mailbox (git): send off your commits; its flag goes up
966
+ let mailFlag;
967
+ {
968
+ const g = new THREE.Group();
969
+ at(cyl(0.05, 0.06, 0.82, 0xb9875c), 0, 0.41, 0, 0, g); // post
970
+ at(rbox(0.56, 0.34, 0.34, 0.12, 0x7cc0ff), 0, 0.98, 0, 0, g); // box, door towards -x
971
+ at(rbox(0.02, 0.22, 0.24, 0.01, 0x5aa6ec), -0.285, 0.97, 0, 0, g); // door
972
+ at(ball(0.025, 0xffffff), -0.3, 0.98, 0.07, 0, g); // handle
973
+ mailFlag = at(new THREE.Group(), 0.12, 0.95, 0.18, 0, g); // flag pivot
974
+ at(rbox(0.025, 0.3, 0.02, 0.01, 0x5b5470), 0, 0.15, 0, 0, mailFlag);
975
+ at(rbox(0.14, 0.09, 0.015, 0.01, 0xff6b6b), 0.07, 0.26, 0, 0, mailFlag);
976
+ mailFlag.rotation.z = -Math.PI / 2; // down
977
+ at(g, 6.95, 0, 3.3);
978
+ }
979
+
980
+ // Cardboard boxes (installing packages)
981
+ {
982
+ const box = (w, h, d, x, y, z, ry) => {
983
+ const b = at(rbox(w, h, d, 0.02, 0xd9a066), x, y, z, ry);
984
+ at(rbox(w + 0.005, 0.012, 0.07, 0.004, 0xf3d6a8), x, y + h / 2, z, ry); // tape
985
+ return b;
986
+ };
987
+ box(0.52, 0.4, 0.46, -1.95, 0.2, 4.9, 0.1);
988
+ box(0.46, 0.38, 0.42, -1.38, 0.19, 4.85, -0.15);
989
+ box(0.42, 0.34, 0.4, -1.72, 0.57, 4.9, 0.3);
990
+ }
991
+
992
+ // Coffee corner
993
+ {
994
+ at(rbox(1.9, 0.95, 0.8, 0.06, 0xfff6ea), -6.0, 0.48, 4.3);
995
+ for (const dx of [-0.47, 0.47]) {
996
+ at(rbox(0.86, 0.72, 0.03, 0.02, 0xf4e4d2), -6.0 + dx, 0.45, 4.7); // cupboard door
997
+ at(ball(0.035, 0xc9976a), -6.0 + dx * 0.25, 0.62, 4.73); // knob
998
+ }
999
+ at(rbox(0.5, 0.6, 0.45, 0.08, 0xff8f70), -6.3, 1.25, 4.3);
1000
+ at(rbox(0.3, 0.06, 0.14, 0.02, 0x5b5470), -6.3, 1.3, 4.55); // spout
1001
+ at(rbox(0.36, 0.03, 0.2, 0.01, 0x5b5470), -6.3, 0.98, 4.55); // drip tray
1002
+ at(cyl(0.05, 0.045, 0.09, 0xffffff), -6.3, 1.04, 4.55); // a cup filling up
1003
+ at(new THREE.Mesh(new THREE.SphereGeometry(0.025, 8, 8), new THREE.MeshBasicMaterial({ color: 0x6dffb3 })), -6.12, 1.45, 4.53);
1004
+ at(cyl(0.08, 0.07, 0.16, 0xffffff), -5.6, 1.04, 4.3);
1005
+ }
1006
+
1007
+ // Your desk
1008
+ let deskLamp;
1009
+ {
1010
+ const g = new THREE.Group();
1011
+ at(rbox(2.7, 0.13, 1.3, 0.06, 0xffc2d4), 0, 0.82, 0, 0, g);
1012
+ for (const [lx, lz] of [[-1.2, -0.5], [1.2, -0.5], [-1.2, 0.5], [1.2, 0.5]]) at(cyl(0.06, 0.06, 0.8, 0xe8a1b8), lx, 0.4, lz, 0, g);
1013
+ // Your laptop: you sit on the +z side (the chair), so the hinge and screen
1014
+ // are on the far edge, leaning back, with the display facing the chair.
1015
+ at(rbox(0.8, 0.04, 0.55, 0.03, 0xd9d6e4), -0.3, 0.9, 0.12, 0, g);
1016
+ at(rbox(0.66, 0.012, 0.26, 0.01, 0xb9b5c8), -0.3, 0.925, 0.2, 0, g); // keyboard
1017
+ const lid = new THREE.Group();
1018
+ lid.position.set(-0.3, 0.92, -0.15); // the hinge
1019
+ lid.rotation.x = -0.22; // leaning back
1020
+ at(rbox(0.8, 0.52, 0.03, 0.02, 0xd9d6e4), 0, 0.26, 0, 0, lid);
1021
+ const display = new THREE.Mesh(new THREE.PlaneGeometry(0.7, 0.42), new THREE.MeshBasicMaterial({ color: 0x9fc4ff }));
1022
+ display.position.set(0, 0.27, 0.017); // on the side facing you
1023
+ lid.add(display);
1024
+ g.add(lid);
1025
+ at(cyl(0.08, 0.07, 0.16, 0xffffff), 0.55, 0.96, 0.3, 0, g);
1026
+ // lamp that lights up when someone needs you
1027
+ at(cyl(0.16, 0.2, 0.06, 0x5b5470), 1.05, 0.91, -0.35, 0, g);
1028
+ at(cyl(0.03, 0.03, 0.55, 0x5b5470), 1.05, 1.18, -0.35, 0, g);
1029
+ deskLamp = at(ball(0.16, 0xfff3c4, { emissive: 0xffd27a, emissiveIntensity: 0.2 }), 1.05, 1.5, -0.35, 0, g);
1030
+ const nameplate = new THREE.Mesh(new THREE.PlaneGeometry(0.9, 0.3), new THREE.MeshBasicMaterial({ map: textTexture(T.nameplate, '#ffffff', '#b0577a', 256, 86, LANG === 'zh' ? 44 : 38) }));
1031
+ at(nameplate, 0.15, 1.05, -0.66, 0, g);
1032
+ at(officeChair(0xa58bff, 0.9), 0, 0, 1.05, 0, g); // your chair
1033
+ at(g, 3.6, 0, 3.6);
1034
+ const lamp = new THREE.PointLight(0xffc56b, 0, 5, 1.6);
1035
+ at(lamp, 4.65, 1.9, 3.25);
1036
+ deskLamp.userData.light = lamp;
1037
+ }
1038
+
1039
+ // ── Walking: two aisles plus side aisles around the desks ───────
1040
+ // The right aisle runs between the desks and the lounge.
1041
+ const BACK_AISLE = -2.4, FRONT_AISLE = 2.45, LEFT_AISLE = -5.4, RIGHT_AISLE = 5.25;
1042
+ /** Spots reached through waypoints (outer to inner), e.g. the sofa seats. */
1043
+ const approachTo = (p) => SPARE_SEATS.find((s) => s.approach && s.spot.distanceTo(p) < 0.05)?.approach;
1044
+ function route(from, to) {
1045
+ const out = approachTo(from), into = approachTo(to);
1046
+ if (!out && !into) return aisleRoute(from, to);
1047
+ const pts = [];
1048
+ let a = from;
1049
+ if (out) { pts.push(...[...out].reverse().map((p) => p.clone())); a = out[0]; }
1050
+ const b = into ? into[0] : to;
1051
+ pts.push(...aisleRoute(a, b));
1052
+ if (into) pts.push(...into.slice(1).map((p) => p.clone()), to.clone());
1053
+ return pts.filter((p, i) => i === 0 ? p.distanceTo(from) > 0.01 : p.distanceTo(pts[i - 1]) > 0.01);
1054
+ }
1055
+ function aisleRoute(from, to) {
1056
+ const aisle = (p) => (p.z < 0.9 ? BACK_AISLE : FRONT_AISLE);
1057
+ const a = aisle(from), b = aisle(to);
1058
+ const pts = [new THREE.Vector3(from.x, 0, a)];
1059
+ if (a !== b) {
1060
+ const side = (from.x + to.x) / 2 < 0 ? LEFT_AISLE : RIGHT_AISLE;
1061
+ pts.push(new THREE.Vector3(side, 0, a), new THREE.Vector3(side, 0, b));
1062
+ }
1063
+ pts.push(new THREE.Vector3(to.x, 0, b), to.clone());
1064
+ return pts.filter((p, i) => i === 0 || p.distanceTo(pts[i - 1]) > 0.01);
1065
+ }
1066
+
1067
+ // More sessions than desks: two sit on the sofa, two stand at the whiteboard.
1068
+ // When a desk frees up, the longest-seated of them moves over to it.
1069
+ const SPARE_SEATS = [
1070
+ { spot: new THREE.Vector3(6.25, 0, -0.45), face: 0, approach: [new THREE.Vector3(5.5, 0, 0.25), new THREE.Vector3(6.25, 0, 0.25)] },
1071
+ { spot: new THREE.Vector3(6.85, 0, -0.45), face: 0, approach: [new THREE.Vector3(5.5, 0, 0.25), new THREE.Vector3(6.85, 0, 0.25)] },
1072
+ { spot: new THREE.Vector3(-6.5, 0, -1.65), face: -Math.PI / 2 },
1073
+ { spot: new THREE.Vector3(-6.5, 0, -2.75), face: -Math.PI / 2 },
1074
+ ];
1075
+
1076
+ const SPOTS = {
1077
+ plan: { pos: new THREE.Vector3(-6.45, 0, -2.2), face: -Math.PI / 2, act: 'write' },
1078
+ test: { pos: new THREE.Vector3(3.5, 0, -3.95), face: Math.PI, act: 'type' },
1079
+ mail: { pos: new THREE.Vector3(6.2, 0, 3.3), face: Math.PI / 2, act: 'post' },
1080
+ boxes: { pos: new THREE.Vector3(-1.7, 0, 4.0), face: 0, act: 'carry' },
1081
+ files: { pos: new THREE.Vector3(-4.4, 0, -3.65), face: Math.PI, act: 'read' },
1082
+ terminal: { pos: new THREE.Vector3(5.5, 0, -3.55), face: Math.PI, act: 'type' },
1083
+ web: { pos: new THREE.Vector3(-5.25, 0, 1.4), face: -Math.PI / 2, act: 'point' },
1084
+ };
1085
+ // Beside your desk (its left end), facing it, so nothing hides them.
1086
+ // Live pacing: an agent stays put this long before walking somewhere new, so a
1087
+ // burst of quick tool calls doesn't send it running back and forth.
1088
+ const MIN_DWELL_SEC = 2.5;
1089
+ // A gap between tool calls longer than this counts as thinking.
1090
+ const THINK_AFTER_SEC = 1.2;
1091
+ // How long the head-scratching after a failed tool call lasts.
1092
+ const OOPS_SEC = 2.5;
1093
+ // Writing a new plan on the whiteboard takes this long (and is given up on
1094
+ // after PLAN_GIVE_UP_SEC, should it never get there).
1095
+ const PLAN_WRITE_SEC = 3.5, PLAN_GIVE_UP_SEC = 20;
1096
+ // The label's turn clock: shown from a few seconds in, highlighted on long turns.
1097
+ const TURN_CLOCK_FROM_SEC = 5, LONG_TURN_SEC = 10 * 60;
1098
+
1099
+ // Where agents hang out between turns (the coffee corner).
1100
+ const IDLE_SPOTS = [
1101
+ { pos: new THREE.Vector3(-4.9, 0, 3.3), face: -Math.PI / 2 },
1102
+ { pos: new THREE.Vector3(-4.2, 0, 4.3), face: -Math.PI / 2 },
1103
+ { pos: new THREE.Vector3(-3.6, 0, 3.2), face: -Math.PI * 0.6 },
1104
+ { pos: new THREE.Vector3(-5.5, 0, 3.0), face: -Math.PI * 0.85 },
1105
+ { pos: new THREE.Vector3(-3.0, 0, 4.35), face: -Math.PI * 0.55 },
1106
+ ];
1107
+ const esc = (t) => String(t).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
1108
+ const YOU_SLOTS = [[1.75, 3.0], [1.75, 4.25], [0.6, 3.6], [0.6, 2.75], [0.6, 4.5]].map(([x, z]) => new THREE.Vector3(x, 0, z));
1109
+
1110
+ // Each station has a few places to stand: in front, either side, then a row
1111
+ // behind ([sideways, back], metres). Whoever comes first takes the front.
1112
+ const SLOT_OFFSETS = [[0, 0], [0.85, 0], [-0.85, 0], [1.3, 0.65], [-1.3, 0.65]]; // heads are wide: keep clear
1113
+ const slotCache = {};
1114
+ function stationSlots(key) {
1115
+ if (slotCache[key]) return slotCache[key];
1116
+ const { pos, face } = SPOTS[key];
1117
+ const fwd = new THREE.Vector3(Math.sin(face), 0, Math.cos(face));
1118
+ const side = new THREE.Vector3(Math.cos(face), 0, -Math.sin(face));
1119
+ return (slotCache[key] = SLOT_OFFSETS.map(([l, b]) => pos.clone().addScaledVector(side, l).addScaledVector(fwd, -b)));
1120
+ }
1121
+ /** A free place at a station for `me` (helpers leave the front to the agents). */
1122
+ function freeSlot(key, me) {
1123
+ const slots = stationSlots(key);
1124
+ if (me.claim && slots.some((s) => s.distanceTo(me.claim) < 0.05)) return me.claim; // staying put
1125
+ const others = agents.concat(subs).filter((a) => a !== me && a.claim);
1126
+ const order = me.sub ? [1, 2, 3, 4, 0] : [0, 1, 2, 3, 4];
1127
+ const i = order.find((k) => !others.some((a) => a.claim.distanceTo(slots[k]) < 0.2));
1128
+ return slots[i ?? order[0]];
1129
+ }
1130
+ // Between turns: a few things to do, changed every IDLE_SWITCH_SEC or so;
1131
+ // after DOZE_AFTER_SEC with nothing to do it goes back to its desk and dozes
1132
+ // (and stays put, which also lets the office draw less).
1133
+ const IDLE_ANIMS = new Set(['sip', 'lounge', 'stretch', 'chat', 'doze']);
1134
+ const IDLE_SWITCH_SEC = [45, 90], DOZE_AFTER_SEC = 8 * 60;
1135
+ const WINDOW_SPOTS = [new THREE.Vector3(0.35, 0, -4.2), new THREE.Vector3(1.45, 0, -4.2)];
1136
+ const claimedBy = (spot, me) => agents.concat(subs).some((a) => a !== me && a.claim && a.claim.distanceTo(spot) < 0.2);
1137
+
1138
+ // Walking past someone: step aside a little instead of walking through them.
1139
+ const AVOID_R = 0.6, AVOID_PUSH = 0.35;
1140
+
1141
+ // ── Characters (the original chibi figures) ─────────────────────
1142
+ const SKIN = 0xffdcc4;
1143
+ const SKIN_C = new THREE.Color(SKIN);
1144
+ const HOT_FACE = new THREE.Color(0xff8a8a);
1145
+
1146
+ function makeCharacter({ shirt, hairColor }, scale = 1) {
1147
+ const root = new THREE.Group();
1148
+ const body = new THREE.Group();
1149
+ root.add(body);
1150
+ const torso = shade(new THREE.Mesh(new THREE.CapsuleGeometry(0.27, 0.3, 8, 16), mat(shirt)));
1151
+ torso.position.y = 0.66;
1152
+ body.add(torso);
1153
+ const headGroup = new THREE.Group();
1154
+ headGroup.position.y = 1.18;
1155
+ body.add(headGroup);
1156
+ const headMat = mat(SKIN);
1157
+ headGroup.add(shade(new THREE.Mesh(new THREE.SphereGeometry(0.34, 32, 24), headMat)));
1158
+ const hairM = shade(new THREE.Mesh(new THREE.SphereGeometry(0.36, 32, 24, 0, Math.PI * 2, 0, Math.PI * 0.55), mat(hairColor)));
1159
+ hairM.position.set(0, 0.04, -0.03);
1160
+ hairM.rotation.x = -0.25;
1161
+ headGroup.add(hairM);
1162
+ for (const s of [-1, 1]) {
1163
+ const eye = new THREE.Mesh(new THREE.SphereGeometry(0.045, 12, 12), mat(0x2c2540));
1164
+ eye.position.set(0.12 * s, -0.02, 0.31);
1165
+ eye.scale.set(1, 1.3, 0.6);
1166
+ headGroup.add(eye);
1167
+ const cheek = new THREE.Mesh(new THREE.CircleGeometry(0.06, 16), new THREE.MeshBasicMaterial({ color: 0xff9eb5, transparent: true, opacity: 0.55 }));
1168
+ cheek.position.set(0.2 * s, -0.11, 0.29);
1169
+ cheek.rotation.y = 0.5 * s;
1170
+ headGroup.add(cheek);
1171
+ }
1172
+ const limb = (r, len, color) => {
1173
+ const pivot = new THREE.Group();
1174
+ const m = shade(new THREE.Mesh(new THREE.CapsuleGeometry(r, len, 6, 12), mat(color)));
1175
+ m.position.y = -len / 2 - r * 0.6;
1176
+ pivot.add(m);
1177
+ return pivot;
1178
+ };
1179
+ const armL = limb(0.085, 0.24, shirt), armR = limb(0.085, 0.24, shirt);
1180
+ armL.position.set(-0.33, 0.84, 0);
1181
+ armR.position.set(0.33, 0.84, 0);
1182
+ const legL = limb(0.1, 0.18, 0x5b5470), legR = limb(0.1, 0.18, 0x5b5470);
1183
+ legL.position.set(-0.13, 0.4, 0);
1184
+ legR.position.set(0.13, 0.4, 0);
1185
+ body.add(armL, armR, legL, legR);
1186
+ const cup = cyl(0.06, 0.05, 0.12, 0xffffff); // coffee, in the right hand
1187
+ cup.position.set(0, -0.36, 0.07);
1188
+ cup.visible = false;
1189
+ armR.add(cup);
1190
+ const book = rbox(0.34, 0.26, 0.06, 0.02, 0xff8f70);
1191
+ book.position.set(0, 0.78, 0.38);
1192
+ book.rotation.x = -0.5;
1193
+ book.visible = false;
1194
+ body.add(book);
1195
+ const envelope = rbox(0.24, 0.15, 0.02, 0.01, 0xffffff); // for the mailbox
1196
+ envelope.position.set(0.33, 0.95, 0.5);
1197
+ envelope.rotation.set(-0.4, 0, 0.1);
1198
+ envelope.visible = false;
1199
+ body.add(envelope);
1200
+ const parcel = rbox(0.4, 0.3, 0.32, 0.03, 0xd9a066); // a package being installed
1201
+ parcel.position.set(0, 0.74, 0.42);
1202
+ parcel.visible = false;
1203
+ body.add(parcel);
1204
+ root.scale.setScalar(scale);
1205
+ return { root, body, headGroup, headMat, armL, armR, legL, legR, book, envelope, parcel, cup, mats: [], height: 1.55 };
1206
+ }
1207
+
1208
+ // Little effect particles (sweat, steam, puffs)
1209
+ const particles = [];
1210
+ function particle(pos, { color, r, vel, life, grow = 0, gravity = 0, opacity = 0.9 }) {
1211
+ const m = new THREE.Mesh(new THREE.SphereGeometry(r, 12, 10), new THREE.MeshStandardMaterial({ color, transparent: true, opacity, roughness: 0.4 }));
1212
+ m.position.copy(pos);
1213
+ scene.add(m);
1214
+ particles.push({ m, vel, life, age: 0, grow, gravity, opacity });
1215
+ }
1216
+ // Little "z"s floating up from a dozing coworker.
1217
+ const zTex = (() => {
1218
+ const c = document.createElement('canvas');
1219
+ c.width = c.height = 64;
1220
+ const g = c.getContext('2d');
1221
+ g.fillStyle = '#8f86b8';
1222
+ g.font = '800 52px -apple-system, sans-serif';
1223
+ g.textAlign = 'center';
1224
+ g.textBaseline = 'middle';
1225
+ g.fillText('z', 32, 34);
1226
+ const t = new THREE.CanvasTexture(c);
1227
+ t.colorSpace = THREE.SRGBColorSpace;
1228
+ return t;
1229
+ })();
1230
+ const zs = [];
1231
+ function zzz(pos) {
1232
+ const m = new THREE.Sprite(new THREE.SpriteMaterial({ map: zTex, transparent: true, depthWrite: false }));
1233
+ m.position.copy(pos);
1234
+ m.scale.setScalar(0.22);
1235
+ scene.add(m);
1236
+ zs.push({ m, age: 0 });
1237
+ }
1238
+ function updateZs(dt) {
1239
+ for (const z of [...zs]) {
1240
+ z.age += dt;
1241
+ z.m.position.y += dt * 0.35;
1242
+ z.m.position.x += Math.sin(z.age * 3) * dt * 0.12;
1243
+ z.m.scale.setScalar(0.22 + z.age * 0.12);
1244
+ z.m.material.opacity = Math.max(0, 1 - z.age / 2.2);
1245
+ if (z.age >= 2.2) {
1246
+ scene.remove(z.m);
1247
+ z.m.material.dispose();
1248
+ zs.splice(zs.indexOf(z), 1);
1249
+ }
1250
+ }
1251
+ }
1252
+
1253
+ function updateParticles(dt) {
1254
+ for (const p of [...particles]) {
1255
+ p.age += dt;
1256
+ p.vel.y -= p.gravity * dt;
1257
+ p.m.position.addScaledVector(p.vel, dt);
1258
+ p.m.scale.setScalar(1 + p.grow * p.age);
1259
+ p.m.material.opacity = p.opacity * Math.max(0, 1 - p.age / p.life);
1260
+ if (p.age >= p.life) {
1261
+ scene.remove(p.m);
1262
+ p.m.geometry.dispose();
1263
+ particles.splice(particles.indexOf(p), 1);
1264
+ }
1265
+ }
1266
+ }
1267
+ function puff(pos) {
1268
+ for (let i = 0; i < 10; i++) {
1269
+ const a = (i / 10) * Math.PI * 2;
1270
+ particle(pos.clone().add(new THREE.Vector3(0, 0.5, 0)), {
1271
+ color: 0xffffff, r: 0.13, life: 0.6, grow: 2, opacity: 0.85,
1272
+ vel: new THREE.Vector3(Math.cos(a) * 1.4, 0.6 + Math.random(), Math.sin(a) * 1.4),
1273
+ });
1274
+ }
1275
+ }
1276
+
1277
+ /** Little stars in the agent's colour (and white) — the teleport effect. */
1278
+ function sparkle(pos, color) {
1279
+ for (let i = 0; i < 16; i++) {
1280
+ const a = Math.random() * Math.PI * 2;
1281
+ particle(pos.clone().add(new THREE.Vector3((Math.random() - 0.5) * 0.5, 0.25 + Math.random() * 1.2, (Math.random() - 0.5) * 0.5)), {
1282
+ color: i % 3 ? color : 0xffffff, r: 0.04 + Math.random() * 0.035, life: 0.75, grow: -0.7, opacity: 1,
1283
+ vel: new THREE.Vector3(Math.cos(a) * 1.1, 0.5 + Math.random() * 1.4, Math.sin(a) * 1.1),
1284
+ });
1285
+ }
1286
+ }
1287
+ const TELEPORT_POP_SEC = 0.4;
1288
+ /** How far a seated agent's body rises to sit on its chair. */
1289
+ const SIT_LIFT = 0.3;
1290
+ const SIT_ANIMS = new Set(['type', 'think', 'oops', 'idle', 'doze', 'lounge']);
1291
+ /** Homes with somewhere to sit: the desks' chairs and the sofa. */
1292
+ const seatAt = (p) => DESKS.some((d) => d.spot.distanceTo(p) < 0.05) || SPARE_SEATS.some((s) => s.approach && s.spot.distanceTo(p) < 0.05);
1293
+ const easeOutBack = (x) => 1 + 2.70158 * Math.pow(x - 1, 3) + 1.70158 * Math.pow(x - 1, 2);
1294
+
1295
+ // ── Moods (same stages as the office: 20 s / 1 min / 3 min) ─────
1296
+ const DEMO_SPEED = 8;
1297
+ const moodOf = (sec) => (sec >= 180 ? 'strike' : sec >= 60 ? 'steaming' : sec >= 20 ? 'antsy' : 'calm');
1298
+ const MOOD_TEXT = T.mood;
1299
+ const BAR_COLOR = { calm: '#7ccf8a', antsy: '#f2b544', steaming: '#e5484d', strike: '#e5484d' };
1300
+ const TOOL_SPOT = { Read: 'files', Grep: 'files', Glob: 'files', LS: 'files', NotebookRead: 'files', Bash: 'terminal', BashOutput: 'terminal', WebFetch: 'web', WebSearch: 'web' };
1301
+ const TOOL_CN = T.tools;
1302
+ /** Shell commands by kind (from the hook relay): where they're done. */
1303
+ const CMD_SPOT = { test: 'test', git: 'mail', install: 'boxes', build: 'terminal', look: 'files' };
1304
+
1305
+ // Every other tool, by what it does: where it's done (a SPOTS key), or `stay`
1306
+ // for quick bookkeeping that shouldn't send anyone walking (updating the task
1307
+ // list happens alongside nearly every step).
1308
+ const KIND_SPOT = {
1309
+ note: null, sum: null, ui: null, session: null, other: undefined, design: undefined, // undefined: back to the desk
1310
+ msg: 'mail', file: 'mail', repo: 'mail', skill: 'files', files: 'files', bugs: 'terminal',
1311
+ stop: 'terminal', watch: 'terminal', term: 'terminal', db: 'terminal', shot: 'web', browse: 'web', docs: 'web',
1312
+ };
1313
+ /** What to call a tool call, and where it's done: a SPOTS key, null (stay
1314
+ * put), or undefined (at the desk). */
1315
+ function toolInfo(tool, cmd) {
1316
+ if (tool === 'Bash' && CMD_SPOT[cmd]) return { name: T.cmds[cmd], spot: CMD_SPOT[cmd] };
1317
+ const kind = kindOfTool(tool);
1318
+ if (!kind) return { name: TOOL_CN[tool] ?? '🛠 ' + tool, spot: TOOL_SPOT[tool] };
1319
+ const name = T.kinds[kind];
1320
+ // For MCP tools, add the tool itself, readably ("📸 Screenshot · preview screenshot").
1321
+ const detail = tool.startsWith('mcp__') && !STAY_KINDS.has(kind) ? ' · ' + tool.split('__').pop().replace(/[_-]+/g, ' ') : '';
1322
+ return { name: name + detail, spot: KIND_SPOT[kind] };
1323
+ }
1324
+ const spotFor = (tool, cmd) => toolInfo(tool, cmd).spot;
1325
+ const toolName = (tool, cmd) => toolInfo(tool, cmd).name;
1326
+
1327
+ // The test bench's signal tower: yellow blinking while tests run, then green
1328
+ // or red for a while. The mailbox flag goes up while someone uses git.
1329
+ const TEST_RESULT_MS = 8000, FLAG_UP_MS = 4000;
1330
+ const testLight = { state: 'idle', until: 0 };
1331
+ let flagUntil = 0;
1332
+ function testRunning() { testLight.state = 'run'; testLight.until = performance.now() + 120_000; }
1333
+ function testResult(pass, agent) {
1334
+ testLight.state = pass ? 'pass' : 'fail';
1335
+ testLight.until = performance.now() + TEST_RESULT_MS;
1336
+ if (agent) log(`<span style="color:${pass ? '#4caf6e' : 'var(--red)'}">${esc((pass ? T.testPass : T.testFail)(agent.name))}</span>`);
1337
+ if (pass && agent && !agent.wait) agent.cheerUntil = agent.t + 1.2;
1338
+ }
1339
+ function raiseFlag() { flagUntil = performance.now() + FLAG_UP_MS; }
1340
+
1341
+ function fmt(sec) {
1342
+ sec = Math.round(sec);
1343
+ return sec < 60 ? T.secs(sec) : T.mins(Math.floor(sec / 60), sec % 60);
1344
+ }
1345
+ /** Like fmt, with hours for long spans. */
1346
+ function span(sec) {
1347
+ return sec >= 3600 ? T.hours(Math.floor(sec / 3600), Math.floor((sec % 3600) / 60)) : fmt(sec);
1348
+ }
1349
+
1350
+ /** Today's numbers from the server (live mode); the demo counts its own. */
1351
+ const statsToday = { live: false, waits: 0, waitMs: 0, longestWaitMs: 0, turns: 0, workMs: 0 };
1352
+ const css = (c) => '#' + new THREE.Color(c).getHexString();
1353
+
1354
+ let totalWaitSec = 0;
1355
+ const agents = [];
1356
+
1357
+ class Agent {
1358
+ constructor({ name, color, look, home, homeFace = 0, project, sub = false }) {
1359
+ Object.assign(this, { name, shirt: color, project, home, homeFace, sub, t: Math.random() * 10 });
1360
+ this.ch = makeCharacter({ shirt: color, ...look }, sub ? 0.58 : 1);
1361
+ this.pos = home.clone();
1362
+ this.ch.root.position.copy(this.pos);
1363
+ this.facing = homeFace;
1364
+ this.faceTarget = homeFace;
1365
+ this.path = [];
1366
+ this.activity = null;
1367
+ this.status = T.justArrived;
1368
+ this.wait = null;
1369
+ this.cheerUntil = 0;
1370
+ scene.add(this.ch.root);
1371
+ this.tag = label('', sub ? 'tag sub' : 'tag');
1372
+ this.baseTagY = this.ch.height + (sub ? 0.35 : 0.5);
1373
+ this.tag.position.set(0, this.baseTagY, 0);
1374
+ this.ch.root.add(this.tag);
1375
+ this.sweatT = 0;
1376
+ this.steamT = 0;
1377
+ this.sign = null;
1378
+ this.lastTag = '';
1379
+ this.currentName = 'idle';
1380
+ if (!sub) agents.push(this);
1381
+ }
1382
+
1383
+ /** Cross-fade to a named clip (falls back to Special/Idle when a model lacks it). */
1384
+ /** Procedural pose for one frame (the original chibi animation). */
1385
+ pose(name, dt) {
1386
+ this.currentName = name;
1387
+ const { body, headGroup, headMat, armL, armR, legL, legR, book, envelope, parcel, cup } = this.ch;
1388
+ const T = this.t;
1389
+ let armLx = 0, armRx = 0, armLz = 0, armRz = 0, legLx = 0, legRx = 0, bob = 0, headYaw = 0;
1390
+ const sit = this.sitK ?? 0;
1391
+ book.visible = false;
1392
+ envelope.visible = false;
1393
+ parcel.visible = false;
1394
+ cup.visible = false;
1395
+ let headPitch = 0;
1396
+ switch (name) {
1397
+ case 'walk':
1398
+ case 'run': {
1399
+ const s = Math.sin(T * 11);
1400
+ legLx = s * 0.7; legRx = -s * 0.7; armLx = -s * 0.6; armRx = s * 0.6;
1401
+ bob = Math.abs(Math.cos(T * 11)) * 0.06;
1402
+ break;
1403
+ }
1404
+ case 'steaming':
1405
+ bob = Math.abs(Math.sin(T * 9)) * 0.22;
1406
+ armLz = -2.6 + Math.sin(T * 18) * 0.3; armRz = 2.6 - Math.sin(T * 18) * 0.3;
1407
+ legLx = Math.sin(T * 9) * 0.3;
1408
+ break;
1409
+ case 'antsy':
1410
+ armRz = 2.5 + Math.sin(T * 8) * 0.35;
1411
+ legRx = Math.max(0, Math.sin(T * 10)) * -0.4;
1412
+ headYaw = Math.sin(T * 2.2) * 0.5;
1413
+ break;
1414
+ case 'wave':
1415
+ armRz = 2.55 + Math.sin(T * 4) * 0.15;
1416
+ break;
1417
+ case 'cheer':
1418
+ bob = Math.abs(Math.sin(T * 8)) * 0.25;
1419
+ armLz = -2.6; armRz = 2.6;
1420
+ break;
1421
+ case 'sit':
1422
+ case 'type':
1423
+ armLx = -1.25 + Math.sin(T * 16) * 0.12; armRx = -1.25 + Math.cos(T * 16) * 0.12;
1424
+ headYaw = Math.sin(T * 0.7) * 0.08;
1425
+ break;
1426
+ case 'read':
1427
+ armLx = armRx = -1.1; book.visible = true;
1428
+ headYaw = Math.sin(T * 0.8) * 0.15;
1429
+ break;
1430
+ case 'point':
1431
+ armRx = -1.6 + Math.sin(T * 3) * 0.1;
1432
+ break;
1433
+ case 'write':
1434
+ // writing on the whiteboard
1435
+ armRx = -2.25 + Math.sin(T * 7) * 0.12; armRz = -0.12 + Math.sin(T * 3.5) * 0.08;
1436
+ armLx = -0.25;
1437
+ headYaw = Math.sin(T * 1.3) * 0.12;
1438
+ break;
1439
+ case 'sip': {
1440
+ // coffee in hand, a sip now and then
1441
+ cup.visible = true;
1442
+ const sipping = Math.sin(T * 0.9) > 0.55;
1443
+ armRx = sipping ? -2.35 : -0.9; armRz = sipping ? 0.45 : 0.15;
1444
+ headPitch = sipping ? -0.12 : 0;
1445
+ bob = Math.sin(T * 2) * 0.012;
1446
+ break;
1447
+ }
1448
+ case 'lounge':
1449
+ // sunk into the sofa, arms out along the back
1450
+ armLz = -0.55; armRz = 0.55; armLx = armRx = 0.2;
1451
+ headYaw = Math.sin(T * 0.5) * 0.25; headPitch = 0.08;
1452
+ break;
1453
+ case 'stretch': {
1454
+ // a big stretch every few seconds, then a look out of the window
1455
+ const up = Math.max(0, Math.sin(T * 0.8));
1456
+ armLz = -2.9 * up; armRz = 2.9 * up;
1457
+ bob = up * 0.05; headPitch = -0.25 * up;
1458
+ break;
1459
+ }
1460
+ case 'chat':
1461
+ // talking with its hands, nodding along
1462
+ armRx = -0.7 + Math.sin(T * 4.5) * 0.35; armRz = 0.25 + Math.sin(T * 2.3) * 0.15;
1463
+ headYaw = Math.sin(T * 1.7) * 0.18; headPitch = Math.max(0, Math.sin(T * 3.1)) * 0.12;
1464
+ break;
1465
+ case 'doze':
1466
+ // nodding off: the head drops, jerks up, drops again
1467
+ headPitch = 0.35 + Math.sin(T * 0.7) * 0.12 - (Math.sin(T * 0.23) > 0.97 ? 0.3 : 0);
1468
+ armLx = armRx = -0.9;
1469
+ bob = Math.sin(T * 1.1) * 0.01;
1470
+ break;
1471
+ case 'post':
1472
+ // posting a letter: reaching into the mailbox
1473
+ armRx = -1.75 + Math.sin(T * 2.5) * 0.15; armLx = -0.3;
1474
+ envelope.visible = Math.sin(T * 2.5) > -0.6;
1475
+ headYaw = 0.1;
1476
+ break;
1477
+ case 'carry':
1478
+ // holding a box, shifting its weight
1479
+ armLx = armRx = -1.2;
1480
+ parcel.visible = true;
1481
+ bob = 0.02 + Math.abs(Math.sin(T * 3)) * 0.03;
1482
+ break;
1483
+ case 'think':
1484
+ // hand on chin, the other arm folded, head slowly tilting
1485
+ armRx = -2.3; armRz = 0.5;
1486
+ armLx = -0.7; armLz = 0.35;
1487
+ headYaw = Math.sin(T * 0.9) * 0.22;
1488
+ bob = Math.sin(T * 1.6) * 0.01;
1489
+ break;
1490
+ case 'oops':
1491
+ // scratching its head
1492
+ armRx = -2.85 + Math.sin(T * 14) * 0.12; armRz = 0.35;
1493
+ headYaw = Math.sin(T * 6) * 0.25;
1494
+ break;
1495
+ case 'strike':
1496
+ break;
1497
+ default:
1498
+ bob = Math.sin(T * 2) * 0.015;
1499
+ }
1500
+ // Seated: lifted onto the seat, legs forward under the desk.
1501
+ legLx += (-1.3 - legLx) * sit;
1502
+ legRx += (-1.3 - legRx) * sit;
1503
+ bob += SIT_LIFT * sit;
1504
+ const k = 1 - Math.exp(-dt * 14);
1505
+ armL.rotation.x += (armLx - armL.rotation.x) * k;
1506
+ armR.rotation.x += (armRx - armR.rotation.x) * k;
1507
+ armL.rotation.z += (armLz - armL.rotation.z) * k;
1508
+ armR.rotation.z += (armRz - armR.rotation.z) * k;
1509
+ legL.rotation.x += (legLx - legL.rotation.x) * k;
1510
+ legR.rotation.x += (legRx - legR.rotation.x) * k;
1511
+ headGroup.rotation.y += (headYaw - headGroup.rotation.y) * k;
1512
+ headGroup.rotation.x += (headPitch - headGroup.rotation.x) * k;
1513
+ if (name === 'strike') {
1514
+ body.rotation.x += (-Math.PI / 2 - body.rotation.x) * (1 - Math.exp(-dt * 4));
1515
+ body.position.y += (0.32 - body.position.y) * k;
1516
+ } else {
1517
+ body.rotation.x += (0 - body.rotation.x) * k;
1518
+ body.position.y = bob;
1519
+ }
1520
+ // Red in the face when angry.
1521
+ headMat.color.lerp(name === 'steaming' || name === 'strike' ? HOT_FACE : SKIN_C, 1 - Math.exp(-dt * 3));
1522
+ }
1523
+
1524
+ async goTo(spot, face) {
1525
+ this.claim = spot;
1526
+ const cheering = this.cheerUntil - this.t;
1527
+ if (cheering > 0) await sleep(cheering * 1000);
1528
+ if (this.pos.distanceTo(spot) < 0.05) {
1529
+ this.faceTarget = face ?? this.faceTarget;
1530
+ return;
1531
+ }
1532
+ this.path = route(this.pos, spot);
1533
+ this.finalFace = face;
1534
+ return new Promise((resolve) => (this.arrived = resolve));
1535
+ }
1536
+
1537
+ async work(tool, detail, cmd) {
1538
+ if (this.wait) return;
1539
+ const key = spotFor(tool, cmd);
1540
+ this.status = `${toolName(tool, cmd)} ${detail}`;
1541
+ if (this.info) {
1542
+ const k = tool === 'Bash' && cmd ? `Bash:${cmd}` : tool;
1543
+ this.info.turnTools[k] = (this.info.turnTools[k] ?? 0) + 1;
1544
+ }
1545
+ log(`<b style="color:${css(this.shirt)}">${this.name}</b> ${this.status}`);
1546
+ this.activity = null;
1547
+ if (key) await this.goTo(freeSlot(key, this), SPOTS[key].face);
1548
+ else await this.goTo(this.home, this.homeFace);
1549
+ this.activity = key ? SPOTS[key].act : 'type';
1550
+ if (cmd === 'test') {
1551
+ testRunning();
1552
+ setTimeout(() => testResult(Math.random() < 0.75, this), 1800);
1553
+ }
1554
+ if (cmd === 'git') raiseFlag();
1555
+ }
1556
+
1557
+ async ask(kind, detail, risk = null) {
1558
+ const slot = YOU_SLOTS.find((s) => !agents.some((a) => a !== this && a.wait?.slot === s)) ?? YOU_SLOTS[0];
1559
+ this.wait = { kind, detail, risk, sec: 0, slot };
1560
+ log(`<b style="color:${css(this.shirt)}">${this.name}</b> <span style="color:var(--amber)">${T.ask[kind] ?? T.ask.permission}: ${esc(detail)}</span>`);
1561
+ renderApprovals(true);
1562
+ this.activity = null;
1563
+ this.tag.position.y = this.baseTagY;
1564
+ this.teleportTo(slot, Math.PI / 2, 'wait');
1565
+ }
1566
+
1567
+ resolve({ quiet = false } = {}) {
1568
+ if (!this.wait) return;
1569
+ const { sec, kind } = this.wait;
1570
+ totalWaitSec += sec;
1571
+ if (this.demo && this.info) {
1572
+ this.info.waits.count++;
1573
+ this.info.waits.ms += sec * 1000;
1574
+ }
1575
+ this.wait = null;
1576
+ this.activity = null;
1577
+ this.tag.position.y = this.baseTagY;
1578
+ if (this.sign) { scene.remove(this.sign); this.sign = null; }
1579
+ if (quiet) {
1580
+ log(`<span style="color:var(--muted)">${esc(T.gaveUp(this.name, fmt(sec)))}</span>`);
1581
+ } else {
1582
+ this.cheerUntil = this.t + 2.2;
1583
+ this.status = T.cheer;
1584
+ log(`<span style="color:#4caf6e">${esc(T.resolved(kind, this.name, fmt(sec)))}</span>`);
1585
+ }
1586
+ renderApprovals(true);
1587
+ }
1588
+
1589
+ // ── Live mode: react to events without awaiting the walk ──
1590
+ walkTo(spot, face, activity) {
1591
+ this.claim = spot;
1592
+ clearTimeout(this.walkTimer);
1593
+ const go = () => {
1594
+ this.arriveActivity = activity;
1595
+ if (this.pos.distanceTo(spot) < 0.05) {
1596
+ this.path = [];
1597
+ this.faceTarget = face ?? this.faceTarget;
1598
+ this.activity = activity;
1599
+ this.arriveActivity = undefined;
1600
+ this.arrivedAt = this.t;
1601
+ return;
1602
+ }
1603
+ this.activity = null;
1604
+ this.path = route(this.pos, spot);
1605
+ this.finalFace = face;
1606
+ };
1607
+ const cheering = this.cheerUntil - this.t;
1608
+ if (cheering > 0) this.walkTimer = setTimeout(go, cheering * 1000);
1609
+ else go();
1610
+ }
1611
+
1612
+ liveWork(tool, label, cmd) {
1613
+ const key = spotFor(tool, cmd); // null: quick bookkeeping, stay put
1614
+ // MCP tools arrive as mcp__<server>__<tool>; show just the tool, readably.
1615
+ this.status = `${toolName(tool, cmd)}${label ? ' ' + label : ''}`;
1616
+ if (tool === 'Bash' && cmd === 'test') testRunning();
1617
+ if (tool === 'Bash' && cmd === 'git') raiseFlag();
1618
+ this.thinkAt = null;
1619
+ this.oopsUntil = 0;
1620
+ this.oopsPending = false;
1621
+ if (this.status !== this.lastLogged) {
1622
+ log(`<b style="color:${css(this.shirt)}">${esc(this.name)}</b> ${esc(this.status)}`);
1623
+ this.lastLogged = this.status;
1624
+ }
1625
+ if (this.planning) {
1626
+ // At the whiteboard: note what's next and get to it once the plan is up.
1627
+ if (key !== null) this.planning.next = { key };
1628
+ this.planning.nextStatus = this.status;
1629
+ this.status = T.writingPlan;
1630
+ return;
1631
+ }
1632
+ if (key === null) return; // just the label changes
1633
+ if (key) this.intend(freeSlot(key, this), SPOTS[key].face, SPOTS[key].act);
1634
+ else if (this.sub) this.activity = 'type';
1635
+ else this.intend(this.home, this.homeFace, 'type');
1636
+ }
1637
+
1638
+ /** Live mode: take the session's title as the name (folder beside it) and
1639
+ * its to-do step in progress, when it has one. */
1640
+ applySession(sess, live = true) {
1641
+ if (sess.title && sess.title !== this.name) {
1642
+ this.name = sess.title;
1643
+ this.project = this.baseName ?? '';
1644
+ }
1645
+ this.task = sess.task ?? null;
1646
+ // The to-do list: a new or longer one is written up on the whiteboard.
1647
+ const steps = sess.steps ?? [];
1648
+ const grew = steps.length > (this.steps?.length ?? 0);
1649
+ if (grew) this.planGen = (this.planGen ?? 0) + 1;
1650
+ if (grew && live) this.planningPending = true;
1651
+ this.steps = steps.slice();
1652
+ }
1653
+
1654
+ /** How long this turn has been going ("⏱ 3:12"), while it's working and not waiting on you. */
1655
+ turnClock() {
1656
+ if (this.sub || this.wait || !this.turnStartedAt) return '';
1657
+ const sec = Math.max(0, Math.floor((Date.now() - this.turnStartedAt) / 1000));
1658
+ if (sec < TURN_CLOCK_FROM_SEC) return '';
1659
+ const clock = `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`;
1660
+ return `<span class="turn${sec >= LONG_TURN_SEC ? ' long' : ''}" title="${esc(T.turnFor(fmt(sec)))}">⏱ ${clock}</span>`;
1661
+ }
1662
+
1663
+ /** Walk to the whiteboard and write the new plan up, then carry on with
1664
+ * whatever came in meanwhile. */
1665
+ startPlanning() {
1666
+ if (this.sub || this.wait || this.planning) return;
1667
+ this.planning = { since: this.t, wroteAt: null, next: null, nextStatus: null };
1668
+ this.status = T.writingPlan;
1669
+ this.thinkAt = null;
1670
+ log(`<b style="color:${css(this.shirt)}">${esc(this.name)}</b> ${esc(this.status)}`);
1671
+ this.planning.spot = freeSlot('plan', this);
1672
+ this.intend(this.planning.spot, SPOTS.plan.face, 'write');
1673
+ }
1674
+
1675
+ finishPlanning() {
1676
+ const { next, nextStatus } = this.planning;
1677
+ this.planning = null;
1678
+ if (this.wait) return;
1679
+ if (nextStatus) this.status = nextStatus;
1680
+ if (next?.key) this.intend(freeSlot(next.key, this), SPOTS[next.key].face, SPOTS[next.key].act);
1681
+ else if (next) this.intend(this.home, this.homeFace, 'type');
1682
+ else this.think();
1683
+ }
1684
+
1685
+ /** Vanish in a burst of sparkles and pop up at `spot` — no walking.
1686
+ * Used when an agent needs you: it shouldn't keep you waiting to arrive. */
1687
+ teleportTo(spot, face, activity) {
1688
+ this.claim = spot;
1689
+ this.idling = false;
1690
+ clearTimeout(this.walkTimer);
1691
+ this.intent = null;
1692
+ sparkle(this.pos, this.shirt);
1693
+ this.pos.copy(spot);
1694
+ this.path = [];
1695
+ this.facing = this.faceTarget = face ?? this.faceTarget;
1696
+ this.activity = activity;
1697
+ this.arriveActivity = undefined;
1698
+ this.arrivedAt = this.t;
1699
+ this.appearAt = this.t;
1700
+ sparkle(spot, this.shirt);
1701
+ }
1702
+
1703
+ /** Live mode: head somewhere without thrashing. The label changes at once;
1704
+ * the walk waits until the agent has stayed MIN_DWELL_SEC where it is, and
1705
+ * only the latest intention counts. Waiting on you skips this (walkTo). */
1706
+ intend(spot, face, activity) {
1707
+ this.claim = spot;
1708
+ this.idling = false; // work (or a new idle activity, which sets it again)
1709
+ if (this.path.length === 0 && this.pos.distanceTo(spot) < 0.05) {
1710
+ this.intent = null;
1711
+ this.activity = activity;
1712
+ this.faceTarget = face ?? this.faceTarget;
1713
+ return;
1714
+ }
1715
+ this.intent = { spot, face, activity };
1716
+ }
1717
+
1718
+ /** A tool call finished: if nothing follows soon, it's thinking. */
1719
+ thinkSoon() {
1720
+ this.thinkAt = this.t + THINK_AFTER_SEC;
1721
+ }
1722
+
1723
+ think() {
1724
+ this.thinkAt = null;
1725
+ if (this.planning) return; // it'll think once the plan is up
1726
+ this.status = T.thinking;
1727
+ // Start thinking where it stands (put the book down); walk back later.
1728
+ if (this.path.length === 0) this.activity = 'think';
1729
+ if (!this.sub) this.intend(this.home, this.homeFace, 'think');
1730
+ }
1731
+
1732
+ /** A tool call failed. That's routine (Claude retries on its own), so no
1733
+ * alert and no label: just a short head-scratch, then back to thinking. */
1734
+ oops() {
1735
+ // It failed before the agent set off: scratch its head right here.
1736
+ // If it's already on its way, it scratches once it gets there.
1737
+ if (this.path.length === 0) this.intent = null;
1738
+ this.oopsPending = true;
1739
+ this.thinkAt = null;
1740
+ }
1741
+
1742
+ liveAsk(kind, detail, since, risk = null) {
1743
+ if (this.wait) return;
1744
+ const slot = YOU_SLOTS.find((s) => ![...agents, ...subs].some((a) => a !== this && a.wait?.slot === s)) ?? YOU_SLOTS[0];
1745
+ // A wait already past the strike when we first see it (a reload) doesn't alert again.
1746
+ this.wait = { kind, detail: detail ?? '', risk, sec: 0, slot, since, struck: (Date.now() - since) / 1000 >= MOOD_SEC.strike };
1747
+ this.tag.position.y = this.baseTagY;
1748
+ log(`<b style="color:${css(this.shirt)}">${esc(this.name)}</b> <span style="color:var(--amber)">${T.ask[kind] ?? T.ask.permission}${detail ? ': ' + esc(detail) : ''}</span>`);
1749
+ this.thinkAt = null;
1750
+ this.planning = null;
1751
+ this.teleportTo(slot, Math.PI / 2, 'wait');
1752
+ alertWaiting(this);
1753
+ renderApprovals(true);
1754
+ }
1755
+
1756
+ /** The turn is over: off to the coffee corner, then whatever the idle loop picks. */
1757
+ goIdle() {
1758
+ this.thinkAt = null;
1759
+ this.planning = null;
1760
+ this.idleSince = this.t;
1761
+ this.idleAct = null;
1762
+ this.idleAct = this.doIdle('sip') ?? this.doIdle('lounge') ?? this.doIdle('stretch');
1763
+ if (!this.idleAct) {
1764
+ this.status = T.idle;
1765
+ this.intend(this.home, this.homeFace, null);
1766
+ this.idling = true;
1767
+ }
1768
+ }
1769
+
1770
+ /** Try an idle activity; its name when there was room for it, else null. */
1771
+ doIdle(act) {
1772
+ let spot, face, partner = null;
1773
+ if (act === 'sip') {
1774
+ const s = IDLE_SPOTS.find((p) => !claimedBy(p.pos, this));
1775
+ if (!s) return null;
1776
+ [spot, face] = [s.pos, s.face];
1777
+ } else if (act === 'lounge') {
1778
+ const seat = SPARE_SEATS.filter((x) => x.approach).find((x) => !claimedBy(x.spot, this));
1779
+ if (!seat) return null;
1780
+ [spot, face] = [seat.spot, seat.face];
1781
+ } else if (act === 'stretch') {
1782
+ spot = WINDOW_SPOTS.find((p) => !claimedBy(p, this));
1783
+ if (!spot) return null;
1784
+ face = Math.PI;
1785
+ } else if (act === 'chat') {
1786
+ // Someone else idling in the coffee corner, and a free spot next to them.
1787
+ partner = agents.find((a) => a !== this && a.idling && (a.idleAct === 'sip' || a.idleAct === 'chat') && a.path.length === 0);
1788
+ const s = partner && IDLE_SPOTS.filter((p) => !claimedBy(p.pos, this) && p.pos.distanceTo(partner.pos) < 1.8).sort((x, y) => x.pos.distanceTo(partner.pos) - y.pos.distanceTo(partner.pos))[0];
1789
+ if (!s) return null;
1790
+ spot = s.pos;
1791
+ face = Math.atan2(partner.pos.x - spot.x, partner.pos.z - spot.z);
1792
+ } else if (act === 'doze') {
1793
+ [spot, face] = [this.home, this.homeFace];
1794
+ } else {
1795
+ return null;
1796
+ }
1797
+ this.status = T.idleActs[act];
1798
+ this.intend(spot, face, act);
1799
+ this.idling = true; // after intend, which clears it
1800
+ this.idleAct = act;
1801
+ this.idleNext = this.t + (act === 'doze' ? Infinity : IDLE_SWITCH_SEC[0] + Math.random() * (IDLE_SWITCH_SEC[1] - IDLE_SWITCH_SEC[0]));
1802
+ if (partner && partner.path.length === 0) {
1803
+ // The one being talked to turns round and joins in.
1804
+ partner.idleAct = 'chat';
1805
+ partner.activity = 'chat';
1806
+ partner.status = T.idleActs.chat;
1807
+ partner.faceTarget = Math.atan2(spot.x - partner.pos.x, spot.z - partner.pos.z);
1808
+ }
1809
+ return act;
1810
+ }
1811
+
1812
+ /** Next idle activity: something other than the last one; a doze once it's been long. */
1813
+ nextIdle() {
1814
+ if (this.t - this.idleSince >= DOZE_AFTER_SEC) return this.doIdle('doze');
1815
+ const options = ['sip', 'lounge', 'stretch', 'chat'].filter((x) => x !== this.idleAct).sort(() => Math.random() - 0.5);
1816
+ for (const act of options) if (this.doIdle(act)) return act;
1817
+ this.idleNext = this.t + IDLE_SWITCH_SEC[0];
1818
+ return null;
1819
+ }
1820
+
1821
+ /** The session ended: get up, walk out of the door, and go. */
1822
+ exit() {
1823
+ if (this.sub) return this.leave();
1824
+ clearTimeout(this.walkTimer);
1825
+ Object.assign(this, { exiting: true, wait: null, planning: null, idling: false, intent: null, thinkAt: null, cheerUntil: 0, oopsPending: false });
1826
+ if (this.sign) { scene.remove(this.sign); this.sign = null; }
1827
+ this.steps = [];
1828
+ this.turnStartedAt = null;
1829
+ this.status = T.goingHome;
1830
+ this.activity = null;
1831
+ this.claim = null;
1832
+ deskOf.delete(this);
1833
+ this.path = route(this.pos, DOOR_OUT);
1834
+ this.finalFace = -Math.PI / 2;
1835
+ renderApprovals(true);
1836
+ }
1837
+
1838
+ /** Come in through the door and walk to `spot`. */
1839
+ enter(spot, face) {
1840
+ this.pos.copy(DOOR_OUT);
1841
+ this.ch.root.position.copy(DOOR_OUT);
1842
+ this.facing = this.faceTarget = Math.PI / 2;
1843
+ this.walkTo(spot, face, null);
1844
+ }
1845
+
1846
+ leave(quiet = false) {
1847
+ clearTimeout(this.walkTimer);
1848
+ if (!quiet) puff(this.pos);
1849
+ scene.remove(this.ch.root);
1850
+ this.tag.element.remove();
1851
+ if (this.sign) scene.remove(this.sign);
1852
+ for (const list of [agents, subs]) if (list.includes(this)) list.splice(list.indexOf(this), 1);
1853
+ deskOf.delete(this);
1854
+ renderApprovals(true);
1855
+ }
1856
+
1857
+ update(dt) {
1858
+ this.t += dt;
1859
+ if (this.exiting && this.path.length === 0) return this.leave(true); // out of the door
1860
+ const { root, mats, headGroup: head } = this.ch;
1861
+ if (this.wait) this.wait.sec = this.wait.since !== undefined ? Math.max(0, (Date.now() - this.wait.since) / 1000) : this.wait.sec + dt * DEMO_SPEED;
1862
+ const mood = this.wait ? moodOf(this.wait.sec) : null;
1863
+ if (this.oopsPending && this.path.length === 0 && !this.intent) {
1864
+ this.oopsPending = false;
1865
+ this.oopsUntil = this.t + OOPS_SEC;
1866
+ this.thinkAt = this.t + OOPS_SEC;
1867
+ }
1868
+ if (this.thinkAt !== null && this.thinkAt !== undefined && this.t >= this.thinkAt && !this.wait) this.think();
1869
+ if (this.intent && !this.wait && this.path.length === 0 && this.t - (this.arrivedAt ?? -99) >= MIN_DWELL_SEC && this.t >= this.cheerUntil && this.t >= (this.oopsUntil ?? 0)) {
1870
+ const { spot, face, activity } = this.intent;
1871
+ this.intent = null;
1872
+ this.walkTo(spot, face, activity);
1873
+ }
1874
+ const walking = this.path.length > 0 && mood !== 'strike';
1875
+ if (this.idling && !this.wait && !walking && !this.intent && this.t >= (this.idleNext ?? Infinity)) this.nextIdle();
1876
+ if (this.planning) {
1877
+ const p = this.planning;
1878
+ if (!walking && !this.intent && this.pos.distanceTo(p.spot) < 0.1) p.wroteAt ??= this.t;
1879
+ if (this.wait || (p.wroteAt !== null && this.t - p.wroteAt >= PLAN_WRITE_SEC) || this.t - p.since > PLAN_GIVE_UP_SEC) this.finishPlanning();
1880
+ }
1881
+
1882
+ if (walking) {
1883
+ const next = this.path[0];
1884
+ const d = next.clone().sub(this.pos);
1885
+ const step = (this.sub ? 2.6 : 2.0) * dt;
1886
+ if (d.length() <= step) {
1887
+ this.pos.copy(next);
1888
+ this.path.shift();
1889
+ if (this.path.length === 0) {
1890
+ this.faceTarget = this.finalFace ?? this.faceTarget;
1891
+ this.arrived?.();
1892
+ this.arrived = null;
1893
+ this.arrivedAt = this.t;
1894
+ if (this.arriveActivity !== undefined) {
1895
+ this.activity = this.arriveActivity;
1896
+ this.arriveActivity = undefined;
1897
+ }
1898
+ }
1899
+ } else {
1900
+ this.pos.addScaledVector(d.normalize(), step);
1901
+ this.faceTarget = Math.atan2(d.x, d.z);
1902
+ }
1903
+ }
1904
+ let diff = this.faceTarget - this.facing;
1905
+ diff = Math.atan2(Math.sin(diff), Math.cos(diff));
1906
+ this.facing += diff * (1 - Math.exp(-dt * 10));
1907
+ root.rotation.y = this.facing;
1908
+
1909
+ // Pick the clip for what the agent is doing and how it feels.
1910
+ const atDesk = !this.sub && this.pos.distanceTo(this.home) < 0.3;
1911
+ let anim;
1912
+ if (walking) anim = this.sub ? 'run' : 'walk';
1913
+ else if (mood === 'strike') anim = 'strike';
1914
+ else if (mood === 'steaming') anim = 'steaming';
1915
+ else if (mood === 'antsy') anim = 'antsy';
1916
+ else if (mood === 'calm' && this.activity === 'wait') anim = 'wave';
1917
+ else if (this.t < this.cheerUntil) anim = 'cheer';
1918
+ else if (this.t < (this.oopsUntil ?? 0)) anim = 'oops';
1919
+ else if (this.activity === 'think') anim = 'think';
1920
+ else if (this.activity === 'type') anim = 'type';
1921
+ else if (this.activity === 'read') anim = 'read';
1922
+ else if (this.activity === 'point') anim = 'point';
1923
+ else if (this.activity === 'post') anim = 'post';
1924
+ else if (this.activity === 'write') anim = 'write';
1925
+ else if (IDLE_ANIMS.has(this.activity)) anim = this.activity;
1926
+ else if (this.activity === 'carry') anim = 'carry';
1927
+ else anim = 'idle';
1928
+ // At its own desk it sits down (helpers have no chair).
1929
+ const seatHere = this.pos.distanceTo(this.home) < 0.05 ? this.home : anim === 'lounge' && this.claim && this.pos.distanceTo(this.claim) < 0.05 ? this.claim : null;
1930
+ const seated = !this.sub && !walking && seatHere && SIT_ANIMS.has(anim) && seatAt(seatHere);
1931
+ this.sitK = (this.sitK ?? 0) + ((seated ? 1 : 0) - (this.sitK ?? 0)) * (1 - Math.exp(-dt * 10));
1932
+ this.pose(anim, dt);
1933
+ if (anim === 'doze') {
1934
+ this.zT = (this.zT ?? 0) - dt;
1935
+ if (this.zT <= 0) {
1936
+ this.zT = 1.6;
1937
+ zzz(this.pos.clone().add(new THREE.Vector3(0.25, 1.75 + (this.sitK ?? 0) * SIT_LIFT, 0)));
1938
+ }
1939
+ }
1940
+ // Step aside for anyone close by while walking (seated agents stay put).
1941
+ this.avoid ??= new THREE.Vector3();
1942
+ let pushX = 0, pushZ = 0;
1943
+ const weight = walking ? 1 : (this.sitK ?? 0) > 0.5 ? 0 : 0.6;
1944
+ if (weight) {
1945
+ for (const o of agents.concat(subs)) {
1946
+ if (o === this) continue;
1947
+ let dx = this.pos.x - o.pos.x, dz = this.pos.z - o.pos.z;
1948
+ let d = Math.hypot(dx, dz);
1949
+ if (d >= AVOID_R) continue;
1950
+ if (d < 1e-3) { dx = agents.indexOf(this) < agents.indexOf(o) ? 1 : -1; dz = 0; d = 1; } // exactly on top: split
1951
+ const k = (AVOID_R - Math.min(d, AVOID_R)) / AVOID_R;
1952
+ pushX += (dx / d) * k;
1953
+ pushZ += (dz / d) * k;
1954
+ }
1955
+ }
1956
+ const ka = 1 - Math.exp(-dt * 6);
1957
+ this.avoid.x += (Math.max(-1, Math.min(1, pushX)) * AVOID_PUSH * weight - this.avoid.x) * ka;
1958
+ this.avoid.z += (Math.max(-1, Math.min(1, pushZ)) * AVOID_PUSH * weight - this.avoid.z) * ka;
1959
+ root.position.set(this.pos.x + this.avoid.x, 0, this.pos.z + this.avoid.z);
1960
+ // Popping in after a teleport.
1961
+ this.baseScale ??= root.scale.x;
1962
+ const pop = this.appearAt === undefined ? 1 : Math.min(1, (this.t - this.appearAt) / TELEPORT_POP_SEC);
1963
+ root.scale.setScalar(this.baseScale * Math.max(0.01, easeOutBack(pop)));
1964
+
1965
+ // Flushed when angry.
1966
+ const heat = mood === 'steaming' ? 0.35 + 0.2 * Math.sin(this.t * 10) : mood === 'strike' ? 0.15 : 0;
1967
+ for (const m of mats) m.emissive?.setRGB(heat, heat * 0.12, heat * 0.12);
1968
+
1969
+ if (mood === 'strike' && !this.sign) this.makeSign();
1970
+ if (mood === 'strike' && this.wait.since !== undefined && !this.wait.struck) {
1971
+ this.wait.struck = true;
1972
+ alertStrike(this);
1973
+ }
1974
+
1975
+ // Sweat and steam off the head.
1976
+ const top = new THREE.Vector3();
1977
+ head.getWorldPosition(top).add(new THREE.Vector3(0, 0.15, 0));
1978
+ if (mood === 'antsy' || mood === 'steaming') {
1979
+ this.sweatT -= dt;
1980
+ if (this.sweatT <= 0) {
1981
+ this.sweatT = mood === 'steaming' ? 0.25 : 0.5;
1982
+ const side = Math.random() < 0.5 ? -1 : 1;
1983
+ particle(top.clone().add(new THREE.Vector3(0.3 * side, -0.05, 0.1)), {
1984
+ color: 0x8fd0ff, r: 0.055, life: 0.7, gravity: 6, opacity: 0.95,
1985
+ vel: new THREE.Vector3(0.4 * side, 0.6, 0),
1986
+ });
1987
+ }
1988
+ }
1989
+ if (mood === 'steaming') {
1990
+ this.steamT -= dt;
1991
+ if (this.steamT <= 0) {
1992
+ this.steamT = 0.12;
1993
+ particle(top.clone().add(new THREE.Vector3((Math.random() - 0.5) * 0.3, 0.15, 0)), {
1994
+ color: 0xffffff, r: 0.09, life: 1.1, grow: 2.2, opacity: 0.8,
1995
+ vel: new THREE.Vector3((Math.random() - 0.5) * 0.4, 1.4, (Math.random() - 0.5) * 0.4),
1996
+ });
1997
+ }
1998
+ }
1999
+
2000
+ // Label.
2001
+ const cls = this.sub
2002
+ ? `tag sub${this.tagLift > 6 ? ' lifted' : ''}`
2003
+ : `tag${mood ? ' waiting' : ''}${mood === 'steaming' ? ' steaming' : ''}${mood === 'strike' ? ' strike' : ''}${this.squeezed && !this.wait ? ' squeezed' : ''}${this.tagLift > 6 ? ' lifted' : ''}`;
2004
+ let html;
2005
+ if (this.sub) {
2006
+ html = this.name;
2007
+ } else {
2008
+ const status = this.wait ? (this.wait.kind === 'question' && mood === 'calm' ? T.askCalm : MOOD_TEXT[mood]) : this.status;
2009
+ const left = this.wait ? Math.max(0, 1 - this.wait.sec / 180) : 1;
2010
+ html =
2011
+ `<div class="name"><span class="dot" style="background:${css(this.shirt)}"></span><span class="nm">${esc(this.name)}</span>${provBadge(this)}<span class="proj">${esc(this.project)}</span></div>` +
2012
+ (this.task ? `<div class="task">📋 ${esc(this.task)}</div>` : '') +
2013
+ `<div class="status"><span class="st">${esc(status)}</span>${this.turnClock()}</div>` +
2014
+ `<div class="bar"><i style="width:${(left * 100).toFixed(1)}%;background:${BAR_COLOR[mood ?? 'calm']}"></i></div>`;
2015
+ }
2016
+ if (html !== this.lastTag || cls !== this.tag.element.className) {
2017
+ this.tag.element.className = cls;
2018
+ this.tag.element.innerHTML = html;
2019
+ this.lastTag = html;
2020
+ }
2021
+ }
2022
+
2023
+ makeSign() {
2024
+ const g = new THREE.Group();
2025
+ at(cyl(0.035, 0.035, 1.3, 0xc9976a), 0, 0.65, 0, 0, g);
2026
+ const face = () => new THREE.MeshStandardMaterial({ map: textTexture(T.strike, '#ffffff', '#e5484d', 256, 128, LANG === 'zh' ? 64 : 54), roughness: 0.8 });
2027
+ const board = shade(new THREE.Mesh(new THREE.BoxGeometry(0.9, 0.5, 0.04), [mat(0xffffff), mat(0xffffff), mat(0xffffff), mat(0xffffff), face(), face()]));
2028
+ at(board, 0, 1.3, 0, 0, g);
2029
+ g.position.set(this.pos.x - 0.8, 0, this.pos.z + 0.2);
2030
+ g.rotation.z = -0.12;
2031
+ scene.add(g);
2032
+ this.sign = g;
2033
+ }
2034
+ }
2035
+
2036
+ // ── HUD ─────────────────────────────────────────────────────────
2037
+ const logList = document.getElementById('log-list');
2038
+ function log(html) {
2039
+ const li = document.createElement('li');
2040
+ li.innerHTML = `<span class="t">${new Date().toTimeString().slice(0, 8)}</span>${html}`;
2041
+ logList.prepend(li);
2042
+ while (logList.children.length > 5) logList.lastChild.remove();
2043
+ }
2044
+ const reqList = document.getElementById('req-list');
2045
+ let hudTick = 0;
2046
+ const PROVIDER_NAME = { codex: 'Codex' };
2047
+ /** A small "Codex" tag for coworkers that aren't Claude Code sessions. */
2048
+ const provBadge = (a) => (PROVIDER_NAME[a.provider] ? `<span class="prov">${PROVIDER_NAME[a.provider]}</span>` : '');
2049
+
2050
+ const RISK_ICON = { high: '🔴', medium: '🟠', low: '🟢' };
2051
+ /** "🔴 Deletes files" for a permission request, judged by the hook relay. */
2052
+ function riskChip(risk) {
2053
+ if (!risk || !RISK_ICON[risk.level] || !T.risk[risk.why]) return '';
2054
+ return `<span class="risk ${risk.level}">${RISK_ICON[risk.level]} ${esc(T.risk[risk.why])}</span>`;
2055
+ }
2056
+ /** What a permission request is for: the tool, readably, and its label. */
2057
+ function askDetail(tool, cmd, label) {
2058
+ return tool ? `${toolName(tool, cmd)}${label ? ' · ' + label : ''}` : label ?? '';
2059
+ }
2060
+
2061
+ function renderApprovals(force) {
2062
+ if (!force && --hudTick > 0) return;
2063
+ hudTick = 8;
2064
+ const waiting = [...agents, ...subs].filter((a) => a.wait);
2065
+ reqList.innerHTML = waiting.length === 0
2066
+ ? `<div class="empty">${T.allGood}</div>`
2067
+ : waiting.map((a) => {
2068
+ const m = moodOf(a.wait.sec);
2069
+ return `<div class="req${m === 'steaming' || m === 'strike' ? ' hot' : ''}">` +
2070
+ `<span class="who" style="color:${css(a.shirt)}">${esc(a.name)}</span>` +
2071
+ `<span class="what">${esc(a.wait.detail)}</span>` +
2072
+ riskChip(a.wait.risk) +
2073
+ `<span class="waited">${T.waited(fmt(a.wait.sec), MOOD_TEXT[m].replace(/^\S+\s/, ''))}</span>` +
2074
+ (a.wait.since !== undefined ? `<span class="go">${T.goTerminal}</span></div>` : `<button data-i="${agents.indexOf(a)}">${a.wait.kind === 'question' ? T.btnAnswer : T.btnApprove}</button></div>`);
2075
+ }).join('');
2076
+ document.getElementById('s-run').innerHTML = `${agents.length + subs.length}${OVERFLOW.n ? ` <small title="${esc(T.overflow(OVERFLOW.n))}">+${OVERFLOW.n}</small>` : ''}`;
2077
+ document.getElementById('s-wait').textContent = waiting.length;
2078
+ document.getElementById('s-wait-tile').classList.toggle('alert', waiting.length > 0);
2079
+ document.title = waiting.length ? T.titleWaiting(waiting.length) : 'officepals';
2080
+ pipChip.textContent = T.pipChip(waiting.length);
2081
+ pipChip.classList.toggle('alert', waiting.length > 0);
2082
+ // Kept waiting today: the server's tally (it survives reloads) plus the waits under way.
2083
+ const ongoing = waiting.reduce((n, a) => n + a.wait.sec, 0);
2084
+ const kept = (statsToday.live ? statsToday.waitMs / 1000 : totalWaitSec) + ongoing;
2085
+ document.getElementById('s-total').textContent = span(kept);
2086
+ const sub = statsToday.live && (statsToday.waits || waiting.length)
2087
+ ? T.statSub(statsToday.waits + waiting.length, fmt(Math.max(statsToday.longestWaitMs / 1000, ...waiting.map((a) => a.wait.sec))))
2088
+ : '';
2089
+ document.getElementById('s-total-sub').textContent = sub;
2090
+ document.getElementById('s-total-tile').title = statsToday.live
2091
+ ? T.statTip(statsToday.turns, span(statsToday.workMs / 1000)).replace('{w}', span(kept))
2092
+ : '';
2093
+ }
2094
+ reqList.addEventListener('click', (e) => {
2095
+ const b = e.target.closest('button');
2096
+ if (b) agents[Number(b.dataset.i)]?.resolve();
2097
+ });
2098
+
2099
+ // ── Alerts: a chime, and a system notification when the page is out of sight ──
2100
+ const ALERTS_KEY = 'officepals-alerts';
2101
+ const MOOD_SEC = { strike: 180 };
2102
+ const alertBtn = document.getElementById('alert-toggle');
2103
+ const canNotify = 'Notification' in window;
2104
+ const alerts = { on: (localStorage.getItem(ALERTS_KEY) ?? localStorage.getItem('cozy-agents-alerts')) === '1' };
2105
+ let audioCtx = null;
2106
+
2107
+ function unlockAudio() {
2108
+ try {
2109
+ audioCtx ??= new AudioContext();
2110
+ if (audioCtx.state === 'suspended') audioCtx.resume();
2111
+ } catch {
2112
+ /* no Web Audio */
2113
+ }
2114
+ }
2115
+ // Browsers start audio only after a click; any click on the page will do.
2116
+ addEventListener('pointerdown', unlockAudio, { once: true });
2117
+
2118
+ const CHIMES = {
2119
+ wait: [659.25, 880], // ding-dong
2120
+ strike: [587.33, 440, 349.23], // falling: something's wrong
2121
+ done: [523.25, 659.25, 783.99], // rising: all done
2122
+ };
2123
+ function chime(kind = 'wait') {
2124
+ if (!alerts.on || !audioCtx) return;
2125
+ const notes = CHIMES[kind] ?? CHIMES.wait;
2126
+ notes.forEach((freq, i) => {
2127
+ const osc = audioCtx.createOscillator();
2128
+ const gain = audioCtx.createGain();
2129
+ const t0 = audioCtx.currentTime + i * 0.15;
2130
+ osc.type = 'sine';
2131
+ osc.frequency.value = freq;
2132
+ gain.gain.setValueAtTime(0.0001, t0);
2133
+ gain.gain.exponentialRampToValueAtTime(0.2, t0 + 0.02);
2134
+ gain.gain.exponentialRampToValueAtTime(0.0001, t0 + 0.4);
2135
+ osc.connect(gain).connect(audioCtx.destination);
2136
+ osc.start(t0);
2137
+ osc.stop(t0 + 0.45);
2138
+ });
2139
+ }
2140
+
2141
+ function notify(title, body, tag) {
2142
+ if (!alerts.on || !canNotify || Notification.permission !== 'granted') return;
2143
+ // Only when you aren't looking: the page is hidden, unfocused, or popped out.
2144
+ if (!document.hidden && document.hasFocus() && !pipWindow) return;
2145
+ const n = new Notification(title, { body, tag, renotify: true });
2146
+ n.onclick = () => {
2147
+ window.focus();
2148
+ n.close();
2149
+ };
2150
+ }
2151
+
2152
+ function alertWaiting(agent) {
2153
+ const w = agent.wait;
2154
+ if (!w || w.since === undefined || Date.now() - w.since > 10_000) return; // live, and just now
2155
+ chime();
2156
+ notify(T.notifyTitle(agent.name), `${T.ask[w.kind] ?? T.ask.permission}${w.detail ? ': ' + w.detail : ''}`, `wait-${agent.name}`);
2157
+ }
2158
+
2159
+ function alertStrike(agent) {
2160
+ chime('strike');
2161
+ notify(T.strikeTitle(agent.name), T.strikeBody, `strike-${agent.name}`);
2162
+ }
2163
+
2164
+ /** A turn of at least DONE_ALERT_MIN_SEC just ended. */
2165
+ const DONE_ALERT_MIN_SEC = 60;
2166
+ function alertDone(agent, ms) {
2167
+ chime('done');
2168
+ notify(T.doneTitle(agent.name), T.doneBody(fmt(ms / 1000)), `done-${agent.session ?? agent.name}`);
2169
+ }
2170
+
2171
+ function renderAlertButton() {
2172
+ const soundOnly = alerts.on && (!canNotify || Notification.permission !== 'granted');
2173
+ alertBtn.textContent = alerts.on ? (soundOnly ? T.alertsSoundOnly : T.alertsOn) : T.alertsOff;
2174
+ alertBtn.classList.toggle('on', alerts.on);
2175
+ alertBtn.title = T.alertsHint;
2176
+ }
2177
+ alertBtn.addEventListener('click', async () => {
2178
+ unlockAudio();
2179
+ if (alerts.on) {
2180
+ alerts.on = false;
2181
+ } else {
2182
+ if (canNotify && Notification.permission === 'default') await Notification.requestPermission();
2183
+ alerts.on = true;
2184
+ chime(); // a sample, so you know what it sounds like
2185
+ }
2186
+ localStorage.setItem(ALERTS_KEY, alerts.on ? '1' : '0');
2187
+ renderAlertButton();
2188
+ });
2189
+ renderAlertButton();
2190
+
2191
+ // ── Pop-out: the office in an always-on-top window (Document Picture-in-Picture) ──
2192
+ let pipWindow = null;
2193
+ const pipBtn = document.getElementById('pip-toggle');
2194
+ const pipNote = document.getElementById('pip-note');
2195
+ const pipChip = document.createElement('div');
2196
+ pipChip.id = 'pip-chip';
2197
+ const canPip = 'documentPictureInPicture' in window;
2198
+
2199
+ const MINI = new URLSearchParams(location.search).has('mini');
2200
+ if (MINI) {
2201
+ document.body.classList.add('mini');
2202
+ document.body.append(pipChip);
2203
+ }
2204
+ document.body.classList.toggle('compact', MINI || innerWidth < COMPACT_BELOW_PX);
2205
+
2206
+ function renderPipButton() {
2207
+ pipBtn.textContent = pipWindow ? T.pipClose : T.pip;
2208
+ pipBtn.title = canPip ? T.pipHint : T.pipFallback;
2209
+ pipNote.hidden = !pipWindow;
2210
+ }
2211
+
2212
+ async function popOut() {
2213
+ if (pipWindow) return pipWindow.close();
2214
+ if (!canPip) {
2215
+ // No always-on-top windows here: open the compact view in a small window instead.
2216
+ const url = new URL(location.href);
2217
+ url.searchParams.set('mini', '');
2218
+ url.searchParams.set('lang', LANG);
2219
+ url.searchParams.delete('demo');
2220
+ if (new URLSearchParams(location.search).has('demo')) url.searchParams.set('demo', '');
2221
+ window.open(url.toString(), 'officepals-mini', 'popup,width=460,height=340');
2222
+ return;
2223
+ }
2224
+ const win = await documentPictureInPicture.requestWindow({ width: 460, height: 340 });
2225
+ pipWindow = win;
2226
+ for (const style of document.querySelectorAll('style')) win.document.head.append(style.cloneNode(true));
2227
+ win.document.title = 'officepals';
2228
+ win.document.documentElement.lang = document.documentElement.lang;
2229
+ win.document.body.classList.add('compact', 'pip');
2230
+ win.document.body.style.setProperty('--night', document.body.style.getPropertyValue('--night') || '0');
2231
+ win.document.body.append(app, pipChip);
2232
+ fitTo(win.innerWidth, win.innerHeight);
2233
+ win.addEventListener('resize', () => fitTo(win.innerWidth, win.innerHeight));
2234
+ win.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeCard(); });
2235
+ win.addEventListener('pagehide', () => {
2236
+ document.body.prepend(app);
2237
+ pipChip.remove();
2238
+ pipWindow = null;
2239
+ fitTo(innerWidth, innerHeight);
2240
+ renderPipButton();
2241
+ });
2242
+ renderPipButton();
2243
+ renderApprovals(true);
2244
+ }
2245
+ pipBtn.addEventListener('click', popOut);
2246
+ document.getElementById('pip-back').addEventListener('click', () => pipWindow?.close());
2247
+ renderPipButton();
2248
+
2249
+ // ── Power: small windows draw less; the loop draws only as often as needed ──
2250
+ // A small window (the pop-out, ?mini, a narrow tab) can't show fine detail, so
2251
+ // it renders fewer pixels and a smaller shadow map.
2252
+ const SMALL_SHADOW = 1024, FULL_SHADOW = 2048;
2253
+ function applyQuality(w) {
2254
+ const small = MINI || !!pipWindow || w < COMPACT_BELOW_PX;
2255
+ const dpr = (pipWindow ?? window).devicePixelRatio || 1;
2256
+ renderer.setPixelRatio(Math.min(dpr, small ? 1.25 : 2));
2257
+ const size = small ? SMALL_SHADOW : FULL_SHADOW;
2258
+ if (sun.shadow.mapSize.x !== size) {
2259
+ sun.shadow.mapSize.set(size, size);
2260
+ sun.shadow.map?.dispose();
2261
+ sun.shadow.map = null; // rebuilt at the new size on the next draw
2262
+ }
2263
+ }
2264
+ applyQuality(innerWidth);
2265
+
2266
+ // Frame rate by what's happening. Busy (someone walking, popping in, cheering,
2267
+ // fretting at your desk, a puff in the air, you turning the camera): every
2268
+ // display frame. Calm (agents sitting and typing): 30 fps, 20 while you're
2269
+ // looking at another window. An empty office: 8 fps.
2270
+ const FPS_CALM = 30, FPS_CALM_AWAY = 20, FPS_EMPTY = 8;
2271
+ const DRAG_SETTLE_MS = 1200; // camera damping after you let go
2272
+ let dragging = false, draggedAt = 0;
2273
+ controls.addEventListener('start', () => (dragging = true));
2274
+ controls.addEventListener('end', () => { dragging = false; draggedAt = performance.now(); });
2275
+ function sceneBusy(now) {
2276
+ if (intro < 1 || dragging || now - draggedAt < DRAG_SETTLE_MS || particles.length) return true;
2277
+ for (const a of agents.concat(subs)) {
2278
+ if (a.path.length || a.wait || a.t < a.cheerUntil || a.t < (a.oopsUntil ?? 0)) return true;
2279
+ if (a.appearAt !== undefined && a.t - a.appearAt < TELEPORT_POP_SEC) return true;
2280
+ }
2281
+ return false;
2282
+ }
2283
+ function targetFps(now) {
2284
+ if (sceneBusy(now)) return 0; // 0 = every display frame
2285
+ if (!agents.length && !subs.length) return FPS_EMPTY;
2286
+ const doc = (pipWindow ?? window).document;
2287
+ return doc.hasFocus() ? FPS_CALM : FPS_CALM_AWAY;
2288
+ }
2289
+ const fpsMeter = { frames: 0, since: performance.now(), fps: 0 }; // for checking in the console
2290
+
2291
+ // Apply the time of day: the view outside, the light inside, the page behind.
2292
+ // Redrawn once a minute (and only when it has changed).
2293
+ const LIGHT_DAY = { sun: [0xfff1dd, 2.4], hemi: [0xfff3e6, 0xc8b6ff, 1.25], fill: 0.7 };
2294
+ // Night only a little warmer and lower than day: the office has its lights on.
2295
+ const LIGHT_NIGHT = { sun: [0xffe6c8, 2.1], hemi: [0xfff0df, 0xb9aef0, 1.18], fill: 0.6 };
2296
+ let lastDaylight = null;
2297
+ function applyDaylight() {
2298
+ const look = daylight(localHour());
2299
+ const key = `${look.top}${look.bottom}${look.dark.toFixed(2)}`;
2300
+ if (key === lastDaylight) return;
2301
+ lastDaylight = key;
2302
+ drawSky(look);
2303
+ drawCity(look.dark);
2304
+ const d = look.dark;
2305
+ sun.color.set(LIGHT_DAY.sun[0]).lerp(new THREE.Color(LIGHT_NIGHT.sun[0]), d);
2306
+ sun.intensity = LIGHT_DAY.sun[1] + (LIGHT_NIGHT.sun[1] - LIGHT_DAY.sun[1]) * d;
2307
+ hemi.color.set(LIGHT_DAY.hemi[0]).lerp(new THREE.Color(LIGHT_NIGHT.hemi[0]), d);
2308
+ hemi.groundColor.set(LIGHT_DAY.hemi[1]).lerp(new THREE.Color(LIGHT_NIGHT.hemi[1]), d);
2309
+ hemi.intensity = LIGHT_DAY.hemi[2] + (LIGHT_NIGHT.hemi[2] - LIGHT_DAY.hemi[2]) * d;
2310
+ fill.intensity = LIGHT_DAY.fill + (LIGHT_NIGHT.fill - LIGHT_DAY.fill) * d;
2311
+ for (const doc of [document, pipWindow?.document].filter(Boolean)) {
2312
+ doc.body.style.setProperty('--night', d.toFixed(3));
2313
+ }
2314
+ }
2315
+ applyDaylight();
2316
+ setInterval(applyDaylight, 2_000); // cheap when nothing changed; office time moves fast
2317
+
2318
+ const timeBtn = document.getElementById('time-toggle');
2319
+ function renderTimeButton() {
2320
+ timeBtn.textContent = timeMode === 'office' ? T.timeOffice : T.timeReal;
2321
+ timeBtn.title = T.timeHint;
2322
+ }
2323
+ timeBtn.addEventListener('click', () => {
2324
+ timeMode = timeMode === 'office' ? 'real' : 'office';
2325
+ localStorage.setItem('officepals-time', timeMode);
2326
+ renderTimeButton();
2327
+ applyDaylight();
2328
+ });
2329
+ renderTimeButton();
2330
+
2331
+ // ── Labels: lift overlapping ones clear of each other ──────────
2332
+ // Each frame, labels are placed from the bottom of the screen (nearest the
2333
+ // camera) up; one that would overlap a label already placed moves up above
2334
+ // it, with a thin line back down to its coworker. Where several crowd
2335
+ // together, they drop the to-do step and the folder.
2336
+ const TAG_GAP = 4, MAX_LIFT = 140;
2337
+ const CROWD_W = 150, CROWD_H = 46; // a nominal label, so squeezing can't feed back
2338
+ const tagV = new THREE.Vector3();
2339
+ function layoutTags(dt) {
2340
+ const doc = (pipWindow ?? window).document;
2341
+ if (doc.body.classList.contains('compact')) return; // no labels in small windows
2342
+ const items = [];
2343
+ for (const a of agents.concat(subs)) {
2344
+ const el = a.tag.element;
2345
+ if (!el.isConnected) continue;
2346
+ a.tag.getWorldPosition(tagV).project(camera);
2347
+ const key = a.lastTag + el.className;
2348
+ if (a.tagSizeFor !== key) {
2349
+ a.tagSize = [el.offsetWidth, el.offsetHeight];
2350
+ a.tagSizeFor = key;
2351
+ }
2352
+ items.push({ a, el, cx: ((tagV.x + 1) / 2) * viewW, cy: ((1 - tagV.y) / 2) * viewH, w: a.tagSize[0], h: a.tagSize[1] });
2353
+ }
2354
+ for (const it of items) {
2355
+ it.crowd = items.filter((o) => o !== it && !o.a.sub && Math.abs(o.cx - it.cx) < CROWD_W && Math.abs(o.cy - it.cy) < CROWD_H).length;
2356
+ }
2357
+ items.sort((p, q) => q.cy - p.cy);
2358
+ const placed = [];
2359
+ const k = 1 - Math.exp(-dt * 10);
2360
+ for (const it of items) {
2361
+ let y = it.cy;
2362
+ for (let guard = 0; guard < 16; guard++) {
2363
+ const hit = placed.find((p) => Math.abs(p.cx - it.cx) < (p.w + it.w) / 2 + TAG_GAP && Math.abs(p.y - y) < (p.h + it.h) / 2 + TAG_GAP);
2364
+ if (!hit) break;
2365
+ y = hit.y - (hit.h + it.h) / 2 - TAG_GAP;
2366
+ }
2367
+ placed.push({ cx: it.cx, y, w: it.w, h: it.h });
2368
+ const a = it.a;
2369
+ a.tagLift = (a.tagLift ?? 0) + (Math.min(MAX_LIFT, it.cy - y) - (a.tagLift ?? 0)) * k;
2370
+ if (Math.abs(a.tagLift) < 0.2) a.tagLift = 0;
2371
+ it.el.style.translate = a.tagLift ? `0 ${(-a.tagLift).toFixed(1)}px` : '';
2372
+ it.el.style.setProperty('--lift', `${a.tagLift.toFixed(1)}px`);
2373
+ a.squeezed = it.crowd >= 2;
2374
+ }
2375
+ }
2376
+
2377
+ // ── Click a coworker: a card with what it's doing and how its turn is going ──
2378
+ const card = document.createElement('div');
2379
+ card.id = 'card';
2380
+ card.className = 'panel';
2381
+ card.hidden = true;
2382
+ app.append(card);
2383
+ let cardAgent = null, cardDrawnAt = 0;
2384
+ const ring = new THREE.Mesh(new THREE.RingGeometry(0.42, 0.55, 40), new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.85 }));
2385
+ ring.rotation.x = -Math.PI / 2;
2386
+ ring.visible = false;
2387
+ scene.add(ring);
2388
+
2389
+
2390
+ /** Tool calls this turn, by what they were ("🌐 Using a web page" ×12), most first. */
2391
+ function toolChips(turnTools = {}) {
2392
+ const by = new Map();
2393
+ for (const [key, n] of Object.entries(turnTools)) {
2394
+ const [tool, cmd] = key.split(':');
2395
+ const name = toolInfo(tool, cmd).name.split(' · ')[0];
2396
+ by.set(name, (by.get(name) ?? 0) + n);
2397
+ }
2398
+ return [...by].sort((x, y) => y[1] - x[1]).slice(0, 8);
2399
+ }
2400
+
2401
+ function renderCard() {
2402
+ const a = cardAgent;
2403
+ const info = a.info ?? {};
2404
+ const now = a.wait
2405
+ ? `<div class="now waiting">${esc(T.card.waitingNow(T.ask[a.wait.kind] ?? T.ask.permission, fmt(a.wait.sec)))}</div>`
2406
+ : `<div class="now">${esc(a.status)}</div>`;
2407
+ const askLine = a.wait ? `<div class="task">${esc(a.wait.detail)}</div>${riskChip(a.wait.risk)}` : '';
2408
+ const turn = a.turnStartedAt
2409
+ ? [T.card.turn, span((Date.now() - a.turnStartedAt) / 1000)]
2410
+ : [T.card.lastTurn, info.lastTurnMs != null ? span(info.lastTurnMs / 1000) : T.card.none];
2411
+ const steps = a.steps ?? [];
2412
+ const done = steps.filter((x) => x === 'completed').length;
2413
+ const waits = info.waits ?? { count: 0, ms: 0 };
2414
+ const chips = toolChips(info.turnTools);
2415
+ card.innerHTML =
2416
+ `<div class="head"><span class="dot" style="background:${css(a.shirt)}"></span><span class="nm">${esc(a.name)}</span>${provBadge(a)}` +
2417
+ `<span class="proj">${esc(a.project ?? '')}</span><button class="x" title="${esc(T.card.close)}">×</button></div>` +
2418
+ now +
2419
+ askLine +
2420
+ (a.task ? `<div class="task">📋 ${esc(a.task)}</div>` : '') +
2421
+ `<div class="grid">` +
2422
+ `<div><span class="k">${turn[0]}</span><span class="v">${esc(turn[1])}</span></div>` +
2423
+ `<div><span class="k">${T.card.steps}</span><span class="v">${steps.length ? `${done} / ${steps.length}` : T.card.none}</span>` +
2424
+ (steps.length ? `<div class="steps"><i style="width:${((done / steps.length) * 100).toFixed(0)}%;background:${css(a.shirt)}"></i></div>` : '') + `</div>` +
2425
+ `<div><span class="k">${T.card.waited}</span><span class="v">${waits.count ? esc(T.card.times(waits.count, span(waits.ms / 1000))) : T.card.never}</span></div>` +
2426
+ `<div><span class="k">${T.card.onDuty}</span><span class="v">${a.firstSeenAt ? esc(span((Date.now() - a.firstSeenAt) / 1000)) : T.card.none}</span></div>` +
2427
+ `</div>` +
2428
+ `<div class="k tools-title">${T.card.tools}</div>` +
2429
+ (chips.length
2430
+ ? `<div class="chips">${chips.map(([name, n]) => `<span class="chip">${esc(name)}<b>×${n}</b></span>`).join('')}</div>`
2431
+ : `<div class="none">${T.card.noTools}</div>`);
2432
+ }
2433
+
2434
+ function openCard(a) {
2435
+ cardAgent = a;
2436
+ card.hidden = false;
2437
+ ring.material.color.set(a.shirt);
2438
+ renderCard();
2439
+ }
2440
+ function closeCard() {
2441
+ cardAgent = null;
2442
+ card.hidden = true;
2443
+ ring.visible = false;
2444
+ }
2445
+ card.addEventListener('click', (e) => { if (e.target.closest('.x')) closeCard(); });
2446
+ const onEsc = (e) => { if (e.key === 'Escape') closeCard(); };
2447
+ addEventListener('keydown', onEsc);
2448
+
2449
+ /** The coworker under the pointer: the nearest body or head within reach on screen. */
2450
+ const pickV = new THREE.Vector3();
2451
+ function agentAt(clientX, clientY) {
2452
+ const rect = renderer.domElement.getBoundingClientRect();
2453
+ const pxPerUnit = (rect.height * camera.zoom) / view();
2454
+ let best = null, bestD = 0.55 * pxPerUnit;
2455
+ for (const a of agents) {
2456
+ for (const y of [0.6, 1.2]) {
2457
+ pickV.set(a.pos.x, y, a.pos.z).project(camera);
2458
+ const d = Math.hypot(rect.left + ((pickV.x + 1) / 2) * rect.width - clientX, rect.top + ((1 - pickV.y) / 2) * rect.height - clientY);
2459
+ if (d < bestD) { bestD = d; best = a; }
2460
+ }
2461
+ }
2462
+ return best;
2463
+ }
2464
+ // A click (not a drag to turn the camera) picks a coworker, or closes the card.
2465
+ let downAt = null;
2466
+ renderer.domElement.addEventListener('pointerdown', (e) => (downAt = [e.clientX, e.clientY]));
2467
+ renderer.domElement.addEventListener('pointerup', (e) => {
2468
+ if (!downAt || Math.hypot(e.clientX - downAt[0], e.clientY - downAt[1]) > 6) return;
2469
+ downAt = null;
2470
+ const a = agentAt(e.clientX, e.clientY);
2471
+ if (a) openCard(a);
2472
+ else closeCard();
2473
+ });
2474
+ renderer.domElement.addEventListener('pointermove', (e) => {
2475
+ if (e.buttons) return;
2476
+ renderer.domElement.style.cursor = agentAt(e.clientX, e.clientY) ? 'pointer' : '';
2477
+ });
2478
+
2479
+ /** Each frame: keep the card fresh (twice a second) and the ring under its coworker. */
2480
+ function updateCard(now, t) {
2481
+ if (!cardAgent) return;
2482
+ if (!agents.includes(cardAgent)) return closeCard();
2483
+ ring.visible = true;
2484
+ ring.position.set(cardAgent.pos.x, 0.07, cardAgent.pos.z);
2485
+ ring.scale.setScalar(1 + 0.06 * Math.sin(t * 4));
2486
+ if (now - cardDrawnAt > 500) {
2487
+ cardDrawnAt = now;
2488
+ renderCard();
2489
+ }
2490
+ }
2491
+
2492
+ // ── Shared ──────────────────────────────────────────────────────
2493
+ const deskOf = new Map();
2494
+ const OVERFLOW = { n: 0 }; // live sessions waiting for a free desk
2495
+ const subs = [];
2496
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2497
+ const until = async (fn, ms) => { const end = performance.now() + ms; while (!fn() && performance.now() < end) await sleep(100); };
2498
+ const pick = (xs) => xs[Math.floor(Math.random() * xs.length)];
2499
+ window.__office = { agents, subs, camera, sph, controls, fpsMeter, renderer, targetFps, sun, testResult, raiseFlag, toolInfo, doorLeaf }; // for debugging in the console
2500
+ const badge = document.getElementById('mode-badge');
2501
+ const emptyCard = document.getElementById('empty');
2502
+
2503
+ // ── Demo mode (?demo): scripted agents, time ×8 ─────────────────
2504
+ function runDemo() {
2505
+ badge.textContent = T.demo;
2506
+ const atlas = new Agent({ name: 'Atlas', color: 0x6ec6ff, look: { hairColor: 0x3b2f2f }, home: DESKS[0].spot, project: 'pixel-office' });
2507
+ const nova = new Agent({ name: 'Nova', color: 0xff8fc8, look: { hairColor: 0xf3c56b }, home: DESKS[1].spot, project: 'api-server' });
2508
+ const echo = new Agent({ name: 'Echo', color: 0x9be38a, look: { hairColor: 0x6b4430 }, home: DESKS[2].spot, project: 'blog' });
2509
+ deskOf.set(atlas, DESKS[0]).set(nova, DESKS[1]).set(echo, DESKS[2]);
2510
+ for (const a of [atlas, nova, echo]) {
2511
+ a.demo = true;
2512
+ a.firstSeenAt = Date.now() - (20 + Math.random() * 90) * 60_000;
2513
+ a.info = { turnTools: { Read: 4, Edit: 6, 'Bash:test': 2, Grep: 3 }, waits: { count: 1, ms: 42_000 }, lastTurnMs: null };
2514
+ }
2515
+ atlas.turnStartedAt = Date.now() - 754_000; // a long one
2516
+ nova.turnStartedAt = Date.now() - 95_000;
2517
+ echo.turnStartedAt = Date.now() - 12_000;
2518
+ atlas.steps = ['completed', 'completed', 'in_progress', 'pending', 'pending'];
2519
+ nova.steps = ['completed', 'in_progress', 'pending'];
2520
+ echo.steps = ['in_progress', 'pending', 'pending', 'pending'];
2521
+ /** Now and then a step gets done; a finished list is followed by a new one,
2522
+ * written up on the whiteboard. */
2523
+ async function progress(a) {
2524
+ if (Math.random() < 0.45) return;
2525
+ const s = a.steps;
2526
+ const cur = s.indexOf('in_progress');
2527
+ if (cur >= 0) s[cur] = 'completed';
2528
+ const next = s.indexOf('pending');
2529
+ if (next >= 0) s[next] = 'in_progress';
2530
+ if (next >= 0) return;
2531
+ await sleep(2500);
2532
+ a.steps = Array.from({ length: 3 + Math.floor(Math.random() * 3) }, (_, k) => (k ? 'pending' : 'in_progress'));
2533
+ a.planGen = (a.planGen ?? 0) + 1;
2534
+ a.status = T.writingPlan;
2535
+ log(`<b style="color:${css(a.shirt)}">${a.name}</b> ${a.status}`);
2536
+ await a.goTo(freeSlot('plan', a), SPOTS.plan.face);
2537
+ a.activity = 'write';
2538
+ await sleep(PLAN_WRITE_SEC * 1000);
2539
+ a.activity = null;
2540
+ }
2541
+ const FILES = ['App.tsx', 'cli.ts', 'mood.ts', 'README.md', 'renderer.ts'];
2542
+ const randomWork = () => pick([
2543
+ ['Edit', pick(FILES)], ['Edit', pick(FILES)], ['Read', pick(FILES)], ['Bash', 'npm test', 'test'],
2544
+ ['Grep', '"patience"'], ['WebSearch', T.demoSearch], ['Write', 'notes.md'],
2545
+ ['Bash', 'git commit', 'git'], ['Bash', 'npm install', 'install'], ['Bash', 'npm run build', 'build'],
2546
+ ]);
2547
+
2548
+ async function spawnSub(parent, name) {
2549
+ const near = parent.pos.clone().add(new THREE.Vector3((Math.random() - 0.5) * 1.2, 0, 0.9));
2550
+ puff(near);
2551
+ const s = new Agent({ name, color: parent.shirt, look: { hairColor: 0x6b4430 }, home: near, project: '', sub: true });
2552
+ subs.push(s);
2553
+ log(`<b style="color:${css(parent.shirt)}">${parent.name}</b> ${esc(T.spawned(name.replace(T.helper, '').trim()))}`);
2554
+ for (let i = 0; i < 2; i++) {
2555
+ const key = pick(['files', 'web']);
2556
+ const spot = freeSlot(key, s);
2557
+ await s.goTo(spot, SPOTS[key].face);
2558
+ s.activity = SPOTS[key].act;
2559
+ await sleep(2200);
2560
+ s.activity = null;
2561
+ }
2562
+ await s.goTo(parent.pos.clone().add(new THREE.Vector3(0.8, 0, -0.6)), 0);
2563
+ puff(s.pos);
2564
+ scene.remove(s.ch.root);
2565
+ s.tag.element.remove();
2566
+ subs.splice(subs.indexOf(s), 1);
2567
+ }
2568
+
2569
+ (async function atlasLoop() {
2570
+ await sleep(1800);
2571
+ for (;;) { await atlas.work(...randomWork()); await sleep(2200 + Math.random() * 1600); await progress(atlas); }
2572
+ })();
2573
+ (async function novaLoop() {
2574
+ await sleep(2600);
2575
+ for (;;) {
2576
+ for (let i = 0; i < 2; i++) { await nova.work(...randomWork()); await sleep(2400); await progress(nova); }
2577
+ await nova.goTo(nova.home, nova.homeFace);
2578
+ nova.ask('permission', askDetail('Bash', null, 'npm publish --access public'), { level: 'high', why: 'publish' });
2579
+ await until(() => !nova.wait, 60000);
2580
+ nova.resolve();
2581
+ await sleep(800);
2582
+ await nova.goTo(nova.home, nova.homeFace);
2583
+ nova.activity = 'type';
2584
+ await sleep(2500);
2585
+ }
2586
+ })();
2587
+ (async function echoLoop() {
2588
+ await sleep(3400);
2589
+ for (;;) {
2590
+ spawnSub(echo, `${T.helper} Explore`);
2591
+ await sleep(900);
2592
+ spawnSub(echo, `${T.helper} Plan`);
2593
+ for (let i = 0; i < 3; i++) { await echo.work(...randomWork()); await sleep(2600); await progress(echo); }
2594
+ echo.ask('question', T.demoQuestion);
2595
+ await until(() => !echo.wait, 9000);
2596
+ echo.resolve();
2597
+ await echo.goTo(echo.home, echo.homeFace);
2598
+ echo.activity = 'type';
2599
+ await sleep(3000);
2600
+ }
2601
+ })();
2602
+ log(`<span style="color:#a07bff">${T.demoHello}</span>`);
2603
+ renderApprovals(true);
2604
+ }
2605
+
2606
+ // ── Live mode: one coworker per Claude Code session ─────────────
2607
+ function runLive() {
2608
+ const PALETTE = [0x6ec6ff, 0xff8fc8, 0x9be38a, 0xffc46b, 0xb79cff, 0x7fd8d0];
2609
+ // Natural hair colours, plus a couple of fun ones.
2610
+ const HAIR = [0x3b2f2f, 0xf3c56b, 0x6b4430, 0x2a2a33, 0xc8692c, 0x8a5a3a, 0xe58fae, 0x5a4a8a];
2611
+ const QUESTION = { AskUserQuestion: 'question', ExitPlanMode: 'plan' };
2612
+ const bySession = new Map(); // session id -> Agent
2613
+ const helpers = new Map(); // sub-agent id -> Agent
2614
+ const overflow = new Map(); // sessions with no free desk: id -> latest session state
2615
+ let skew = 0; // server clock - client clock
2616
+
2617
+ const hash = (t) => [...t].reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 7);
2618
+ const toClient = (serverMs) => serverMs - skew;
2619
+
2620
+ function updateEmpty() {
2621
+ emptyCard.hidden = bySession.size > 0;
2622
+ OVERFLOW.n = overflow.size;
2623
+ renderApprovals(true);
2624
+ }
2625
+
2626
+ function coworker(sess, { enter = true } = {}) {
2627
+ if (bySession.has(sess.id)) return bySession.get(sess.id);
2628
+ const taken = (seat) => [...bySession.values()].some((a) => a.desk === seat);
2629
+ const desk = DESKS.find((d) => !taken(d)) ?? SPARE_SEATS.find((d) => !taken(d));
2630
+ if (!desk) {
2631
+ overflow.set(sess.id, sess);
2632
+ updateEmpty();
2633
+ return null;
2634
+ }
2635
+ const used = new Set([...bySession.values()].map((a) => a.shirt));
2636
+ const h = hash(sess.id);
2637
+ const color = [...PALETTE.slice(h % PALETTE.length), ...PALETTE].find((c) => !used.has(c)) ?? PALETTE[h % PALETTE.length];
2638
+ // >>> not >>: the hash is unsigned, and a negative index used to give white hair.
2639
+ const usedHair = new Set([...bySession.values()].map((a) => a.hair));
2640
+ const hi = (h >>> 4) % HAIR.length;
2641
+ const hair = [...HAIR.slice(hi), ...HAIR].find((c) => !usedHair.has(c)) ?? HAIR[hi];
2642
+ // Several sessions in one folder: "A2 · 1", "A2 · 2", …
2643
+ const base = sess.project ?? sess.id.slice(0, 6);
2644
+ const same = [...bySession.values()].filter((x) => x.baseName === base);
2645
+ let name = base;
2646
+ if (same.length) {
2647
+ for (const x of same) if (x.name === base) x.name = `${base} · 1`;
2648
+ const taken = new Set(same.map((x) => x.name));
2649
+ let n = 2;
2650
+ while (taken.has(`${base} · ${n}`)) n++;
2651
+ name = `${base} · ${n}`;
2652
+ }
2653
+ const a = new Agent({
2654
+ name: sess.title ?? name,
2655
+ color,
2656
+ look: { hairColor: hair },
2657
+ home: desk.spot,
2658
+ homeFace: desk.face,
2659
+ project: sess.title ? base : '#' + sess.id.slice(0, 4),
2660
+ });
2661
+ a.desk = desk;
2662
+ a.provider = sess.provider ?? 'claude';
2663
+ a.hair = hair;
2664
+ a.baseName = base;
2665
+ a.session = sess.id;
2666
+ if (DESKS.includes(desk)) deskOf.set(a, desk);
2667
+ bySession.set(sess.id, a);
2668
+ overflow.delete(sess.id);
2669
+ if (enter) a.enter(desk.spot, desk.face);
2670
+ log(`<b style="color:${css(color)}">${esc(a.name)}</b> ${T.arrived}`);
2671
+ updateEmpty();
2672
+ return a;
2673
+ }
2674
+
2675
+ function dismiss(sessionId) {
2676
+ const a = bySession.get(sessionId);
2677
+ overflow.delete(sessionId);
2678
+ if (!a) return;
2679
+ for (const [id, h] of helpers) if (h.parent === a) { h.leave(); helpers.delete(id); }
2680
+ log(`<b style="color:${css(a.shirt)}">${esc(a.name)}</b> ${T.left}`);
2681
+ a.exit();
2682
+ bySession.delete(sessionId);
2683
+ // A desk freed up: whoever has been on the sofa or at the whiteboard longest moves over.
2684
+ if (DESKS.includes(a.desk)) {
2685
+ const spare = [...bySession.values()].find((x) => SPARE_SEATS.includes(x.desk));
2686
+ if (spare) moveHome(spare, a.desk);
2687
+ }
2688
+ // A seat just freed up: seat the longest-waiting overflow session.
2689
+ const [nextId, nextSess] = overflow.entries().next().value ?? [];
2690
+ if (nextId) {
2691
+ overflow.delete(nextId);
2692
+ const b = coworker(nextSess);
2693
+ if (b) sync(b, nextSess);
2694
+ }
2695
+ updateEmpty();
2696
+ }
2697
+
2698
+ /** Give a coworker a new home seat, and walk it over when it's at home now. */
2699
+ function moveHome(a, seat) {
2700
+ const wasHome = a.pos.distanceTo(a.home) < 0.05 && a.path.length === 0;
2701
+ a.desk = seat;
2702
+ a.home = seat.spot;
2703
+ a.homeFace = seat.face;
2704
+ if (DESKS.includes(seat)) deskOf.set(a, seat);
2705
+ if (wasHome && !a.wait) a.walkTo(seat.spot, seat.face, a.activity); // at once: someone may take its seat
2706
+ }
2707
+
2708
+ function helper(parent, id, type) {
2709
+ if (helpers.has(id)) return helpers.get(id);
2710
+ const near = parent.pos.clone().add(new THREE.Vector3((Math.random() - 0.5) * 1.2, 0, 0.9));
2711
+ puff(near);
2712
+ const h = new Agent({ name: `${T.helper} ${type ?? ''}`.trim(), color: parent.shirt, look: { hairColor: 0x6b4430 }, home: near, project: '', sub: true });
2713
+ h.parent = parent;
2714
+ subs.push(h);
2715
+ helpers.set(id, h);
2716
+ log(`<b style="color:${css(parent.shirt)}">${esc(parent.name)}</b> ${esc(T.spawned(type))}`);
2717
+ return h;
2718
+ }
2719
+
2720
+ /** Bring a coworker in line with the server's view of its session. */
2721
+ /** When the current turn started (client clock), while the session is working. */
2722
+ const applyTurn = (a, sess) => {
2723
+ a.turnStartedAt = sess.phase === 'working' && sess.turnStart != null ? toClient(sess.turnStart) : null;
2724
+ a.firstSeenAt = toClient(sess.firstSeen);
2725
+ a.info = { turnTools: sess.turnTools ?? {}, waits: sess.waits ?? { count: 0, ms: 0 }, lastTurnMs: sess.lastTurnMs };
2726
+ };
2727
+
2728
+ function sync(a, sess) {
2729
+ a.applySession(sess, false); // a snapshot: lists already up don't need writing
2730
+ applyTurn(a, sess);
2731
+ const w = sess.waiting;
2732
+ if (w && !a.wait) a.liveAsk(w.kind, w.kind === 'permission' ? askDetail(w.tool, w.cmd, w.label) : w.label ?? w.tool, toClient(w.since), w.risk);
2733
+ else if (!w && a.wait) a.resolve({ quiet: true });
2734
+ if (!w) {
2735
+ if (sess.tool) a.liveWork(sess.tool, sess.label, sess.cmd);
2736
+ else if (sess.phase === 'idle') a.goIdle();
2737
+ else a.think();
2738
+ }
2739
+ for (const [id, sub] of Object.entries(sess.subagents ?? {})) {
2740
+ const h = helper(a, id, sub.type);
2741
+ const sw = sub.waiting;
2742
+ if (sw && !h.wait) h.liveAsk(sw.kind, sw.kind === 'permission' ? askDetail(sw.tool, sw.cmd, sw.label) : sw.label ?? sw.tool, toClient(sw.since), sw.risk);
2743
+ else if (sub.tool && !h.wait) h.liveWork(sub.tool, sub.label, sub.cmd);
2744
+ }
2745
+ for (const [id, h] of helpers) if (h.parent === a && !(id in (sess.subagents ?? {}))) { h.leave(); helpers.delete(id); }
2746
+ }
2747
+
2748
+ let firstSnapshot = true; // who's here when the page opens is already at work
2749
+ function onSnapshot(msg) {
2750
+ skew = msg.now - Date.now();
2751
+ for (const id of [...overflow.keys()]) if (!(id in msg.sessions)) overflow.delete(id);
2752
+ for (const id of [...bySession.keys()]) if (!(id in msg.sessions)) dismiss(id);
2753
+ for (const sess of Object.values(msg.sessions).sort((x, y) => x.firstSeen - y.firstSeen)) {
2754
+ const a = coworker(sess, { enter: !firstSnapshot });
2755
+ if (a) sync(a, sess);
2756
+ }
2757
+ firstSnapshot = false;
2758
+ updateEmpty();
2759
+ renderApprovals(true);
2760
+ }
2761
+
2762
+ function onUpdate({ ts, event: ev, session: sess }) {
2763
+ skew = ts - Date.now();
2764
+ if (ev.event === 'SessionEnd' || !sess) return dismiss(ev.session);
2765
+ const a = coworker(sess);
2766
+ if (!a) return;
2767
+ a.applySession(sess);
2768
+ applyTurn(a, sess);
2769
+ const now = toClient(ts);
2770
+
2771
+ if (ev.agent) {
2772
+ const h = ev.event === 'SubagentStop' ? helpers.get(ev.agent) : helper(a, ev.agent, ev.agentType ?? sess.subagents?.[ev.agent]?.type);
2773
+ if (!h) return;
2774
+ if (ev.event === 'SubagentStop') {
2775
+ h.walkTo(a.pos.clone().add(new THREE.Vector3(0.8, 0, -0.6)), 0, null);
2776
+ setTimeout(() => { h.leave(); helpers.delete(ev.agent); }, 2500);
2777
+ } else if (ev.event === 'PreToolUse') {
2778
+ if (h.wait) h.resolve();
2779
+ if (QUESTION[ev.tool]) h.liveAsk(QUESTION[ev.tool], ev.label ?? ev.tool, now);
2780
+ else h.liveWork(ev.tool, ev.label, ev.cmd);
2781
+ } else if (ev.event === 'PermissionRequest' || (ev.event === 'Notification' && ev.notification === 'permission_prompt')) {
2782
+ h.liveAsk('permission', askDetail(ev.tool, ev.cmd, ev.label), now, ev.risk);
2783
+ } else if (ev.event === 'PostToolUse' || ev.event === 'PostToolUseFailure') {
2784
+ if (ev.tool === 'Bash' && ev.cmd === 'test') testResult(ev.event === 'PostToolUse', h);
2785
+ if (h.wait) h.resolve();
2786
+ else if (ev.event === 'PostToolUseFailure') h.oops();
2787
+ else h.thinkSoon();
2788
+ }
2789
+ return;
2790
+ }
2791
+
2792
+ switch (ev.event) {
2793
+ case 'UserPromptSubmit':
2794
+ if (a.wait) a.resolve({ quiet: true });
2795
+ a.status = T.newTask;
2796
+ a.thinkAt = null;
2797
+ a.intend(a.home, a.homeFace, 'think');
2798
+ break;
2799
+ case 'PreToolUse':
2800
+ if (a.wait && !QUESTION[ev.tool]) a.resolve();
2801
+ if (QUESTION[ev.tool]) a.liveAsk(QUESTION[ev.tool], ev.label ?? (ev.tool === 'ExitPlanMode' ? T.planLabel : T.questionLabel), now);
2802
+ else a.liveWork(ev.tool, ev.label, ev.cmd);
2803
+ break;
2804
+ case 'PermissionRequest':
2805
+ a.liveAsk('permission', askDetail(ev.tool, ev.cmd, ev.label), now, ev.risk);
2806
+ break;
2807
+ case 'Notification':
2808
+ if (ev.notification === 'permission_prompt') a.liveAsk('permission', ev.tool ?? '', now);
2809
+ break;
2810
+ case 'PostToolUse':
2811
+ case 'PostToolUseFailure':
2812
+ if (ev.tool === 'Bash' && ev.cmd === 'test') testResult(ev.event === 'PostToolUse', a);
2813
+ if (a.wait) {
2814
+ a.resolve();
2815
+ a.intend(a.home, a.homeFace, 'think'); // after the cheer, back to the desk
2816
+ a.status = T.thinking;
2817
+ } else if (ev.event === 'PostToolUseFailure') {
2818
+ a.oops();
2819
+ } else {
2820
+ a.thinkSoon();
2821
+ }
2822
+ break;
2823
+ case 'Stop':
2824
+ if (a.wait) a.resolve({ quiet: true });
2825
+ // A long job just finished: a little cheer, and tell you.
2826
+ if ((sess.lastTurnMs ?? 0) >= DONE_ALERT_MIN_SEC * 1000) {
2827
+ a.cheerUntil = a.t + 1.8;
2828
+ log(`<span style="color:#4caf6e">${esc(T.doneLog(a.name, fmt(sess.lastTurnMs / 1000)))}</span>`);
2829
+ alertDone(a, sess.lastTurnMs);
2830
+ }
2831
+ a.goIdle();
2832
+ break;
2833
+ default:
2834
+ break;
2835
+ }
2836
+ if (a.planningPending) {
2837
+ a.planningPending = false;
2838
+ a.startPlanning();
2839
+ }
2840
+ renderApprovals(true);
2841
+ }
2842
+
2843
+ function connect() {
2844
+ const es = new EventSource('/events');
2845
+ es.onopen = () => {
2846
+ badge.textContent = T.live;
2847
+ badge.className = 'badge live';
2848
+ };
2849
+ es.onerror = () => {
2850
+ badge.textContent = T.down;
2851
+ badge.className = 'badge down';
2852
+ };
2853
+ es.onmessage = (m) => {
2854
+ const msg = JSON.parse(m.data);
2855
+ if (msg.type === 'snapshot') onSnapshot(msg);
2856
+ else if (msg.type === 'update') onUpdate(msg);
2857
+ if (msg.stats || msg.type === 'stats') {
2858
+ Object.assign(statsToday, msg.stats ?? msg.today, { live: true });
2859
+ renderApprovals(true);
2860
+ }
2861
+ };
2862
+ }
2863
+ updateEmpty();
2864
+ connect();
2865
+ }
2866
+
2867
+ if (new URLSearchParams(location.search).has('demo')) runDemo();
2868
+ else runLive();
2869
+
2870
+ // ── Loop ────────────────────────────────────────────────────────
2871
+ const clock = new THREE.Clock();
2872
+ let intro = 0;
2873
+ let lastDraw = -Infinity;
2874
+ function frame(now = performance.now()) {
2875
+ // The pop-out window keeps animating even when this tab is in the background.
2876
+ const host = pipWindow ?? window;
2877
+ host.requestAnimationFrame(frame);
2878
+ if (host.document.hidden) return; // nobody can see it
2879
+ const fps = targetFps(now);
2880
+ if (fps && now - lastDraw < 1000 / fps - 2) return;
2881
+ lastDraw = now;
2882
+ fpsMeter.frames++;
2883
+ if (now - fpsMeter.since >= 1000) {
2884
+ fpsMeter.fps = Math.round((fpsMeter.frames * 1000) / (now - fpsMeter.since));
2885
+ fpsMeter.frames = 0;
2886
+ fpsMeter.since = now;
2887
+ }
2888
+
2889
+ const dt = Math.min(clock.getDelta(), 0.05);
2890
+ const t = clock.elapsedTime;
2891
+
2892
+ if (intro < 1) {
2893
+ intro = Math.min(1, intro + dt / 2.4);
2894
+ camera.zoom = 0.55 + 0.45 * (1 - Math.pow(1 - intro, 3));
2895
+ camera.updateProjectionMatrix();
2896
+ }
2897
+ if (!userTook) {
2898
+ sph.theta = Math.PI / 4 + Math.sin(t * 0.12) * 0.28;
2899
+ camera.position.setFromSpherical(sph).add(target);
2900
+ camera.lookAt(target);
2901
+ }
2902
+ controls.update();
2903
+
2904
+ globe.rotation.y += dt * (agents.some((a) => a.activity === 'point') || subs.some((s) => s.activity === 'point') ? 2.2 : 0.3);
2905
+ const busyTerm = [...agents, ...subs].some((a) => a.activity === 'type' && a.pos.distanceTo(SPOTS.terminal.pos) < 1.2);
2906
+ LEDS.forEach((l, i) => (l.visible = Math.sin(t * (busyTerm ? 14 : 3) + i * 1.7) > -0.2));
2907
+ // The wall clock shows the time the office follows.
2908
+ const hour = localHour();
2909
+ window.__clockHand.rotation.z = -(hour % 1) * Math.PI * 2;
2910
+ if (testLight.state !== 'idle' && now > testLight.until) testLight.state = 'idle';
2911
+ const lampOn = { green: testLight.state === 'pass', red: testLight.state === 'fail', yellow: testLight.state === 'run' && Math.sin(t * 9) > 0 };
2912
+ for (const [k, lamp] of Object.entries(testLamps)) {
2913
+ lamp.material.color.copy(lampOn[k] ? lamp.userData.on : lamp.userData.off);
2914
+ lamp.material.emissiveIntensity = lampOn[k] ? 1.1 : 0;
2915
+ }
2916
+ const flagTo = now < flagUntil ? 0 : -Math.PI / 2;
2917
+ mailFlag.rotation.z += (flagTo - mailFlag.rotation.z) * (1 - Math.exp(-dt * 8));
2918
+ skyTex.offset.x = (t * 0.006) % 1;
2919
+ window.__clockHour.rotation.z = -((hour % 12) / 12) * Math.PI * 2;
2920
+ for (const [a, d] of deskOf) {
2921
+ const on = a.activity === 'type' && a.pos.distanceTo(d.spot) < 0.3;
2922
+ d.logo.material.color.set(on ? a.shirt : 0xffffff);
2923
+ d.logo.scale.setScalar(on ? 1 + 0.15 * Math.sin(t * 6) : 1);
2924
+ d.screen.material.color.set(on ? 0xffffff : a.pos.distanceTo(d.spot) < 0.3 ? 0xa8acc0 : 0x4a4f66);
2925
+ if (on) d.screen.material.map.offset.y = (d.screen.material.map.offset.y + dt * 0.25) % 1;
2926
+ }
2927
+ const anyone = agents.some((a) => a.wait);
2928
+ deskLamp.material.emissiveIntensity = anyone ? 0.9 + 0.6 * Math.sin(t * 6) : 0.2;
2929
+ deskLamp.userData.light.intensity = anyone ? 6 + 4 * Math.sin(t * 6) : 0;
2930
+
2931
+ for (const a of agents) a.update(dt);
2932
+ updateBoard(dt);
2933
+ updateDoor(dt);
2934
+ updateCard(now, t);
2935
+ for (const s of subs) s.update(dt);
2936
+ updateParticles(dt);
2937
+ updateZs(dt);
2938
+ renderApprovals(false);
2939
+
2940
+ renderer.render(scene, camera);
2941
+ labels.render(scene, camera);
2942
+ layoutTags(dt);
2943
+ }
2944
+ frame();
2945
+ </script>
2946
+ </body>
2947
+ </html>