agenthub/frontend/components/OfficeScene.tsx

1245 lines
43 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"use client";
// 像素办公室(纯 canvas 程序化绘制,不用图片资产)。
// 每人一个工位,屏幕显示在跑什么,墙上只有一块看板(左栏在岗状态、右栏任务队列);
// 忙 = 坐工位敲键盘,闲 = 茶水间/沙发/讨论区轮着去,异常 = 站在机柜那边,离线 = 椅子空着。
// 产出不进画面(明细在右侧面板):这里只画"谁在干什么"的状态。
// 房间配色(墙、地板、窗外天色、机柜、看板纸面)跟着控制台主题在夜景/白天之间切换,
// 见 lib/office-palette.ts;人偶和家具的颜色不跟着变。
// u = 一格像素块的边长,由工位数量算出来(见 lib/office-layout.ts);
// canvas 后备缓冲跟着显示尺寸 × devicePixelRatio 走,所以放到多大都不糊。
import { useEffect, useRef } from "react";
import {
AREA,
ART_W,
LABEL_H,
SCENE_H,
SCENE_W,
WALL_H,
clamp,
layoutScene,
type DeskLayout,
type Mood,
type SceneLayout,
} from "@/lib/office-layout";
import { OFFICE_DARK, officePalette, type OfficePalette } from "@/lib/office-palette";
import { useTheme } from "@/lib/theme";
import type { Agent, Task } from "@/lib/types";
const W = SCENE_W;
const H = SCENE_H;
const CORRIDOR_X = 1158;
const BAR_ENTRY_X = 344; // 去茶水间的进入口(吧台右侧的空地)
const SIDE_ENTRY_X = 746; // 去休息区/讨论区的竖道(两块地毯中间的空地)
const INK = "#1b1812";
const CREAM = "#e9e3d7";
const MUTED = "#a09888";
const GOLD = "#c9a227";
const GREEN = "#4ade80";
const AMBER = "#facc15";
const RED = "#ef4444";
// 房间配色跟着控制台主题走(人偶和家具的颜色不跟着变,见 lib/office-palette.ts)。
// 画布每帧都读这个模块级的当前值,所以组件里改一次就等于当场换装,不用重挂画布。
let PAL: OfficePalette = OFFICE_DARK;
const MOOD_COLOR: Record<Mood, string> = {
busy: GOLD,
idle: GREEN,
warn: AMBER,
off: "#7a7166",
};
const STATUS_WORD: Record<Mood, string> = { busy: "在忙", idle: "空闲", warn: "异常", off: "离线" };
const DRIVER_COLORS: Record<string, [string, string]> = {
nanobot: ["#c9a227", "#8a6f4d"],
openclaw: ["#4a90c2", "#3d6d91"],
mock: ["#8b7ba8", "#6b5f85"],
connector: ["#5aa469", "#437a4e"],
openai_compatible: ["#c2685a", "#8f4b41"],
};
// 每种 Agent 类型一套"行头":工装配色 + 头顶物件(见 backend/agenthub/db/models.py: AGENT_TYPES)。
// 类型不明(custom)时才退回按 driver 上色,这样老数据也有颜色,新数据一眼能认出是哪家。
// 坐标是"格子"坐标,和身体网格同一套:y=0 是发顶,可以取负值(帽子/天线画在头顶上方)。
type MarkCell = { x: number; y: number; w: number; h: number; color: string };
const TYPE_STYLES: Record<string, { shirt: [string, string]; marks: MarkCell[] }> = {
// nanobot:金色工装 + 头顶天线
nanobot: {
shirt: ["#c9a227", "#8a6f4d"],
marks: [
{ x: 4, y: -2, w: 1, h: 2, color: "#8a6f4d" },
{ x: 3, y: -4, w: 3, h: 2, color: "#ffd166" },
],
},
// DeepSeek Harness:靛蓝工装 + 青色护目镜 + 头箍
deepseek_harness: {
shirt: ["#4f6bed", "#3346a8"],
marks: [
{ x: 2, y: -2, w: 5, h: 2, color: "#3346a8" },
{ x: 1, y: 3, w: 7, h: 1, color: "#22d3ee" },
],
},
// OpenClaw:钢蓝工装 + 鸭舌帽
openclaw: {
shirt: ["#4a90c2", "#3d6d91"],
marks: [
{ x: 1, y: -1, w: 7, h: 2, color: "#e6edf5" },
{ x: 0, y: 1, w: 9, h: 1, color: "#3d6d91" },
],
},
// Hermes:琥珀工装 + 帽羽 + 头环(信使的双翼)
hermes: {
shirt: ["#e08b2f", "#a35f1c"],
marks: [
{ x: 0, y: 1, w: 1, h: 2, color: "#f4e3c2" },
{ x: 8, y: 1, w: 1, h: 2, color: "#f4e3c2" },
{ x: 3, y: 0, w: 3, h: 1, color: "#ffd166" },
{ x: 4, y: -3, w: 1, h: 2, color: "#e08b2f" },
],
},
};
// 离线/异常时整体压灰,别让帽子比人还显眼
const DIM_MARK = "#8a8478";
const SKINS = ["#e8bd93", "#d8a87c", "#f0cfae", "#c79468"];
const HAIRS = ["#3c352b", "#5a3b28", "#2b2620", "#6d5334", "#4a3350"];
const driverColors = (driver: string): [string, string] => {
const hit = DRIVER_COLORS[driver];
if (hit) return hit;
let hash = 0;
for (const ch of driver) hash = (hash * 31 + ch.charCodeAt(0)) % 360;
return [`hsl(${hash} 45% 55%)`, `hsl(${hash} 35% 40%)`];
};
const hashOf = (seed: string) => {
let hash = 0;
for (const ch of seed) hash = (hash * 31 + ch.charCodeAt(0)) % 9973;
return hash;
};
const outfitOf = (agent: Agent, dim: boolean): Outfit => {
const hash = hashOf(agent.id + agent.name);
const style = TYPE_STYLES[agent.agent_type];
return {
skin: dim ? "#9a938a" : SKINS[hash % SKINS.length],
hair: dim ? "#4b4740" : HAIRS[(hash >> 3) % HAIRS.length],
shirt: (style ? style.shirt : driverColors(agent.driver))[dim ? 1 : 0],
pants: dim ? "#5f5a52" : "#3c352b",
shoe: dim ? "#413c35" : "#241f19",
};
};
/** 这个 Agent 头顶该顶什么(类型没认出来就不顶)。 */
const marksOf = (agent: Agent): MarkCell[] => TYPE_STYLES[agent.agent_type]?.marks ?? [];
/* ---------------- 人偶:身体 + 可替换的腿部动作 ---------------- */
const BODY_FRONT = [
"..HHHHH..",
".HHHHHHH.",
".HHHHHHH.",
".HSESSEH.",
".HSSSSSH.",
"..SSSSS..",
"..BBBBB..",
".BBBBBBB.",
"SSBBBBBSS",
".BBBBBBB.",
];
const BODY_SIDE = [
"...HHHH..",
"..HHHHHH.",
"..HHHHHH.",
"..HSESHH.",
"..HSSSHH.",
"...SSS...",
"...BBB...",
"..BBBBB..",
".BBBBBBB.",
".BBBBBB..",
];
const LEGS_STAND = ["..PPPPP..", "..PP.PP..", "..PP.PP..", "..FF.FF.."];
const LEGS_WIDE = ["..PPPPP..", "..PP.PP..", ".PP...PP.", "FF.....FF"];
const LEGS_CLOSE = ["..PPPPP..", "..PPPPPP.", "...PPPP..", "..FFF.FF."];
type Outfit = { skin: string; hair: string; shirt: string; pants: string; shoe: string };
type Ctx = CanvasRenderingContext2D;
function px(ctx: Ctx, x: number, y: number, w: number, h: number, color: string) {
ctx.fillStyle = color;
ctx.fillRect(Math.round(x), Math.round(y), Math.round(w), Math.round(h));
}
/** 按"格子"画:原点 + 边长 u,一格就是一个像素块,取整后边缘锐利。 */
type Pen = (gx: number, gy: number, gw: number, gh: number, color: string) => void;
function pen(ctx: Ctx, ox: number, oy: number, u: number): Pen {
return (gx, gy, gw, gh, color) => {
ctx.fillStyle = color;
ctx.fillRect(
Math.round(ox + gx * u),
Math.round(oy + gy * u),
Math.max(1, Math.round(gw * u)),
Math.max(1, Math.round(gh * u)),
);
};
}
function text(
ctx: Ctx,
value: string,
x: number,
y: number,
color = CREAM,
align: CanvasTextAlign = "left",
size = 11,
) {
ctx.font = `${size}px ArkPixel, monospace`;
ctx.textAlign = align;
ctx.fillStyle = color;
ctx.fillText(value, Math.round(x), Math.round(y));
ctx.textAlign = "left";
}
const fitCache = new Map<string, string>();
/** 按像素宽度截断,文字永远不会捅出外框。 */
function fitText(ctx: Ctx, value: string, maxWidth: number): string {
const key = `${Math.round(maxWidth)}|${value}`;
const cached = fitCache.get(key);
if (cached !== undefined) return cached;
let out = value;
if (ctx.measureText(value).width > maxWidth) {
out = "";
for (const ch of value) {
if (ctx.measureText(out + ch + "…").width > maxWidth) break;
out += ch;
}
out += "…";
}
if (fitCache.size > 800) fitCache.clear();
fitCache.set(key, out);
return out;
}
/** 折行 + 截断:屏幕再小也不会漏字。 */
function clipLines(ctx: Ctx, value: string, maxW: number, lines: number, size: number): string[] {
ctx.font = `${size}px ArkPixel, monospace`;
const rest = value.replace(/\s+/g, " ").trim();
const out: string[] = [];
let left = rest;
while (left && out.length < lines) {
let take = 0;
for (let i = 1; i <= left.length; i += 1) {
if (ctx.measureText(left.slice(0, i)).width > maxW) break;
take = i;
}
take = Math.max(1, take);
const last = out.length === lines - 1;
out.push(
last && take < left.length ? `${left.slice(0, Math.max(1, take - 1))}…` : left.slice(0, take),
);
left = left.slice(take);
}
return out;
}
function shadow(ctx: Ctx, cx: number, y: number, w: number, alpha = 0.3) {
px(ctx, cx - w / 2, y, w, 3, `rgba(${PAL.shadowRGB},${alpha})`);
px(ctx, cx - w / 2 + 4, y + 3, Math.max(2, w - 8), 2, `rgba(${PAL.shadowRGB},${alpha * 0.6})`);
px(ctx, cx - w / 2 + 4, y - 3, Math.max(2, w - 8), 3, `rgba(${PAL.shadowRGB},${alpha * 0.6})`);
}
/** face: 0 = 正面,1 = 右侧身,-1 = 左侧身。脚底对齐 (cx, feetY)。
* marks 是这套类型的头饰(帽子/天线/护目镜),跟着人一起走、一起转身。 */
function sprite(
ctx: Ctx,
cx: number,
feetY: number,
u: number,
fit: Outfit,
legs: string[],
face: -1 | 0 | 1,
marks: MarkCell[] = [],
dim = false,
) {
const grid = [...(face === 0 ? BODY_FRONT : BODY_SIDE), ...legs];
const pal: Record<string, string> = {
H: fit.hair,
S: fit.skin,
E: "#2b2620",
B: fit.shirt,
P: fit.pants,
F: fit.shoe,
};
const ox = Math.round(cx - (9 * u) / 2);
const oy = Math.round(feetY - grid.length * u);
grid.forEach((row, gy) => {
row.split("").forEach((ch, gx) => {
if (ch === ".") return;
px(ctx, ox + (face === -1 ? 8 - gx : gx) * u, oy + gy * u, u, u, pal[ch]);
});
});
// 头饰:侧身时水平镜像(和身体同一套坐标),离线时压灰
marks.forEach((mark) => {
const gx = face === -1 ? 8 - (mark.x + mark.w - 1) : mark.x;
px(ctx, ox + gx * u, oy + mark.y * u, mark.w * u, mark.h * u, dim ? DIM_MARK : mark.color);
});
}
function bubble(
ctx: Ctx,
cx: number,
y: number,
line: string,
color = "#f2ece0",
maxW = 250,
below = false,
) {
ctx.font = "11px ArkPixel, monospace";
const label = fitText(ctx, line, maxW - 16);
const width = Math.round(ctx.measureText(label).width + 16);
cx = Math.max(width / 2 + 6, Math.min(W - width / 2 - 6, cx));
if (below) {
px(ctx, cx - 4, y, 8, 8, color);
px(ctx, cx - width / 2, y + 6, width, 21, color);
px(ctx, cx - width / 2, y + 25, width, 2, "rgba(27,24,18,0.25)");
ctx.fillStyle = INK;
ctx.fillText(label, Math.round(cx - width / 2 + 8), Math.round(y + 21));
return;
}
y = Math.max(y, 26);
px(ctx, cx - width / 2, y - 21, width, 20, color);
px(ctx, cx - width / 2, y - 21, width, 2, "rgba(255,255,255,0.4)");
px(ctx, cx - 4, y - 2, 8, 5, color);
ctx.fillStyle = INK;
ctx.fillText(label, Math.round(cx - width / 2 + 8), Math.round(y - 7));
}
/* ---------------- 房间本体 ---------------- */
const STARS: [number, number][] = [
[18, 32],
[44, 42],
[70, 34],
[90, 48],
[128, 38],
[198, 44],
[210, 32],
];
function wall(ctx: Ctx, frame: number, clock: number) {
px(ctx, 0, 0, W, WALL_H, PAL.wall);
px(ctx, 0, 0, W, 22, PAL.wallHi);
px(ctx, 0, WALL_H - 16, W, 16, PAL.wallLo);
px(ctx, 0, WALL_H - 18, W, 3, PAL.trim);
// 挂旗
for (let i = 0; i < 18; i += 1) {
const x = 366 + i * 27;
px(ctx, x, 8, 2, 8, "#6b5f52");
const tint = [GOLD, "#c2685a", "#5aa469", "#4a90c2"][i % 4];
px(ctx, x + 2, 10, 18, 11, tint);
px(ctx, x + 6, 21, 10, 6, tint);
}
// 窗:夜里是亮着灯的楼,白天是同一片天际线(配色随主题换,形状不变)
for (const wx of [372, 618]) {
px(ctx, wx - 8, 22, 232, 116, PAL.trim);
px(ctx, wx, 28, 216, 100, PAL.sky);
px(ctx, wx, 28, 216, 30, PAL.skyBand);
for (const [sx, sy] of STARS) px(ctx, wx + sx, sy, 2, 2, PAL.star);
// 月亮(白天就是太阳):实心 + 两个环形山(挖一口的画法会在天上留下缺口)
px(ctx, wx + 152, 40, 20, 24, PAL.moon);
px(ctx, wx + 148, 44, 28, 16, PAL.moon);
px(ctx, wx + 156, 48, 5, 5, PAL.moonShade);
px(ctx, wx + 165, 56, 4, 4, PAL.moonShade);
for (let i = 0; i < 4; i += 1) {
const bh = 30 + ((i * 13) % 4) * 12;
px(ctx, wx + 14 + i * 50, 128 - bh, 34, bh, i % 2 ? PAL.buildingFar : PAL.buildingNear);
for (let j = 0; j < 5; j += 1) {
const ly = 138 - bh + j * 9;
if (ly > 122 || (i * 7 + j * 3 + Math.floor(frame / 14)) % 5 === 0) continue;
px(ctx, wx + 20 + i * 50, ly, 4, 4, PAL.windowLit);
}
}
px(ctx, wx + 106, 28, 4, 100, PAL.trim);
px(ctx, wx - 14, 134, 244, 8, PAL.sill);
px(ctx, wx - 14, 142, 244, 3, PAL.sillEdge);
}
// 挂钟:走真实时间
const sec = clock;
px(ctx, 878, 26, 54, 54, PAL.trim);
px(ctx, 882, 30, 46, 46, PAL.clockFace);
px(ctx, 884, 32, 42, 42, PAL.clockFaceHi);
const date = new Date(sec * 1000);
const minute = date.getMinutes() / 60;
const hour = ((date.getHours() % 12) + minute) / 12;
const hand = (ratio: number, len: number, color: string, thick: number) => {
for (let i = 1; i <= len; i += 1) {
const a = ratio * Math.PI * 2;
px(
ctx,
905 + Math.sin(a) * i - thick / 2,
53 - Math.cos(a) * i - thick / 2,
thick,
thick,
color,
);
}
};
hand(hour, 11, PAL.clockHour, 3);
hand(minute, 16, PAL.clockMinute, 2);
px(ctx, 903, 51, 4, 4, INK);
}
function floor(ctx: Ctx, lanes: number[]) {
px(ctx, 0, WALL_H, W, H - WALL_H, PAL.floorBase);
const PW = 132;
const PH = 24;
for (let row = 0, y = WALL_H; y < H; row += 1, y += PH) {
const shift = (row % 2) * (PW / 2);
for (let x = -PW; x < W; x += PW) {
const tint = (row * 5 + Math.floor((x + shift) / PW) * 3) % 3;
px(
ctx,
x + shift,
y,
PW - 2,
PH - 2,
tint === 0 ? PAL.floorTintA : tint === 1 ? PAL.floorTintB : PAL.floorTintC,
);
px(ctx, x + shift + 14, y + 10, PW - 44, 1, PAL.floorGrain);
px(ctx, x + shift + PW - 2, y, 2, PH, PAL.floorEdge);
}
}
// 踩出来的通道:每排工位前的走廊 + 右侧走道 + 两个停留点,
// 画的就是 walkerOf 真正会走的线,不会出现"路和人不一样"。
const wear = (x: number, y: number, w: number, h: number) => {
px(ctx, x, y, w, h, PAL.wear);
};
lanes.forEach((y) => wear(AREA.x - 10, y - 11, AREA.w + 28, 22));
wear(CORRIDOR_X - 15, lanes[0] - 11, 32, 584 - lanes[0]); // 去机柜的走道
wear(BAR_ENTRY_X - 12, lanes[0] - 11, 26, 712 - lanes[0] + 11); // 下茶水间的那条道
wear(SIDE_ENTRY_X - 12, lanes[0] - 11, 26, 712 - lanes[0] + 11); // 下休息区/讨论区的那条道
wear(62, 688, 268, 24); // 吧台前
wear(1180, 498, 96, 82); // 机柜前
}
/** 墙上那块看板的位置:右侧墙面(挂钟右边、机柜上方),整块贴着墙。 */
const BOARD = { x: 944, y: 14, w: 316, h: 132 };
interface BoardData {
/** 四种在岗状态各多少人,和工位名牌同一套配色。 */
crew: Record<Mood, number>;
queued: number;
running: number;
done: number;
live: boolean;
}
/**
* 墙上唯一的看板:左栏"在岗"(人现在在什么状态),右栏"任务"(队列有多少待办/在途/完成)。
*
* 以前这里是两块板——墙上的「在岗」和讨论区旁的「任务看板」。它们问的其实是同一个问题
* "办公室现在什么情况",抬头却要看两处,其中一块还立在过道上。合并成一块之后:位置上
* 挪到右侧墙面正中(不再压着讨论区的走动线),样式上换成"表头条 + 双栏"——标题行带
* 实时通道指示灯,下面两栏各自用色块对齐工位名牌的配色,产出明细仍旧只在右侧控制台。
*/
function statusBoard(ctx: Ctx, data: BoardData, frame: number) {
const { x, y, w, h } = BOARD;
const left = x + 14;
const mid = x + Math.round(w * 0.52);
const right = x + w - 14;
const total = data.crew.busy + data.crew.idle + data.crew.warn + data.crew.off;
const inflight = data.queued + data.running;
// 板身:木框 + 纸面,和以前一样是"挂在墙上的实物"
px(ctx, x, y, w, h, PAL.trim);
px(ctx, x + 4, y + 4, w - 8, h - 8, PAL.boardPaper);
px(ctx, x + 4, y + 4, w - 8, 2, PAL.boardPaperHi);
px(ctx, left, y + h - 12, w - 28, 5, PAL.boardRule);
// 表头条:办公室名字 + 实时通道指示灯(通道断了灯就灭)
px(ctx, x + 4, y + 4, w - 8, 24, PAL.boardHeader);
text(ctx, "AgentHub 办公室", left, y + 21, PAL.boardHeaderInk, "left", 13);
px(ctx, x + w - 64, y + 13, 8, 8, data.live ? (frame % 2 === 0 ? GREEN : "#1f6b3a") : "#7a7166");
text(
ctx,
data.live ? "实时" : "断开",
x + w - 50,
y + 21,
data.live ? GREEN : PAL.boardMuted,
"left",
10,
);
// 一行总览:多少工位、几个在忙、多少件在途
text(
ctx,
fitText(ctx, `${total} 个工位 · ${data.crew.busy} 在忙 · ${inflight} 件在途`, w - 30),
left,
y + 42,
PAL.boardMuted,
"left",
10,
);
// 两栏:左「在岗」右「任务」,中间一条竖线分开,行距一致,扫一眼就能横向对齐
px(ctx, mid - 9, y + 56, 2, 80, PAL.boardRule);
text(ctx, "在岗", left, y + 62, PAL.boardLabel, "left", 10);
text(ctx, "任务", mid + 6, y + 62, PAL.boardLabel, "left", 10);
const crewRows: [Mood, string][] = [
["busy", "在忙"],
["idle", "空闲"],
["warn", "异常"],
["off", "离线"],
];
crewRows.forEach(([mood, label], index) => {
const ry = y + 78 + index * 15;
px(ctx, left, ry - 8, 8, 8, MOOD_COLOR[mood]);
text(ctx, label, left + 13, ry, PAL.boardLabel, "left", 10);
text(ctx, String(data.crew[mood]), mid - 20, ry, PAL.boardInk, "right", 11);
});
const taskRows: [string, number, string][] = [
["待办", data.queued, PAL.boardMuted],
["在途", data.running, GOLD],
["完成", data.done, GREEN],
];
taskRows.forEach(([label, value, color], index) => {
const ry = y + 78 + index * 15;
px(ctx, mid + 6, ry - 8, 8, 8, color);
text(ctx, label, mid + 20, ry, PAL.boardLabel, "left", 10);
text(ctx, String(value), right, ry, PAL.boardInk, "right", 11);
});
}
function racks(ctx: Ctx, frame: number, alarm: boolean) {
const x = 1176;
text(ctx, alarm ? "机柜区 · 告警" : "机柜区", x + 48, 196, alarm ? RED : MUTED, "center");
px(ctx, x - 4, 468, 104, 12, PAL.rackInner);
px(ctx, x + 6, 478, 84, 6, `rgba(${PAL.shadowRGB},0.35)`);
px(ctx, x, 202, 96, 268, PAL.rackFrame);
px(ctx, x + 2, 204, 92, 4, PAL.rackEdge);
px(ctx, x + 2, 204, 3, 264, PAL.rackEdge);
px(ctx, x + 6, 210, 84, 254, PAL.rackInner);
for (let i = 0; i < 9; i += 1) {
const y = 216 + i * 27;
px(ctx, x + 11, y, 74, 20, PAL.rackPanel);
px(ctx, x + 11, y, 74, 2, PAL.rackPanelHi);
const blink = alarm ? frame % 2 === 0 : (frame + i) % 3 !== 0;
px(ctx, x + 16, y + 7, 5, 5, blink ? (alarm ? RED : GREEN) : PAL.rackScreen);
px(ctx, x + 25, y + 7, 5, 5, (frame + i) % 4 === 0 ? AMBER : PAL.rackScreen);
px(ctx, x + 37, y + 8, 38, 3, PAL.rackSlot);
px(ctx, x + 37, y + 13, 26, 3, PAL.rackSlot);
}
if (alarm)
px(ctx, x, 202, 96, 268, frame % 2 === 0 ? "rgba(239,68,68,0.12)" : "rgba(239,68,68,0.03)");
}
/** 讨论区:地毯 + 长桌 + 两把椅子,把右下角的空地用上。 */
function meetingCorner(ctx: Ctx, frame: number) {
px(ctx, 762, 616, 296, 96, "#383f36"); // 地毯
px(ctx, 768, 622, 284, 84, "#475044");
px(ctx, 768, 622, 284, 3, "rgba(255,255,255,0.06)");
for (const seat of [790, 1014]) {
// 两把转椅:靠背 / 坐垫 / 支柱 / 椅脚
px(ctx, seat < 900 ? seat - 6 : seat + 26, 618, 8, 34, "#4a5a6b");
px(ctx, seat, 638, 28, 12, "#5c6f84");
px(ctx, seat + 10, 650, 7, 18, "#3b4857");
px(ctx, seat + 2, 666, 24, 5, "#39434f");
}
px(ctx, 826, 636, 168, 46, "#8f6d48"); // 长桌
px(ctx, 826, 636, 168, 6, "#b78f65");
px(ctx, 826, 636, 168, 2, "rgba(255,255,255,0.12)");
px(ctx, 834, 682, 8, 14, "#6f5539");
px(ctx, 978, 682, 8, 14, "#6f5539");
px(ctx, 856, 622, 34, 16, "#2a251f"); // 桌上的笔记本
px(ctx, 859, 625, 28, 10, frame % 2 === 0 ? "#2f4f3c" : "#2b463a");
px(ctx, 940, 624, 12, 14, "#efe9dd");
px(ctx, 924, 626, 10, 12, GOLD);
text(ctx, "讨论区", 910, 612, "#c1bda9", "center");
}
function coffeeCorner(ctx: Ctx, frame: number) {
px(ctx, 36, 618, 300, 96, "#5d4630"); // 地毯
px(ctx, 42, 624, 288, 84, "#6d5238");
px(ctx, 42, 624, 288, 3, "rgba(255,255,255,0.05)");
// 后柜:咖啡机、杯子、小盆栽都在台面上
px(ctx, 56, 602, 262, 44, "#46341f");
px(ctx, 58, 604, 258, 40, "#7a5d3f");
px(ctx, 58, 598, 258, 7, "#a67f57");
for (let i = 0; i < 4; i += 1) px(ctx, 92 + i * 62, 612, 3, 30, "#5c452e");
px(ctx, 76, 556, 48, 42, "#767c85"); // 咖啡机
px(ctx, 76, 556, 48, 5, "#8d949d");
px(ctx, 84, 566, 32, 16, "#241f19");
px(ctx, 88, 570, 8, 3, GREEN);
px(ctx, 96, 584, 12, 14, "#8a5a3a");
px(ctx, frame % 2 === 0 ? 99 : 101, 590, 6, 8, "#f0ead9");
for (let i = 0; i < 3; i += 1) {
const rise = (frame + i * 2) % 6;
px(
ctx,
98 + i * 4 + (rise % 2 ? 2 : 0),
548 - rise * 4,
3,
4,
`rgba(236,232,220,${0.34 - rise * 0.05})`,
);
}
for (const [sx, sw] of [
[150, 14],
[176, 12],
[200, 16],
] as [number, number][]) {
px(ctx, sx, 586, sw, 12, "#efe9dd");
px(ctx, sx, 586, sw, 3, "#cfc7b8");
}
px(ctx, 234, 580, 18, 18, "#8a5a3a"); // 台面上的小盆栽
px(ctx, 236, 566, 8, 14, "#3c6030");
px(ctx, 244, 572, 8, 8, "#487a3a");
// 前吧台:人站在台前
px(ctx, 62, 642, 252, 12, "#b78f65");
px(ctx, 62, 654, 252, 44, "#8a6a49");
px(ctx, 62, 654, 252, 3, "#6f5539");
px(ctx, 66, 692, 244, 6, "#5c452e");
for (let i = 0; i < 5; i += 1) px(ctx, 76 + i * 48, 662, 3, 26, "#7a5d3f");
text(ctx, "茶水间", 310, 597, "#ddd2bc", "right");
}
function sofa(ctx: Ctx) {
px(ctx, 430, 604, 300, 100, "#54402d"); // 地毯(前面一段是人走的路)
px(ctx, 436, 610, 288, 88, "#634c34");
px(ctx, 452, 606, 204, 26, "#7d5f6d"); // 靠背
px(ctx, 444, 624, 20, 34, "#8c6a79"); // 扶手
px(ctx, 644, 624, 20, 34, "#8c6a79");
px(ctx, 462, 630, 184, 22, "#9c7787"); // 坐垫
px(ctx, 552, 630, 3, 22, "#8a6675");
px(ctx, 462, 652, 184, 5, "#775866");
px(ctx, 664, 626, 34, 26, "#7a5d3f"); // 边桌
px(ctx, 668, 618, 26, 8, "#8f6d48");
px(ctx, 676, 608, 10, 10, "#c9a227");
text(ctx, "休息区", 440, 702, "#c9bda8");
}
function plant(ctx: Ctx, x: number, y: number, k = 1) {
const s = (a: number, b: number, c: number, d: number, color: string) =>
px(ctx, x + a * k, y + b * k, c * k, d * k, color);
s(-1, 0, 22, 16, "#8a5a3a");
s(-1, 0, 22, 4, "#a06e47");
s(8, -18, 6, 20, "#3f6b34");
s(-4, -30, 14, 14, "#2f4c26");
s(14, -34, 14, 14, "#3c6030");
s(2, -44, 14, 14, "#37582d");
s(6, -36, 10, 10, "#487a3a");
}
/* ---------------- 工位 ---------------- */
/** 本页面打交道的就是真实 Agent/Task,布局类型按它们实例化。 */
type Desk = DeskLayout<Agent, Task>;
type Scene = SceneLayout<Agent, Task>;
function monitor(p: Pen, mood: Mood, frame: number, typed: boolean) {
const skin: Record<Mood, [string, string]> = {
busy: ["#0f231b", GREEN],
idle: ["#141b22", "#5d7080"],
warn: ["#251611", AMBER],
off: ["#0c0b0a", "#3a362f"],
};
const [bg, ink] = skin[mood];
p(26, 0, 17, 12, "#2a251f");
p(27, 1, 15, 9, bg);
if (mood === "off") {
p(40, 8, 1, 1, "#4b4740"); // 待机灯
} else if (mood === "busy") {
if (!typed)
for (let i = 0; i < 3; i += 1) p(29, 2 + i * 2, 3 + ((frame + i * 3) % 4) * 2, 1, ink);
if (frame % 2 === 0) p(39, 7, 1, 2, ink);
} else if (mood === "warn") {
p(29, 3, 10, 1, frame % 2 === 0 ? ink : "#7a5f18");
p(29, 6, 6, 1, ink);
} else {
p(29, 4, 6, 1, ink);
p(29, 7, 3, 1, ink);
}
p(27, 10, 15, 1, "#39322a"); // 底座
p(33, 11, 3, 2, "#2a251f");
if (mood === "busy") p(25, 0, 19, 13, "rgba(74,222,128,0.05)");
}
function deskOf(ctx: Ctx, desk: Desk, frame: number) {
const { u, ax, ay, mood } = desk;
const p = pen(ctx, ax, ay, u);
const dim = mood === "off";
shadow(ctx, ax + (ART_W * u) / 2, ay + 25 * u, ART_W * u * 0.86, 0.26);
// 椅子
p(19, 0, 8, 3, dim ? "#39414d" : "#46505f");
p(17, 3, 12, 8, dim ? "#3f4650" : "#4a5a6b");
p(17, 3, 12, 2, dim ? "#4a5260" : "#5c6f84");
// 只有"在忙"的人坐在工位上
if (mood === "busy") {
sprite(
ctx,
ax + 23 * u,
ay + 16 * u,
u,
outfitOf(desk.agent, false),
LEGS_STAND,
0,
marksOf(desk.agent),
);
}
// 桌子
p(0, 13, 44, 3, dim ? "#8a7256" : "#b78f65");
p(0, 16, 44, 2, dim ? "#6f573c" : "#8f7048");
p(3, 18, 4, 8, dim ? "#5a4630" : "#7c5f40");
p(37, 18, 4, 8, dim ? "#5a4630" : "#7c5f40");
p(10, 18, 26, 5, dim ? "#5f4b34" : "#87694a");
p(0, 13, 44, 1, "rgba(255,255,255,0.10)");
// 屏幕上直接写在跑什么,字按屏幕宽度折行截断
const lines =
mood === "busy" && desk.job && u >= 3
? clipLines(
ctx,
desk.job.title || desk.job.prompt || "任务",
13 * u - 3,
3,
clamp(Math.round(u * 1.6), 8, 15),
)
: [];
monitor(p, mood, frame, lines.length > 0);
const size = clamp(Math.round(u * 1.6), 8, 15);
lines.forEach((line, index) =>
text(ctx, line, ax + 28 * u, ay + (3 + index * 3) * u, "#9df0bd", "left", size),
);
p(19, 13, 10, 2, "#39322a"); // 键盘
p(20, 13, 8, 1, "#4d453a");
if (mood === "busy") {
const tap = frame % 2 === 0;
p(tap ? 19 : 20, 12, 2, 1, outfitOf(desk.agent, false).skin);
p(tap ? 27 : 26, 12, 2, 1, outfitOf(desk.agent, false).skin);
}
// 桌角放一沓便签纸(只是桌面道具,不表示产出数量——产出明细在右侧面板)
p(6, 13, 8, 1, "#efe9dd");
p(6, 12, 7, 1, "#ded6c6");
p(15, 12, 3, 2, dim ? "#3a362f" : GOLD); // 杯子
p(18, 12, 1, 1, dim ? "#3a362f" : GOLD);
// 台灯
p(1, 4, 1, 9, "#3d372d");
p(0, 2, 5, 2, "#c2685a");
if (!dim) px(ctx, ax, ay + 4 * u, 8 * u, 10 * u, "rgba(255,214,120,0.07)");
if (dim)
text(
ctx,
"z Z",
ax + 29 * u,
ay + 8 * u,
"#6f6a60",
"left",
clamp(Math.round(u * 1.8), 8, 12),
);
}
function namePlate(ctx: Ctx, desk: Desk) {
const cx = desk.cellX + Math.round(desk.cellW / 2);
const label =
(desk.agent.emoji ? desk.agent.emoji + " " : "") + (desk.agent.display_name || desk.agent.name);
ctx.font = "11px ArkPixel, monospace";
const w = Math.min(desk.cellW - 8, Math.max(96, ctx.measureText(label).width + 54));
const x = cx - Math.round(w / 2);
px(ctx, x, desk.cellY + 1, w, LABEL_H - 3, PAL.plateBg);
px(ctx, x, desk.cellY + 1, w, 2, MOOD_COLOR[desk.mood]);
const clipW = w - 52;
text(ctx, fitText(ctx, label, clipW), x + 10, desk.cellY + LABEL_H - 9, PAL.plateInk);
text(
ctx,
STATUS_WORD[desk.mood],
x + w - 10,
desk.cellY + LABEL_H - 9,
MOOD_COLOR[desk.mood],
"right",
);
}
/* ---------------- 走动:只走走廊,拐直角,不穿桌子 ---------------- */
type Pt = { x: number; y: number };
type Zone = "bar" | "lounge" | "meeting" | "rack";
/** 一个能停人的位子。sit = 坐下(用坐垫色盖住腿);front = 先走到这条横线再拐到位子上。 */
type Spot = { x: number; y: number; face?: -1 | 1; sit?: string; front?: number };
const BAR_SPOTS: Spot[] = [
{ x: 152, y: 700 },
{ x: 212, y: 706 },
{ x: 270, y: 700 },
{ x: 96, y: 706 },
{ x: 300, y: 688 },
{ x: 64, y: 688 },
];
const LOUNGE_SPOTS: Spot[] = [
{ x: 507, y: 656, front: 684, sit: "#9c7787" }, // 沙发两个座
{ x: 599, y: 656, front: 684, sit: "#9c7787" },
];
const MEET_SPOTS: Spot[] = [
{ x: 786, y: 700, face: 1 }, // 长桌两头,面对面
{ x: 1038, y: 700, face: -1 },
{ x: 852, y: 708, face: 1 }, // 桌前,侧头看看板
];
const RACK_SPOTS: Spot[] = [
{ x: 1200, y: 520 },
{ x: 1244, y: 534 },
{ x: 1200, y: 552 },
{ x: 1244, y: 566 },
];
/** 每个去处:走哪条竖道下来、几个位子、待多久、回工位歇多久。 */
const ZONES: Record<Zone, { entryX: number; spots: Spot[]; dwell: number; rest: number }> = {
bar: { entryX: BAR_ENTRY_X, spots: BAR_SPOTS, dwell: 8, rest: 6 },
lounge: { entryX: SIDE_ENTRY_X, spots: LOUNGE_SPOTS, dwell: 34, rest: 9 },
meeting: { entryX: SIDE_ENTRY_X, spots: MEET_SPOTS, dwell: 28, rest: 9 },
rack: { entryX: CORRIDOR_X, spots: RACK_SPOTS, dwell: 40, rest: 4 },
};
/** 空闲的人在这三个地方轮着转,谁都不会一直空着。 */
const TOUR: Zone[] = ["bar", "lounge", "meeting"];
const SPEED = 46; // 像素 / 秒
const tourOf = (desk: Desk): Zone[] => (desk.mood === "warn" ? ["rack"] : TOUR);
/** 只走走廊 + 竖道 + 位子前的横线,拐直角,不穿桌子。 */
function routeOf(desk: Desk, zone: Zone, spot: Spot): Pt[] {
const entryX = ZONES[zone].entryX;
const front = spot.front ?? spot.y;
const route: Pt[] = [
{ x: desk.homeX, y: desk.aisleY },
{ x: entryX, y: desk.aisleY },
];
if (front !== spot.y) route.push({ x: entryX, y: front }, { x: spot.x, y: front });
route.push({ x: spot.x, y: spot.y });
return route;
}
function polyLen(route: Pt[]): number {
let len = 0;
for (let i = 1; i < route.length; i += 1)
len += Math.abs(route[i].x - route[i - 1].x) + Math.abs(route[i].y - route[i - 1].y);
return len;
}
function pointAt(route: Pt[], arc: number) {
let left = arc;
let face: -1 | 0 | 1 = 1;
for (let i = 1; i < route.length; i += 1) {
const [a, b] = [route[i - 1], route[i]];
const len = Math.abs(b.x - a.x) + Math.abs(b.y - a.y);
if (b.x > a.x) face = 1;
if (b.x < a.x) face = -1;
if (len === 0) continue;
if (left <= len) {
const k = len === 0 ? 0 : left / len;
return { x: a.x + (b.x - a.x) * k, y: a.y + (b.y - a.y) * k, face };
}
left -= len;
}
const last = route[route.length - 1];
return { x: last.x, y: last.y, face };
}
interface Walker {
x: number;
y: number;
face: -1 | 0 | 1;
walking: boolean;
withCup: boolean;
sit?: string; // 坐下时的坐垫色
desk: Desk;
}
interface Trip {
zone: Zone;
seat: number;
route: Pt[];
len: number;
travel: number;
}
type Phase = "out" | "dwell" | "back" | "rest";
interface WalkerState {
trip: Trip;
phase: Phase;
t: number;
mood: Mood;
}
type States = Map<string, WalkerState>;
const seatTaken = (states: States, zone: Zone, seat: number, id: string) => {
for (const [agentId, state] of states) {
if (
agentId !== id &&
state.trip.zone === zone &&
state.trip.seat === seat &&
state.phase !== "rest"
)
return true;
}
return false;
};
/** 挑下一个去处:按 TOUR 顺序找第一个还有空位的地方;全满了就先在工位待着。 */
function tripTo(desk: Desk, from: Zone | null, states: States): Trip | null {
const zones = tourOf(desk);
const seed = hashOf(desk.agent.id);
const at = from === null ? seed % zones.length : Math.max(0, zones.indexOf(from));
for (let step = from === null ? 0 : 1; step < zones.length; step += 1) {
const zone = zones[(at + step) % zones.length];
const spots = ZONES[zone].spots;
for (let i = 0; i < spots.length; i += 1) {
const seat = (seed + i) % spots.length;
if (seatTaken(states, zone, seat, desk.agent.id)) continue;
const route = routeOf(desk, zone, spots[seat]);
const len = polyLen(route);
return { zone, seat, route, len, travel: len / SPEED };
}
}
return null;
}
/** 走 → 待着 → 走回来 → 工位歇会儿 → 换下一个去处。状态存着,人和路线都不会瞬移。 */
function stepWalker(state: WalkerState, desk: Desk, dt: number, states: States) {
const limitOf = () =>
state.phase === "dwell"
? ZONES[state.trip.zone].dwell
: state.phase === "rest"
? ZONES[state.trip.zone].rest
: state.trip.travel;
if (desk.mood !== state.mood) {
state.mood = desk.mood;
if (state.phase === "dwell") state.t = ZONES[state.trip.zone].dwell; // 情况变了,别歇了
}
state.t += dt;
for (;;) {
const limit = limitOf();
if (state.t < limit) return;
if (state.phase === "rest") {
const next = tripTo(desk, state.trip.zone, states);
if (!next) {
state.t = 0; // 位子都满着,再等等
return;
}
state.trip = next;
state.phase = "out";
state.t -= limit;
continue;
}
state.phase = state.phase === "out" ? "dwell" : state.phase === "dwell" ? "back" : "rest";
state.t -= limit;
}
}
function walkerAt(state: WalkerState, desk: Desk): Walker {
const spot = ZONES[state.trip.zone].spots[state.trip.seat];
if (state.phase === "rest")
return { x: desk.homeX, y: desk.aisleY, face: 0, walking: false, withCup: false, desk };
if (state.phase === "dwell")
return {
x: spot.x,
y: spot.y,
face: spot.face ?? 0,
walking: false,
withCup: state.trip.zone === "bar",
sit: spot.sit,
desk,
};
const arc = state.phase === "out" ? SPEED * state.t : state.trip.len - SPEED * state.t;
return { ...pointAt(state.trip.route, arc), walking: true, withCup: false, desk };
}
/** 每帧推进所有不在工位上的人;状态由调用方(组件的 ref)持有。 */
function updateWalkers(scene: Scene, states: States, dt: number): Walker[] {
const walkers: Walker[] = [];
const alive = new Set<string>();
scene.desks.forEach((desk) => {
if (desk.mood === "busy" || desk.mood === "off") return;
alive.add(desk.agent.id);
let state = states.get(desk.agent.id);
if (!state) {
const trip = tripTo(desk, null, states);
if (!trip) return;
state = { trip, phase: "out", t: 0, mood: desk.mood };
states.set(desk.agent.id, state);
}
stepWalker(state, desk, dt, states);
walkers.push(walkerAt(state, desk));
});
states.forEach((_, id) => {
if (!alive.has(id)) states.delete(id);
});
return walkers;
}
function drawWalker(ctx: Ctx, walker: Walker, clock: number) {
const { desk } = walker;
const dim = desk.mood === "off";
const legs = walker.walking
? Math.floor(clock * 6) % 2 === 0
? LEGS_WIDE
: LEGS_CLOSE
: LEGS_STAND;
// 坐进沙发的人按沙发的比例画,坐下去后拿坐垫把腿盖住
const u = walker.sit ? Math.min(desk.u, 8) : desk.u;
if (!walker.sit) shadow(ctx, walker.x, walker.y - u, 9 * u * 0.8, 0.3);
sprite(ctx, walker.x, walker.y, u, outfitOf(desk.agent, dim), legs, walker.face, marksOf(desk.agent), dim);
if (walker.sit) {
const half = Math.min(5 * u, 46);
const top = Math.round(walker.y - 4.2 * u);
px(ctx, walker.x - half, top, half * 2, walker.y - top, walker.sit);
px(ctx, walker.x - half, walker.y, half * 2, 5, "#775866");
}
if (walker.withCup)
px(ctx, walker.x + (walker.face === -1 ? -6 : 3) * u, walker.y - 6 * u, 2 * u, 2 * u, GOLD);
}
/* ---------------- 合成整幅画面 ---------------- */
function vignette(ctx: Ctx) {
const grad = ctx.createRadialGradient(W / 2, H / 2 - 40, 240, W / 2, H / 2, 860);
grad.addColorStop(0, `rgba(${PAL.vignetteRGB},0)`);
grad.addColorStop(1, `rgba(${PAL.vignetteRGB},${PAL.vignetteAlpha})`);
ctx.fillStyle = grad;
ctx.fillRect(0, 0, W, H);
}
/** 选中/悬停的工位:只描四角,不挡画面。 */
function markRect(ctx: Ctx, x: number, y: number, w: number, h: number, color: string) {
const len = 16;
const t = 3;
(
[
[x, y, 1, 1],
[x + w, y, -1, 1],
[x, y + h, 1, -1],
[x + w, y + h, -1, -1],
] as [number, number, number, number][]
).forEach(([cx, cy, dx, dy]) => {
px(ctx, dx > 0 ? cx : cx - len, dy > 0 ? cy : cy - t, len, t, color);
px(ctx, dx > 0 ? cx : cx - t, dy > 0 ? cy : cy - len, t, len, color);
});
}
interface Snapshot {
agents: Agent[];
tasks: Task[];
live: boolean;
selected: string;
}
function drawScene(
ctx: Ctx,
snapshot: Snapshot,
hover: Desk | null,
clock: number,
states: States,
dt: number,
) {
const frame = Math.floor(clock * 5);
const scene = layoutScene(snapshot.agents, snapshot.tasks);
const done = snapshot.tasks.filter((job) => job.status === "completed").length;
const running = snapshot.tasks.filter((job) => job.status === "running").length;
const queued = snapshot.tasks.filter((job) => job.status === "queued").length;
const alarm = scene.desks.some((desk) => desk.mood === "warn");
const crew: Record<Mood, number> = { busy: 0, idle: 0, warn: 0, off: 0 };
scene.desks.forEach((desk) => {
crew[desk.mood] += 1;
});
wall(ctx, frame, clock);
floor(ctx, scene.lanes);
vignette(ctx);
statusBoard(ctx, { crew, queued, running, done, live: snapshot.live }, frame);
racks(ctx, frame, alarm);
coffeeCorner(ctx, frame);
sofa(ctx);
meetingCorner(ctx, frame);
plant(ctx, 6, 258, 1.25);
plant(ctx, 386, 708);
plant(ctx, 1188, 710, 1.15);
// 人和桌子按"脚底所在的横线"排序,走近的挡住远的,不会出现人陷在桌子后面。
const actors: { base: number; paint: () => void }[] = [];
scene.desks.forEach((desk) =>
actors.push({ base: desk.ay + 26 * desk.u, paint: () => deskOf(ctx, desk, frame) }),
);
const walkers = updateWalkers(scene, states, dt);
walkers.forEach((walker) =>
actors.push({ base: walker.y, paint: () => drawWalker(ctx, walker, clock) }),
);
actors.sort((a, b) => a.base - b.base).forEach((actor) => actor.paint());
scene.desks.forEach((desk) => namePlate(ctx, desk));
scene.desks.forEach((desk) => {
if (desk.mood !== "warn") return;
const walker = walkers.find((item) => item.desk.agent.id === desk.agent.id);
if (!walker || !desk.agent.last_error) return;
// 人回到工位(rest)时不飘气泡,屏幕上已经是黄色的了;
// 站在机柜前气泡放脚下(别盖住机柜),走路时放头顶(别盖住沙发上的人)。
const st = states.get(desk.agent.id);
if (!st || st.phase === "rest") return;
const atRack = st.trip.zone === "rack" && st.phase === "dwell";
bubble(
ctx,
walker.x,
atRack ? walker.y + 6 : walker.y - 11 * desk.u,
desk.agent.last_error,
"#f5cfa0",
250,
atRack,
);
});
const picked = (key: string) =>
scene.desks.find((desk) => desk.agent.id === key || desk.agent.name === key) ?? null;
[picked(snapshot.selected), hover].forEach((desk, index) => {
if (!desk) return;
const boxW = Math.min(desk.cellW - 5, ART_W * desk.u + 28);
markRect(
ctx,
desk.homeX - Math.round(boxW / 2),
desk.cellY + 1,
boxW,
desk.ay + 26 * desk.u + 4 - desk.cellY,
index === 0 ? GOLD : "rgba(242,236,224,0.85)",
);
});
}
export interface OfficeSceneProps {
agents: Agent[];
tasks: Task[];
live: boolean;
selected: string;
onSelect: (agent: Agent) => void;
}
export function OfficeScene({ agents, tasks, live, selected, onSelect }: OfficeSceneProps) {
const canvas = useRef<HTMLCanvasElement | null>(null);
const snapshot = useRef<Snapshot>({ agents, tasks, live, selected });
// 房间配色跟着控制台主题走。主题写进 ref、绘制循环每帧读它,等于"下一帧换装"——
// 不用重挂画布,也不会把人偶的走动状态重置(模块级的 PAL 只在绘制里赋值)。
const theme = useTheme();
const themeRef = useRef(theme);
// 后备缓冲比例:canvas 的像素尺寸 = 显示尺寸(px) × devicePixelRatio。
// 场景永远按逻辑 1280×720 画,比例交给 ctx.setTransform——这样窗口拉宽、
// 换到 2x/3x 屏都是 1:1 像素,不会像固定 1280 位图那样被拉伸成糊的。
const renderScale = useRef(1);
// 悬停只写 ref,不触发 React 重渲染,绘制时按 id 找回工位。
const hoverId = useRef("");
// 走动状态(去了哪儿、走到哪一步)也得跨帧留着,否则每帧都在重新算会瞬移。
const states = useRef<States>(new Map());
const lastClock = useRef(0);
useEffect(() => {
snapshot.current = { agents, tasks, live, selected };
}, [agents, tasks, live, selected]);
useEffect(() => {
themeRef.current = theme;
}, [theme]);
useEffect(() => {
const el = canvas.current;
if (!el) return;
const ctx = el.getContext("2d");
if (!ctx) return;
// 显示多大就渲染多大:CSS 宽度 × DPR,夹在 0.75~2.5 之间防止超宽屏上画出巨型位图。
const fit = () => {
const box = el.getBoundingClientRect();
if (!box.width) return;
const dpr = window.devicePixelRatio || 1;
const next = clamp((box.width * dpr) / W, 0.75, 2.5);
const pixelW = Math.round(W * next);
const pixelH = Math.round(H * next);
if (el.width !== pixelW || el.height !== pixelH) {
el.width = pixelW;
el.height = pixelH;
}
renderScale.current = next;
};
fit();
const observer = new ResizeObserver(fit);
observer.observe(el);
window.addEventListener("resize", fit);
let raf = 0;
let lastDpr = window.devicePixelRatio;
const draw = () => {
PAL = officePalette(themeRef.current);
const clock = performance.now() / 1000;
const dt = clamp(clock - lastClock.current, 0, 0.25); // 切走再回来别一口气走完全程
lastClock.current = clock;
if (window.devicePixelRatio !== lastDpr) {
// 拖到另一块屏幕(1x ↔ 2x)时重新配一次后备缓冲
lastDpr = window.devicePixelRatio;
fit();
}
ctx.setTransform(renderScale.current, 0, 0, renderScale.current, 0, 0);
ctx.imageSmoothingEnabled = false;
const scene = layoutScene(snapshot.current.agents, snapshot.current.tasks);
const id = hoverId.current;
const hover =
scene.desks.find((desk) => desk.agent.id === id || desk.agent.name === id) ?? null;
drawScene(ctx, snapshot.current, hover, clock, states.current, dt);
raf = requestAnimationFrame(draw);
};
raf = requestAnimationFrame(draw);
return () => {
cancelAnimationFrame(raf);
observer.disconnect();
window.removeEventListener("resize", fit);
};
}, []);
const hit = (event: React.MouseEvent<HTMLCanvasElement>): Desk | null => {
const el = canvas.current;
if (!el) return null;
const box = el.getBoundingClientRect();
const x = ((event.clientX - box.left) / box.width) * W;
const y = ((event.clientY - box.top) / box.height) * H;
const { desks } = layoutScene(snapshot.current.agents, snapshot.current.tasks);
return (
desks.find(
(desk) =>
x > desk.cellX + 2 &&
x < desk.cellX + desk.cellW - 2 &&
y > desk.cellY &&
y < desk.cellY + desk.cellH - 4,
) ?? null
);
};
return (
<canvas
ref={canvas}
// 像素尺寸由 fit() 按"显示宽度 × devicePixelRatio"设定,这里只固定显示比例
style={{ aspectRatio: "16 / 9" }}
className="w-full rounded-[8px] border-[3px] border-[color:var(--pixel-border)]"
onMouseMove={(event) => {
const desk = hit(event);
hoverId.current = desk ? desk.agent.id : "";
event.currentTarget.style.cursor = desk ? "pointer" : "default";
}}
onMouseLeave={() => {
hoverId.current = "";
}}
onClick={(event) => {
const desk = hit(event);
if (desk) onSelect(desk.agent);
}}
/>
);
}