@songsid/agend 2.4.0-beta.16 → 2.4.0-beta.18
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/dist/auth-api.js +2 -0
- package/dist/auth-api.js.map +1 -1
- package/dist/backend/claude-code.d.ts +10 -1
- package/dist/backend/claude-code.js +7 -2
- package/dist/backend/claude-code.js.map +1 -1
- package/dist/backend/claude-transcript-errors.d.ts +4 -0
- package/dist/backend/claude-transcript-errors.js +5 -1
- package/dist/backend/claude-transcript-errors.js.map +1 -1
- package/dist/backend/types.d.ts +6 -0
- package/dist/backend/types.js.map +1 -1
- package/dist/build-provenance.json +1 -1
- package/dist/claude-credential-launch.d.ts +1 -0
- package/dist/claude-credential-launch.js +13 -2
- package/dist/claude-credential-launch.js.map +1 -1
- package/dist/claude-credential-vault.d.ts +7 -1
- package/dist/claude-credential-vault.js +26 -1
- package/dist/claude-credential-vault.js.map +1 -1
- package/dist/claude-request-observation.d.ts +7 -0
- package/dist/claude-request-observation.js +26 -0
- package/dist/claude-request-observation.js.map +1 -0
- package/dist/cli-audited.js +11 -8
- package/dist/cli-audited.js.map +1 -1
- package/dist/daemon.d.ts +8 -0
- package/dist/daemon.js +68 -13
- package/dist/daemon.js.map +1 -1
- package/dist/fleet-context.d.ts +1 -0
- package/dist/fleet-manager.d.ts +28 -0
- package/dist/fleet-manager.js +222 -10
- package/dist/fleet-manager.js.map +1 -1
- package/dist/fleet-windows-runtime.d.ts +1 -1
- package/dist/fleet-windows-runtime.js +1 -1
- package/dist/fleet-windows-runtime.js.map +1 -1
- package/dist/fleet-yaml-stringify.d.ts +3 -0
- package/dist/fleet-yaml-stringify.js +79 -0
- package/dist/fleet-yaml-stringify.js.map +1 -0
- package/dist/general-knowledge/skills/web-dashboard/SKILL.md +17 -3
- package/dist/host-monitoring-alert-policy.d.ts +71 -0
- package/dist/host-monitoring-alert-policy.js +150 -0
- package/dist/host-monitoring-alert-policy.js.map +1 -0
- package/dist/host-monitoring-alert-resources.d.ts +11 -0
- package/dist/host-monitoring-alert-resources.js +16 -0
- package/dist/host-monitoring-alert-resources.js.map +1 -0
- package/dist/host-monitoring-alert-settings.d.ts +14 -0
- package/dist/host-monitoring-alert-settings.js +63 -0
- package/dist/host-monitoring-alert-settings.js.map +1 -0
- package/dist/host-monitoring-alert-store.d.ts +49 -0
- package/dist/host-monitoring-alert-store.js +228 -0
- package/dist/host-monitoring-alert-store.js.map +1 -0
- package/dist/host-monitoring-alert-text.d.ts +7 -0
- package/dist/host-monitoring-alert-text.js +10 -0
- package/dist/host-monitoring-alert-text.js.map +1 -0
- package/dist/host-monitoring-alerts.d.ts +76 -0
- package/dist/host-monitoring-alerts.js +261 -0
- package/dist/host-monitoring-alerts.js.map +1 -0
- package/dist/host-monitoring-config.d.ts +2 -1
- package/dist/host-monitoring-config.js +8 -3
- package/dist/host-monitoring-config.js.map +1 -1
- package/dist/host-monitoring-footprint-policy.d.ts +45 -0
- package/dist/host-monitoring-footprint-policy.js +150 -0
- package/dist/host-monitoring-footprint-policy.js.map +1 -0
- package/dist/host-monitoring-footprint.d.ts +42 -0
- package/dist/host-monitoring-footprint.js +169 -0
- package/dist/host-monitoring-footprint.js.map +1 -0
- package/dist/host-monitoring-history-files.d.ts +2 -0
- package/dist/host-monitoring-history-files.js +16 -0
- package/dist/host-monitoring-history-files.js.map +1 -0
- package/dist/host-monitoring-history-policy.d.ts +57 -0
- package/dist/host-monitoring-history-policy.js +107 -0
- package/dist/host-monitoring-history-policy.js.map +1 -0
- package/dist/host-monitoring-history-store.d.ts +52 -0
- package/dist/host-monitoring-history-store.js +178 -0
- package/dist/host-monitoring-history-store.js.map +1 -0
- package/dist/host-monitoring-history-worker.d.ts +1 -0
- package/dist/host-monitoring-history-worker.js +66 -0
- package/dist/host-monitoring-history-worker.js.map +1 -0
- package/dist/host-monitoring-history.d.ts +80 -0
- package/dist/host-monitoring-history.js +301 -0
- package/dist/host-monitoring-history.js.map +1 -0
- package/dist/host-monitoring-platform.d.ts +73 -0
- package/dist/host-monitoring-platform.js +273 -0
- package/dist/host-monitoring-platform.js.map +1 -0
- package/dist/host-monitoring-process-identity.d.ts +8 -0
- package/dist/host-monitoring-process-identity.js +81 -0
- package/dist/host-monitoring-process-identity.js.map +1 -0
- package/dist/host-monitoring-runtime.d.ts +42 -0
- package/dist/host-monitoring-runtime.js +95 -0
- package/dist/host-monitoring-runtime.js.map +1 -0
- package/dist/host-monitoring-settings-store.d.ts +5 -0
- package/dist/host-monitoring-settings-store.js +49 -0
- package/dist/host-monitoring-settings-store.js.map +1 -0
- package/dist/host-monitoring.d.ts +108 -0
- package/dist/host-monitoring.js +157 -0
- package/dist/host-monitoring.js.map +1 -0
- package/dist/instance-lifecycle.js +2 -2
- package/dist/instance-lifecycle.js.map +1 -1
- package/dist/needs-you-hub.d.ts +1 -0
- package/dist/needs-you-hub.js +1 -0
- package/dist/needs-you-hub.js.map +1 -1
- package/dist/needs-you.d.ts +3 -2
- package/dist/needs-you.js +1 -0
- package/dist/needs-you.js.map +1 -1
- package/dist/public-web-gateway.js +11 -1
- package/dist/public-web-gateway.js.map +1 -1
- package/dist/runtime-cli-install.js +17 -16
- package/dist/runtime-cli-install.js.map +1 -1
- package/dist/settings-api.d.ts +5 -0
- package/dist/settings-api.js +70 -7
- package/dist/settings-api.js.map +1 -1
- package/dist/settings-baseline.d.ts +1 -0
- package/dist/settings-baseline.js +6 -4
- package/dist/settings-baseline.js.map +1 -1
- package/dist/settings-change.js +8 -0
- package/dist/settings-change.js.map +1 -1
- package/dist/settings-effect.d.ts +4 -0
- package/dist/settings-effect.js +25 -4
- package/dist/settings-effect.js.map +1 -1
- package/dist/topic-commands.js +4 -0
- package/dist/topic-commands.js.map +1 -1
- package/dist/transcript-monitor.d.ts +1 -0
- package/dist/transcript-monitor.js +18 -0
- package/dist/transcript-monitor.js.map +1 -1
- package/dist/ui/accounts-view.js +7 -5
- package/dist/ui/chat-store.js +21 -4
- package/dist/ui/claude-credentials.js +12 -1
- package/dist/ui/fleet-office-pack.js +2 -2
- package/dist/ui/fleet-office-play.js +142 -3
- package/dist/ui/fleet-office-skin.js +67 -2
- package/dist/ui/fleet-office-store.js +41 -0
- package/dist/ui/fleet-office-zones.js +15 -8
- package/dist/ui/fleet-office.js +126 -21
- package/dist/ui/host-alerts.js +23 -0
- package/dist/ui/host-footprint.js +17 -0
- package/dist/ui/host-health-model.js +42 -0
- package/dist/ui/host-health.js +79 -0
- package/dist/ui/host-time.js +5 -0
- package/dist/ui/panel-chat.js +101 -43
- package/dist/ui/panel-fleet.js +24 -11
- package/dist/ui/panel-hub.js +5 -1
- package/dist/ui/panel-needs.js +27 -16
- package/dist/ui/panel-settings.js +4 -3
- package/dist/ui/search-dialog.js +8 -1
- package/dist/ui/settings-capabilities.js +2 -0
- package/dist/ui/settings-host-alerts.js +22 -0
- package/dist/ui/settings-host-monitoring.js +37 -18
- package/dist/ui/settings-registry.js +4 -1
- package/dist/ui/shared/accounts.css +8 -4
- package/dist/ui/shared/agent-sheet.js +5 -2
- package/dist/ui/shared/app-i18n.js +2 -2
- package/dist/ui/shared/app-route.js +1 -1
- package/dist/ui/shared/app.css +87 -9
- package/dist/ui/shared/app.js +1 -0
- package/dist/ui/shared/chat-render.js +24 -9
- package/dist/ui/shared/chat-strings.js +4 -4
- package/dist/ui/shared/chat-thread.js +45 -11
- package/dist/ui/shared/instance-nav.js +47 -5
- package/dist/ui/shared/jump-idle.js +36 -0
- package/dist/ui/shared/theme.js +6 -2
- package/dist/ui/shared/ui-menu.js +17 -11
- package/dist/web-api.d.ts +3 -0
- package/dist/web-api.js +249 -4
- package/dist/web-api.js.map +1 -1
- package/dist/web-chat-history.d.ts +47 -2
- package/dist/web-chat-history.js +149 -11
- package/dist/web-chat-history.js.map +1 -1
- package/dist/web-guest-access.js +4 -4
- package/dist/web-guest-access.js.map +1 -1
- package/dist/web-shell-routes.d.ts +1 -1
- package/dist/web-shell-routes.js +1 -1
- package/dist/web-shell-routes.js.map +1 -1
- package/dist/web-upload.d.ts +1 -1
- package/dist/web-upload.js.map +1 -1
- package/package.json +1 -1
|
@@ -50,9 +50,16 @@ export function overflowSpots(area, need = 0) {
|
|
|
50
50
|
* `lend` (one no owner of it took). A reserved seat not lent, none of whose owners wants the area, is unavailable:
|
|
51
51
|
* the area's overflow spots and `over` count without it. Seats without `for` work as before.
|
|
52
52
|
*/
|
|
53
|
-
export function assignSeats(pack, wants, prev = new Map()) {
|
|
53
|
+
export function assignSeats(pack, wants, prev = new Map(), seatPrefs = null) {
|
|
54
54
|
const seats = new Map(), crowd = new Map(), taken = new Map(), spill = new Map(), demand = new Map(), wanting = new Map();
|
|
55
55
|
const areaOf = (a) => own(pack.areas, a);
|
|
56
|
+
const prefOf = (name, area) => {
|
|
57
|
+
const p = prev.get(name);
|
|
58
|
+
if (p && p.area === area) return p;
|
|
59
|
+
const byArea = seatPrefs && own(seatPrefs, name);
|
|
60
|
+
const slot = byArea && own(byArea, area);
|
|
61
|
+
return Number.isInteger(slot) && slot >= 0 ? { area, slot } : null;
|
|
62
|
+
};
|
|
56
63
|
for (const w of wants) {
|
|
57
64
|
demand.set(w.area, (demand.get(w.area) || 0) + 1);
|
|
58
65
|
if (!wanting.has(w.area)) wanting.set(w.area, new Set());
|
|
@@ -70,9 +77,9 @@ export function assignSeats(pack, wants, prev = new Map()) {
|
|
|
70
77
|
const usedIn = (area) => { if (!taken.has(area)) taken.set(area, new Set()); return taken.get(area); };
|
|
71
78
|
const give = (name, area, slot) => { const p = pos(area, slot); usedIn(area).add(slot); seats.set(name, { area, slot, x: p.x, y: p.y }); };
|
|
72
79
|
const free = (w) => !seats.has(w.name) && !!areaOf(w.area);
|
|
73
|
-
// Owners first: their own seat from last time, then their first free one.
|
|
80
|
+
// Owners first: their own seat from last time (or saved seat pref), then their first free one.
|
|
74
81
|
for (const w of wants) {
|
|
75
|
-
const p =
|
|
82
|
+
const p = prefOf(w.name, w.area), s = p && p.slot >= 0 && areaOf(w.area) ? areaOf(w.area).seats[p.slot] : null;
|
|
76
83
|
if (s && mine(s, w.name) && !usedIn(w.area).has(p.slot)) give(w.name, w.area, p.slot);
|
|
77
84
|
}
|
|
78
85
|
for (const w of wants) {
|
|
@@ -81,8 +88,8 @@ export function assignSeats(pack, wants, prev = new Map()) {
|
|
|
81
88
|
if (slot >= 0) give(w.name, w.area, slot);
|
|
82
89
|
}
|
|
83
90
|
for (const w of wants) {
|
|
84
|
-
const p =
|
|
85
|
-
if (!free(w) || !p ||
|
|
91
|
+
const p = prefOf(w.name, w.area);
|
|
92
|
+
if (!free(w) || !p || !pos(w.area, p.slot) || usedIn(w.area).has(p.slot)) continue;
|
|
86
93
|
const s = p.slot >= 0 ? areaOf(w.area).seats[p.slot] : null;
|
|
87
94
|
if (s && s.for && !lent(s)) continue; // reserved for someone else (theirs would be taken above)
|
|
88
95
|
give(w.name, w.area, p.slot);
|
|
@@ -106,11 +113,11 @@ export function assignSeats(pack, wants, prev = new Map()) {
|
|
|
106
113
|
* the desks layout (rooms → desks with a seat), in logical units, plus `mode: "zones"`, the pack's areas and graph (and
|
|
107
114
|
* its `straight`, #2634, and `idleVisits`, #3685), the seats given (`seats`, the next call's `prev`), `crowd` and `over` (the areas over capacity).
|
|
108
115
|
*/
|
|
109
|
-
export function zonesLayout(pack, nodes, prev = new Map(), { night = false } = {}) {
|
|
116
|
+
export function zonesLayout(pack, nodes, prev = new Map(), { night = false, seatPrefs = null } = {}) {
|
|
110
117
|
// At night (#2568) the idle go to bed: the area asleep people go to while it has a free seat; the rest doze where they are.
|
|
111
118
|
const bed = zoneOf(pack, "paused"), bedSeats = own(pack.areas, bed)?.seats || [], sleepers = new Set(), inBed = new Set();
|
|
112
119
|
const wantsOf = (beds) => nodes.filter((n) => n.state !== "missing").map((n) => ({ name: n.name, area: beds.has(n.name) ? bed : zoneOf(pack, n.state) }));
|
|
113
|
-
let placed = assignSeats(pack, wantsOf(inBed), prev);
|
|
120
|
+
let placed = assignSeats(pack, wantsOf(inBed), prev, seatPrefs);
|
|
114
121
|
if (night) {
|
|
115
122
|
// #2691 review: who goes to bed is decided by the seat assignment itself (assignSeats' reservation rules), one
|
|
116
123
|
// sleeper at a time — whoever has a bed of their own there first, then the rest in the fleet's order. A sleeper
|
|
@@ -122,7 +129,7 @@ export function zonesLayout(pack, nodes, prev = new Map(), { night = false } = {
|
|
|
122
129
|
const hasBed = (n) => bedSeats.some((s) => s.for && s.for.includes(n.name));
|
|
123
130
|
for (const n of idle) sleepers.add(n.name);
|
|
124
131
|
for (const n of [...idle.filter(hasBed), ...idle.filter((n) => !hasBed(n))]) {
|
|
125
|
-
const trial = assignSeats(pack, wantsOf(new Set([...inBed, n.name])), prev), s = trial.seats.get(n.name);
|
|
132
|
+
const trial = assignSeats(pack, wantsOf(new Set([...inBed, n.name])), prev, seatPrefs), s = trial.seats.get(n.name);
|
|
126
133
|
if (!s || s.area !== bed || s.slot < 0) {
|
|
127
134
|
if (!hasBed(n)) break; // no bed free for anyone without one: none for the rest either
|
|
128
135
|
continue;
|
package/dist/ui/fleet-office.js
CHANGED
|
@@ -72,11 +72,11 @@ import { hits, needle } from "./fleet-canvas-layout.js";
|
|
|
72
72
|
import { AUTO_ID, LOBBY, autoLayout, backingScale, coatOf, createFlights, customLayout, deskAt, desksOf, filterOk, lampOf, layoutOk, lightOf, membersOf,
|
|
73
73
|
officePose, officeRooms, signOf, workOn } from "./fleet-office-model.js";
|
|
74
74
|
import { BUILT_IN_SKINS, CHAR_DEPTH, DEFAULT_PAL, PICTURE_SKINS, bubbleBox, pixelSkin, loadBuiltInSkin, loadPackSkin, modeOf, skinFor, tagBox, tagFootprint } from "./fleet-office-skin.js";
|
|
75
|
-
import { CALLING, activeFurniture, bubbleAt, hiddenBy, bubbleRank, NIGHT, WANDER, createMail, createWalkers, isNight, linesFor, npcKey, personAt, placeBubbles, thinBubbles, walkTargets, zonesLayout } from "./fleet-office-zones.js";
|
|
75
|
+
import { CALLING, activeFurniture, bubbleAt, hiddenBy, bubbleRank, NIGHT, WANDER, createMail, createWalkers, isNight, linesFor, npcKey, personAt, placeBubbles, routeStaysInArea, thinBubbles, walkTargets, zonesLayout } from "./fleet-office-zones.js";
|
|
76
76
|
import { actsOk, createOfficeStore } from "./fleet-office-store.js";
|
|
77
77
|
import { badgeOf, fixedOf, mergeLevels } from "./fleet-office-levels.js";
|
|
78
78
|
import { OfficeCard, cardModel } from "./fleet-office-card.js";
|
|
79
|
-
import { PLAY, createHold, createSnackDrag, createSnacks, playAllowed, pruneReactions, reactionAt, scatterWords } from "./fleet-office-play.js";
|
|
79
|
+
import { PLAY, applySeatDrop, clampDropForArea, createHold, createSnackDrag, createSnacks, findSeatDropTarget, playAllowed, pruneReactions, reactionAt, scatterWords, seatDropTargets } from "./fleet-office-play.js";
|
|
80
80
|
import { POLL_MS } from "./fleet-traffic.js";
|
|
81
81
|
import { OfficeEditor, officeForSave } from "./fleet-office-editor.js";
|
|
82
82
|
import { LayoutEditor, handlesOf } from "./fleet-office-layout.js";
|
|
@@ -495,9 +495,12 @@ export function drawPart(ctx, p, a, ox, oy, ms, still, hot, env, tagsOff = false
|
|
|
495
495
|
// y (a tie: the item first, the person in front); furniture over them; things in the air; the pack's foreground
|
|
496
496
|
// (door frames, pillars, table fronts); then what must stay readable: crowd counts and name tags (bubbles below).
|
|
497
497
|
const t = ms > 0 ? ms : now(), live = furnitureAt(p, t);
|
|
498
|
+
const draggedHeld = p.hold ? p.hold.held() : null;
|
|
499
|
+
const heldName = draggedHeld ? draggedHeld.name : null;
|
|
498
500
|
if (!still && ms > 0 && p.snacks) {
|
|
501
|
+
const snackHidden = heldName ? new Map(live.hidden).set(heldName, "__held__") : live.hidden;
|
|
499
502
|
const changed = p.snacks.step(t, {
|
|
500
|
-
desks: p.desks, walkers: p.walkers, hidden:
|
|
503
|
+
desks: p.desks, walkers: p.walkers, hidden: snackHidden, ownArea: !!p.ownArea,
|
|
501
504
|
areas: p.L.areas, graph: p.L, snacksById: p.snacksById,
|
|
502
505
|
charEatOf: (n) => (sk.eatStrip ? sk.eatStrip(n) : null),
|
|
503
506
|
onClaim: p.onSnackClaim,
|
|
@@ -519,7 +522,7 @@ export function drawPart(ctx, p, a, ox, oy, ms, still, hot, env, tagsOff = false
|
|
|
519
522
|
// #2665: by day, each item's night place too (at night the items are there already).
|
|
520
523
|
...(p.ghosts && !p.night ? nightGhostsOf(sk.pack).map((n) => ({ y: n.y, k: 1, n })) : [])]
|
|
521
524
|
.sort((x, y) => x.y - y.y || x.k - y.k);
|
|
522
|
-
// M-3432 (#4255): draw drop-target rings above the floor layer only, never over furniture or characters.
|
|
525
|
+
// M-3432 (#4255) & M-3445 (#4266): draw drop-target rings above the floor layer only, never over furniture or characters.
|
|
523
526
|
const drop = p.snackDrop && p.snackDrop.current;
|
|
524
527
|
if (drop && drop.kind === "place") {
|
|
525
528
|
ctx.save();
|
|
@@ -539,8 +542,34 @@ export function drawPart(ctx, p, a, ox, oy, ms, still, hot, env, tagsOff = false
|
|
|
539
542
|
ctx.restore();
|
|
540
543
|
}
|
|
541
544
|
}
|
|
545
|
+
const seatDrop = heldName && p.seatDrop ? p.seatDrop.current : null;
|
|
546
|
+
if (seatDrop && seatDrop.name === heldName && Array.isArray(seatDrop.targets)) {
|
|
547
|
+
for (const st of seatDrop.targets) {
|
|
548
|
+
if (st.current) continue;
|
|
549
|
+
const isHover = !!seatDrop.hover && seatDrop.hover.area === st.area && seatDrop.hover.slot === st.slot;
|
|
550
|
+
ctx.save();
|
|
551
|
+
if (isHover) {
|
|
552
|
+
ctx.fillStyle = env.pal.accentDim;
|
|
553
|
+
ctx.beginPath(); ctx.ellipse(st.x, st.y, 26, 11, 0, 0, Math.PI * 2); ctx.fill();
|
|
554
|
+
ctx.strokeStyle = "rgba(0, 0, 0, 0.38)"; ctx.lineWidth = 4.5;
|
|
555
|
+
ctx.beginPath(); ctx.ellipse(st.x, st.y, 26, 11, 0, 0, Math.PI * 2); ctx.stroke();
|
|
556
|
+
ctx.strokeStyle = env.pal.accent; ctx.lineWidth = 2.5;
|
|
557
|
+
ctx.beginPath(); ctx.ellipse(st.x, st.y, 26, 11, 0, 0, Math.PI * 2); ctx.stroke();
|
|
558
|
+
} else {
|
|
559
|
+
ctx.globalAlpha = 0.9;
|
|
560
|
+
ctx.fillStyle = env.pal.accentDim;
|
|
561
|
+
ctx.beginPath(); ctx.ellipse(st.x, st.y, 22, 10, 0, 0, Math.PI * 2); ctx.fill();
|
|
562
|
+
ctx.strokeStyle = "rgba(0, 0, 0, 0.35)"; ctx.lineWidth = 3.5;
|
|
563
|
+
ctx.beginPath(); ctx.ellipse(st.x, st.y, 22, 10, 0, 0, Math.PI * 2); ctx.stroke();
|
|
564
|
+
ctx.strokeStyle = env.pal.accent; ctx.lineWidth = 2; ctx.setLineDash([5, 3]);
|
|
565
|
+
ctx.beginPath(); ctx.ellipse(st.x, st.y, 22, 10, 0, 0, Math.PI * 2); ctx.stroke();
|
|
566
|
+
}
|
|
567
|
+
ctx.restore();
|
|
568
|
+
}
|
|
569
|
+
}
|
|
542
570
|
for (const f of furniture) if (f.depth !== "y" && f.depth < CHAR_DEPTH) sk.drawFurniture(ctx, f, f.asleep || live.active.has(f.id), ms, env);
|
|
543
571
|
for (const it of post) if (it.t === 0) sk.drawProp(ctx, it, ms, env); // a letter on the floor: under the people
|
|
572
|
+
let heldPerson = null;
|
|
544
573
|
for (const { f, p: q, g, n, sn } of band) {
|
|
545
574
|
if (f) { sk.drawFurniture(ctx, f, f.asleep || live.active.has(f.id), ms, env); continue; }
|
|
546
575
|
if (sn) {
|
|
@@ -556,6 +585,7 @@ export function drawPart(ctx, p, a, ox, oy, ms, still, hot, env, tagsOff = false
|
|
|
556
585
|
}
|
|
557
586
|
if (n) { ctx.save(); ctx.globalAlpha = GHOST_ALPHA; sk.drawFurniture(ctx, n, true, 0, env); ctx.restore(); continue; }
|
|
558
587
|
if (g) { ctx.save(); ctx.globalAlpha = GHOST_ALPHA; sk.drawCharacter(ctx, { x: g.x - 44, y: g.y - 53, w: 88, h: 53, seat: g }, g.look, 0, env); ctx.restore(); continue; }
|
|
588
|
+
if (heldName && q.look.name === heldName) { heldPerson = q; continue; } // M-3445 (#4267): drawn lifted on top below
|
|
559
589
|
if (live.hidden.has(q.look.name)) continue; // #2698: drawn as the item (never while walking)
|
|
560
590
|
const box = { ...q.d, x: q.at.x - 44, y: q.at.y - 53, w: 88, h: 53, seat: { x: q.at.x, y: q.at.y } };
|
|
561
591
|
// An agent's own pose (office_set, #2578) while its act lasts and nothing calls it; walking is walking; M-3432: eating when fed.
|
|
@@ -574,6 +604,12 @@ export function drawPart(ctx, p, a, ox, oy, ms, still, hot, env, tagsOff = false
|
|
|
574
604
|
}
|
|
575
605
|
}
|
|
576
606
|
for (const f of furniture) if (f.depth !== "y" && f.depth >= CHAR_DEPTH) sk.drawFurniture(ctx, f, f.asleep || live.active.has(f.id), ms, env);
|
|
607
|
+
// M-3445 (#4267): the character currently being dragged renders lifted above furniture and other characters in its `dragged` pose.
|
|
608
|
+
if (heldPerson) {
|
|
609
|
+
const box = { ...heldPerson.d, x: heldPerson.at.x - 44, y: heldPerson.at.y - 53, w: 88, h: 53, seat: { x: heldPerson.at.x, y: heldPerson.at.y } };
|
|
610
|
+
const posed = actPosed(p, heldPerson.look);
|
|
611
|
+
sk.drawCharacter(ctx, box, { ...posed, pose: "dragged", basePose: posed.pose }, ms, env);
|
|
612
|
+
}
|
|
577
613
|
for (const it of up) sk.drawProp(ctx, it, ms, env);
|
|
578
614
|
for (const it of post) if (it.t > 0) sk.drawProp(ctx, it, ms, env);
|
|
579
615
|
if (sk.drawForeground) sk.drawForeground(ctx, p.L, env);
|
|
@@ -588,7 +624,7 @@ export function drawPart(ctx, p, a, ox, oy, ms, still, hot, env, tagsOff = false
|
|
|
588
624
|
const taken = [];
|
|
589
625
|
const touches = (b) => taken.some((o) => b.x < o.x + o.w && o.x < b.x + b.w && b.y < o.y + o.h && o.y < b.y + b.h);
|
|
590
626
|
for (const q of people) {
|
|
591
|
-
if (live.hidden.has(q.look.name) || !tagged(q)) continue;
|
|
627
|
+
if ((live.hidden.has(q.look.name) && q.look.name !== heldName) || !tagged(q)) continue;
|
|
592
628
|
sk.drawTag(ctx, q.at.x, q.at.y, q.look, env);
|
|
593
629
|
const box = tagBox(ctx, q.at.x, q.at.y, q.look.label);
|
|
594
630
|
tags.push(box); taken.push(tagFootprint(ctx, box, q.look.badge));
|
|
@@ -599,7 +635,7 @@ export function drawPart(ctx, p, a, ox, oy, ms, still, hot, env, tagsOff = false
|
|
|
599
635
|
// kept on the scene (`heldTags`): hitPart hits each person on theirs, past the picture's edge too (#2699 review).
|
|
600
636
|
const held = [];
|
|
601
637
|
for (const f of furniture) {
|
|
602
|
-
const on = people.filter((q) => live.hidden.get(q.look.name) === f.id);
|
|
638
|
+
const on = people.filter((q) => live.hidden.get(q.look.name) === f.id && q.look.name !== heldName);
|
|
603
639
|
if (!on.length) {
|
|
604
640
|
if (!tagsOff && f.label) {
|
|
605
641
|
const nl = npcLook(p, f), box = tagBox(ctx, f.x, f.y, nl.label);
|
|
@@ -704,7 +740,7 @@ export function drawPart(ctx, p, a, ox, oy, ms, still, hot, env, tagsOff = false
|
|
|
704
740
|
}
|
|
705
741
|
} };
|
|
706
742
|
if (defer) defer.push(say); else say();
|
|
707
|
-
return walking || up.length > 0 || p.flights.size() > 0 || post.some((it) => it.t > 0) || rising.length > 0 || !!reacting || (!!p.snacks && p.snacks.active(t0)) || !!(p.snackDrop && p.snackDrop.current);
|
|
743
|
+
return walking || up.length > 0 || p.flights.size() > 0 || post.some((it) => it.t > 0) || rising.length > 0 || !!reacting || (!!p.snacks && p.snacks.active(t0)) || !!(p.snackDrop && p.snackDrop.current) || !!(p.hold && p.hold.held());
|
|
708
744
|
}
|
|
709
745
|
/**
|
|
710
746
|
* #2661: an NPC's name tag (a furniture item's label) — with the title a pack pins on it (`levels.fixed` by its id),
|
|
@@ -895,6 +931,8 @@ export function Office({ view, traffic, q = "", lease, onOpen, assetUrl, assetIm
|
|
|
895
931
|
const flights = useMemo(() => createFlights(), []);
|
|
896
932
|
const walkers = useMemo(() => createWalkers(), []);
|
|
897
933
|
const seatsRef = useRef(new Map()); // the zones layout's last seats: kept where they can be
|
|
934
|
+
const seatPrefsRef = useRef({}), seatKeyRef = useRef(""), seatDropRef = useRef(null);
|
|
935
|
+
const [seatRev, setSeatRev] = useState(0);
|
|
898
936
|
// #2554: All offices' tiles keep their own: seats (by tile and style), walkers and flights (by tile); and the items
|
|
899
937
|
// flying between tiles.
|
|
900
938
|
const tileSeats = useRef(new Map()), tileWalkers = useRef(new Map()), tileFlights = useRef(new Map());
|
|
@@ -1162,17 +1200,30 @@ export function Office({ view, traffic, q = "", lease, onOpen, assetUrl, assetIm
|
|
|
1162
1200
|
// While Edit layout is open: a faint figure on every seat, in the pose its area is for (#2558), so a seat is placed by
|
|
1163
1201
|
// what will stand, sit or lie there, not by a dot.
|
|
1164
1202
|
const ghosts = zones && !!layout && !layoutStale;
|
|
1203
|
+
const shared = talk !== undefined || typeof onOpen !== "function";
|
|
1204
|
+
// What a view and per-device seat choices are kept for: the office and its style (All offices: its own key).
|
|
1205
|
+
const officeKey = overview ? `${ALL_ID}@tiles` : `${custom ? custom.id : AUTO_ID}@${baseSkin.id}`;
|
|
1165
1206
|
const keep = (n) => !(hideAsleep && ASLEEP.has(n.state));
|
|
1166
1207
|
const single = useMemo(() => {
|
|
1167
1208
|
if (overview) return { rooms: [], width: 1, height: 1 }; // All offices: the tiles below
|
|
1168
1209
|
const all = custom ? membersOf(custom, view) : [...new Map(officeRooms(view, filter).flatMap((r) => r.nodes).map((n) => [n.name, n])).values()];
|
|
1169
1210
|
const nodes = all.filter(keep);
|
|
1170
|
-
if (zones) {
|
|
1211
|
+
if (zones) {
|
|
1212
|
+
const skKey = shared ? "" : officeKey;
|
|
1213
|
+
if (seatKeyRef.current !== skKey) {
|
|
1214
|
+
seatKeyRef.current = skKey;
|
|
1215
|
+
seatsRef.current = new Map();
|
|
1216
|
+
seatPrefsRef.current = skKey ? store.seats(skKey) : {};
|
|
1217
|
+
}
|
|
1218
|
+
const z = zonesLayout(skin.pack, nodes, seatsRef.current, { night, seatPrefs: skKey ? seatPrefsRef.current : null });
|
|
1219
|
+
seatsRef.current = z.seats;
|
|
1220
|
+
return z;
|
|
1221
|
+
}
|
|
1171
1222
|
// The desks wrap at the stage's width at the scale they open on (desksK: a pixel level near one CSS px a unit).
|
|
1172
1223
|
const deskW = Math.max(240, Math.floor(width / desksK(ratio)));
|
|
1173
1224
|
if (!custom) return autoLayout(officeRooms(view, filter).map((r) => (hideAsleep ? { ...r, nodes: r.nodes.filter(keep) } : r)), { width: deskW });
|
|
1174
1225
|
return officeScene(custom, nodes, skin, false, deskW);
|
|
1175
|
-
}, [overview, view, filter, custom, width, ratio, skin, hideAsleep, night]);
|
|
1226
|
+
}, [overview, view, filter, custom, width, ratio, skin, hideAsleep, night, seatRev, officeKey, shared]);
|
|
1176
1227
|
// ── #2554: All offices' tiles — each stored office (then the lobby: whoever is in no office) laid out as its own view
|
|
1177
1228
|
// lays it out, in its own style (desks wrap at a cell's width), with its own seats, walkers and flights ──
|
|
1178
1229
|
const lobbyAll = useMemo(() => (overview ? lobbyNodes(stored, view) : []), [overview, stored, view]);
|
|
@@ -1220,8 +1271,7 @@ export function Office({ view, traffic, q = "", lease, onOpen, assetUrl, assetIm
|
|
|
1220
1271
|
const visitMemo = useMemo(() => ({ claims: new Map(), idle: null }), [skin]);
|
|
1221
1272
|
// M-3293: play — never on a share link's page (no onOpen there, or its own `talk`), with reduced motion, in All
|
|
1222
1273
|
// offices, the carousel or Edit layout. `hold`: the person picked up (carried where the pointer is, walked back from
|
|
1223
|
-
// where they are dropped
|
|
1224
|
-
const shared = talk !== undefined || typeof onOpen !== "function";
|
|
1274
|
+
// where they are dropped, or seated on another seat in their area: M-3445 #4266/#4267); `reacts`: pats and feeds showing.
|
|
1225
1275
|
const play = playAllowed({ on: playOn, still, zones, overview, layout: !!layout, shared }) && !carouselPick;
|
|
1226
1276
|
const hold = useMemo(() => createHold(), []), reacts = useRef(new Map()), walkNow = useRef(null), holdTimer = useRef(null);
|
|
1227
1277
|
// M-3432 (#4255): custom snacks from the active skin pack (client-local, only when play is enabled).
|
|
@@ -1239,7 +1289,7 @@ export function Office({ view, traffic, q = "", lease, onOpen, assetUrl, assetIm
|
|
|
1239
1289
|
if (store.tellOn(winner)) void store.tell(winner, "feed");
|
|
1240
1290
|
loop.current?.wake();
|
|
1241
1291
|
};
|
|
1242
|
-
useEffect(() => { if (!play) { snackDragCtrl.retire(); hold.cancel(); reacts.current.clear(); snacks.clear(); snackDropRef.current = null; setArmedSnack(null); setSnackDrag(null); } }, [play]);
|
|
1292
|
+
useEffect(() => { if (!play) { const wasHeld = !!hold.held(); snackDragCtrl.retire(); hold.cancel(); seatDropRef.current = null; reacts.current.clear(); snacks.clear(); snackDropRef.current = null; setArmedSnack(null); setSnackDrag(null); if (wasHeld) walkNow.current?.(); } }, [play]);
|
|
1243
1293
|
useEffect(() => { if (!showSnacks) { snackDragCtrl.retire(); snackDropRef.current = null; setArmedSnack(null); setSnackDrag(null); } }, [showSnacks]);
|
|
1244
1294
|
useEffect(() => () => { snackDragCtrl.retire(); }, []);
|
|
1245
1295
|
useEffect(() => {
|
|
@@ -1281,10 +1331,8 @@ export function Office({ view, traffic, q = "", lease, onOpen, assetUrl, assetIm
|
|
|
1281
1331
|
const touched = useRef(false), fitted = useRef(false), drag = useRef(gestureState());
|
|
1282
1332
|
const miniViewRef = useRef(null), miniRef = useRef(null), overlayEl = useRef(null), tipDeskRef = useRef(null), pctRef = useRef(null);
|
|
1283
1333
|
const labelEls = useRef(new Map()); // #2554: the tiles' labels (tile key → element)
|
|
1284
|
-
// What a view is kept for: the office and its style (All offices: its own key).
|
|
1285
|
-
const officeKey = overview ? `${ALL_ID}@tiles` : `${custom ? custom.id : AUTO_ID}@${baseSkin.id}`;
|
|
1286
1334
|
snackCtxRef.current = { showSnacks, officeKey, styleKey };
|
|
1287
|
-
useEffect(() => { snackDragCtrl.retire(); snacks.clear(); snackDropRef.current = null; setArmedSnack(null); setSnackDrag(null); }, [officeKey, styleKey]);
|
|
1335
|
+
useEffect(() => { snackDragCtrl.retire(); hold.cancel(); seatDropRef.current = null; snacks.clear(); snackDropRef.current = null; setArmedSnack(null); setSnackDrag(null); }, [officeKey, styleKey]);
|
|
1288
1336
|
const keyRef = useRef(officeKey), saveTimer = useRef(0);
|
|
1289
1337
|
// The fit mode (Fit: contain; Fill: cover), kept per office and style like the view.
|
|
1290
1338
|
const [fitRev, setFitRev] = useState(0);
|
|
@@ -1544,6 +1592,7 @@ export function Office({ view, traffic, q = "", lease, onOpen, assetUrl, assetIm
|
|
|
1544
1592
|
scene.current = { ...base, overview: true, parts, lay: arranged };
|
|
1545
1593
|
} else {
|
|
1546
1594
|
scene.current = { ...base, overview: false, part: { ...partOf(L, looks, skin, zones, walkers, flights), ghosts, night, mail, acts: actsHere, actSeen: actSeen.current, ups: ups.current, levelsOn: !!(lv && lv.enabled), levels: wordsOf(skin), reacts: reacts.current,
|
|
1595
|
+
hold: play ? hold : null, seatDrop: seatDropRef,
|
|
1547
1596
|
snacks: play ? snacks : null, snacksById, ownArea, snackDrop: snackDropRef, onSnackClaim, onSnacksChanged: () => walkNow.current?.() } };
|
|
1548
1597
|
}
|
|
1549
1598
|
if (still) draw(0); else loop.current?.wake();
|
|
@@ -1766,12 +1815,24 @@ export function Office({ view, traffic, q = "", lease, onOpen, assetUrl, assetIm
|
|
|
1766
1815
|
pinch: (from, to) => { raw.current = Math.min(OK_MAX, Math.max(OK_MIN, raw.current * (to.dist / from.dist))); setView(pinchOffice(view0(), from, to, raw.current)); } });
|
|
1767
1816
|
/** Where a drag pans: the canvas, and Edit layout's overlay off its handles (the controls, the bar and the list: never). */
|
|
1768
1817
|
const onScene = (el) => !!el && (el === canvasRef.current || (typeof el.closest === "function" && !!el.closest(".ol-svg") && !el.closest(".ol-handle")));
|
|
1769
|
-
/** M-3293
|
|
1818
|
+
/** M-3293 / M-3445: update the floor-level seat drop targets while carrying `h` ({ name, at }). */
|
|
1819
|
+
const updateSeatDrop = (h) => {
|
|
1820
|
+
if (!h || !zones || !skin || !skin.pack) { seatDropRef.current = null; return; }
|
|
1821
|
+
const ds = desksOf(L);
|
|
1822
|
+
seatDropRef.current = {
|
|
1823
|
+
name: h.name,
|
|
1824
|
+
targets: seatDropTargets(skin.pack, ds, h.name),
|
|
1825
|
+
hover: findSeatDropTarget(skin.pack, ds, h.name, h.at),
|
|
1826
|
+
};
|
|
1827
|
+
};
|
|
1828
|
+
/** M-3293 / M-3445: someone picked up — enters `dragged` pose under the pointer, highlights valid seats in their area. */
|
|
1770
1829
|
const pickedUp = (pointerId) => {
|
|
1771
1830
|
const h = hold.held();
|
|
1772
1831
|
if (!h) return;
|
|
1773
1832
|
// Captured only now: a press that stays a click must reach the canvas (its card), which a capture would take away.
|
|
1774
1833
|
try { stageRef.current.setPointerCapture(pointerId); } catch { /* gone */ }
|
|
1834
|
+
snacks.cancel(h.name);
|
|
1835
|
+
updateSeatDrop(h);
|
|
1775
1836
|
walkers.place(h.name, h.at); drag.current.swallow = true;
|
|
1776
1837
|
setTip(null); setCard(null); loop.current?.wake();
|
|
1777
1838
|
};
|
|
@@ -1789,24 +1850,60 @@ export function Office({ view, traffic, q = "", lease, onOpen, assetUrl, assetIm
|
|
|
1789
1850
|
g.down(e);
|
|
1790
1851
|
if (drag.current.pts.size === 2) raw.current = view0().k; // a pinch starts from the zoom shown
|
|
1791
1852
|
};
|
|
1792
|
-
/** M-3293: while a press may pick someone up it is theirs (no pan); once held it carries them; a finger that moved first pans. */
|
|
1853
|
+
/** M-3293 / M-3445: while a press may pick someone up it is theirs (no pan); once held it carries them; a finger that moved first pans. */
|
|
1793
1854
|
const onStageMove = (e) => {
|
|
1794
1855
|
if (hold.state()) {
|
|
1795
1856
|
const w = pointOf(e), was = hold.state();
|
|
1796
1857
|
const st = w ? hold.move(e.pointerId, w.x, w.y, now(), e.clientX, e.clientY) : hold.state();
|
|
1797
|
-
if (st === "held") {
|
|
1858
|
+
if (st === "held") {
|
|
1859
|
+
if (was !== "held") pickedUp(e.pointerId);
|
|
1860
|
+
else { const h = hold.held(); updateSeatDrop(h); walkers.place(h.name, h.at); loop.current?.wake(); }
|
|
1861
|
+
return;
|
|
1862
|
+
}
|
|
1798
1863
|
if (st === "maybe" || st === "press") return;
|
|
1799
|
-
if (st === "pan") { clearTimeout(holdTimer.current); hold.cancel(); }
|
|
1864
|
+
if (st === "pan") { clearTimeout(holdTimer.current); hold.cancel(); seatDropRef.current = null; }
|
|
1800
1865
|
}
|
|
1801
1866
|
g.move(e);
|
|
1802
1867
|
};
|
|
1868
|
+
/** M-3445 (#4266): settle a dragged character onto a valid seat in their area (or clamp/walk back to their seat). */
|
|
1869
|
+
const finishHoldDrop = (r, commitSeat) => {
|
|
1870
|
+
seatDropRef.current = null;
|
|
1871
|
+
if (!r) return;
|
|
1872
|
+
const ds = desksOf(L);
|
|
1873
|
+
const target = commitSeat && zones && skin && skin.pack ? findSeatDropTarget(skin.pack, ds, r.name, r.at) : null;
|
|
1874
|
+
if (target) {
|
|
1875
|
+
if (!target.current) {
|
|
1876
|
+
const res = applySeatDrop({ pack: skin.pack, desks: ds, seats: seatsRef.current, prefs: seatPrefsRef.current, name: r.name, target });
|
|
1877
|
+
seatsRef.current = res.seats;
|
|
1878
|
+
seatPrefsRef.current = res.prefs;
|
|
1879
|
+
if (!shared) store.saveSeats(officeKey, res.prefs);
|
|
1880
|
+
if (res.swapped) {
|
|
1881
|
+
const occPos = walkers.at(res.swapped.name, now()) || { x: target.x, y: target.y };
|
|
1882
|
+
if (ownArea && !routeStaysInArea(occPos, res.swapped.seat, L, target.area, null)) {
|
|
1883
|
+
walkers.place(res.swapped.name, res.swapped.seat);
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1886
|
+
walkers.place(r.name, { x: target.x, y: target.y });
|
|
1887
|
+
setSeatRev((n) => n + 1);
|
|
1888
|
+
} else {
|
|
1889
|
+
walkers.place(r.name, { x: target.x, y: target.y });
|
|
1890
|
+
walkNow.current?.();
|
|
1891
|
+
}
|
|
1892
|
+
} else {
|
|
1893
|
+
const d = ds.find((x) => x && x.node && x.node.name === r.name);
|
|
1894
|
+
const landAt = ownArea && d ? clampDropForArea(r.at, d.seat, L, d.area) : r.at;
|
|
1895
|
+
walkers.place(r.name, landAt);
|
|
1896
|
+
walkNow.current?.();
|
|
1897
|
+
}
|
|
1898
|
+
loop.current?.wake();
|
|
1899
|
+
};
|
|
1803
1900
|
const onStageUp = (e) => {
|
|
1804
1901
|
clearTimeout(holdTimer.current);
|
|
1805
1902
|
const r = hold.up(e.pointerId);
|
|
1806
|
-
if (r) {
|
|
1903
|
+
if (r) { finishHoldDrop(r, true); drag.current.swallow = true; setTimeout(() => { if (!drag.current.pts.size) drag.current.swallow = false; }, 0); }
|
|
1807
1904
|
g.up(e);
|
|
1808
1905
|
};
|
|
1809
|
-
const onStageCancel = (e) => { clearTimeout(holdTimer.current); const r = hold.up(e.pointerId);
|
|
1906
|
+
const onStageCancel = (e) => { clearTimeout(holdTimer.current); const r = hold.up(e.pointerId); finishHoldDrop(r, false); g.up(e); };
|
|
1810
1907
|
const onWheel = (e) => {
|
|
1811
1908
|
if (!onScene(e.target) && !(typeof e.target?.closest === "function" && e.target.closest(".ol-handle, .oo-tile-label"))) return;
|
|
1812
1909
|
e.preventDefault();
|
|
@@ -1816,6 +1913,14 @@ export function Office({ view, traffic, q = "", lease, onOpen, assetUrl, assetIm
|
|
|
1816
1913
|
};
|
|
1817
1914
|
const onKeyDown = (e) => {
|
|
1818
1915
|
if (e.defaultPrevented) return; // Edit layout's handles move with the arrows
|
|
1916
|
+
if (e.key === "Escape" && hold.held()) {
|
|
1917
|
+
e.preventDefault();
|
|
1918
|
+
clearTimeout(holdTimer.current);
|
|
1919
|
+
const h = hold.held();
|
|
1920
|
+
hold.cancel();
|
|
1921
|
+
finishHoldDrop(h, false);
|
|
1922
|
+
return;
|
|
1923
|
+
}
|
|
1819
1924
|
const tag = e.target && e.target.tagName;
|
|
1820
1925
|
if (tag === "INPUT" || tag === "SELECT" || tag === "TEXTAREA") return;
|
|
1821
1926
|
const z = zoomKey(e);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import {hostTime} from './host-time.js';
|
|
2
|
+
import {html,useState,useEffect,useRef} from '/assets/app-html.js';
|
|
3
|
+
import {register,t,lang} from '/assets/app-i18n.js';
|
|
4
|
+
import {fleetPath} from '/assets/app-route.js';
|
|
5
|
+
register('hostAlerts',{
|
|
6
|
+
en:{started:'Started ',title:'Host alerts',warning:'Warning',urgent:'Urgent',recovered:'Recovered',cpu:'CPU',memory:'Memory pressure',filesystem:'Filesystem',backing:'Windows backing drive',value:'Current: {0} · Threshold: {1}',pressureValue:'Current: {0} ({1})',pressureWarning:'warning threshold reached',pressureUrgent:'urgent threshold reached',pressureRecovery:'waiting for recovery confirmation',ack:'Acknowledge',acknowledged:'Acknowledged',snooze:'Snooze for 1 hour',snoozed:'Snoozed until {0}',busy:'Saving…',open:'View host health',failed:'Host alerts are unavailable. Check monitoring settings and local storage.',pending:'{0} notifications pending',error:'Could not save. Refresh the page and try again.',normal:'Normal',elevated:'Elevated',critical:'Critical',none:'No active host alerts',age:'Last incident update:',kept:'Acknowledging keeps the problem visible. An urgent escalation bypasses a warning snooze.'},
|
|
7
|
+
'zh-TW':{started:'發生於 ',title:'主機警示',warning:'注意',urgent:'緊急',recovered:'已恢復',cpu:'CPU',memory:'記憶體壓力',filesystem:'檔案系統',backing:'存放 WSL 的 Windows 磁碟',value:'目前:{0} · 門檻:{1}',pressureValue:'目前:{0}({1})',pressureWarning:'達到注意門檻',pressureUrgent:'達到緊急門檻',pressureRecovery:'等待恢復確認',ack:'我已看過',acknowledged:'已看過',snooze:'暫停提醒 1 小時',snoozed:'暫停提醒至 {0}',busy:'儲存中…',open:'查看主機狀態',failed:'主機警示無法使用,請檢查監測設定與本機儲存空間。',pending:'{0} 則通知待送出',error:'無法儲存,請重新整理頁面後再試。',normal:'正常',elevated:'偏高',critical:'嚴重',none:'目前沒有主機警示',age:'問題最後更新:',kept:'標記已看過後,問題仍會顯示。升為緊急時會略過注意等級的暫停提醒。'}
|
|
8
|
+
});
|
|
9
|
+
export const hostAlertText=(key,...args)=>t('hostAlerts.'+key,...args);
|
|
10
|
+
export function hostAlertValue(record,value=record.value){return record.kind==='backing-drive'?(value/1024**3).toFixed(1)+' GiB':record.kind==='memory'?hostAlertText(['normal','elevated','critical'][value]||'failed'):value.toFixed(1)+'%';}
|
|
11
|
+
export function hostAlertName(record){const label=hostAlertText(({cpu:'cpu',memory:'memory',filesystem:'filesystem','backing-drive':'backing'})[record?.kind]||'title');return label+(record?.kind==='filesystem'&&/^disk:[a-f0-9]{16}$/.test(record.key||'')?' · '+record.key.slice(-6):'');}
|
|
12
|
+
export function hostAlertDrive(drive){return /^[A-Z]$/.test(drive||'')?(lang()==='zh-TW'?'('+drive+':)':' ('+drive+':)'):'';}
|
|
13
|
+
export function hostAlertDescription(record){return record.kind==='memory'?hostAlertText('pressureValue',hostAlertValue(record),hostAlertText(record.value>=record.threshold?(record.level==='urgent'?'pressureUrgent':'pressureWarning'):'pressureRecovery')):hostAlertText('value',hostAlertValue(record),hostAlertValue(record,record.threshold));}
|
|
14
|
+
export function HostAlertActions({record,onChange}){
|
|
15
|
+
const [busy,setBusy]=useState(false),[error,setError]=useState(false),alive=useRef(true);
|
|
16
|
+
useEffect(()=>{alive.current=true;return()=>{alive.current=false;};},[]);
|
|
17
|
+
const act=async(snoozeMs)=>{if(busy)return;setBusy(true);setError(false);try{const response=await fetch('/ui/host-alert-action',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({key:record.key,revision:record.revision,...(snoozeMs?{snoozeMs}:{})})});if(!response.ok)throw Error();if(alive.current)onChange?.();}catch{if(alive.current)setError(true);}finally{if(alive.current)setBusy(false);}};
|
|
18
|
+
return html`<div><div class="n-actions"><button type="button" class="btn btn-sm" disabled=${busy||record.acknowledgedAt!==undefined} onClick=${()=>act()}>${hostAlertText(busy?'busy':record.acknowledgedAt!==undefined?'acknowledged':'ack')}</button><button type="button" class="btn btn-sm" disabled=${busy} onClick=${()=>act(3600000)}>${hostAlertText('snooze')}</button><a class="btn btn-sm" href=${fleetPath('host-health')}>${hostAlertText('open')}</a></div>${error?html`<p class="notice warn" role="alert">${hostAlertText('error')}</p>`:null}</div>`;
|
|
19
|
+
}
|
|
20
|
+
export function HostAlerts({alerts,onChange}){
|
|
21
|
+
if(!alerts||alerts.state==='off')return null;
|
|
22
|
+
return html`<section class="card host-alerts"><h3>${hostAlertText('title')}</h3>${alerts.state==='failed'?html`<p class="notice warn" role="alert">${hostAlertText('failed')}</p>`:alerts.active.length?alerts.active.map(record=>html`<article key=${record.key} class="host-volume"><div class="host-row"><h4>${hostAlertName(record)}</h4><span class="tag">${hostAlertText(record.level)}</span></div><p>${hostAlertDescription(record)}</p><p class="note">${hostAlertText('age')}${lang()==='zh-TW'?'':' '}<span class="host-sample-time">${hostTime(record.updatedAt)}</span></p>${record.snoozedUntil>Date.now()?html`<p class="note">${hostAlertText('snoozed',hostTime(record.snoozedUntil))}</p>`:null}<${HostAlertActions} record=${record} onChange=${onChange}/></article>`):html`<p class="note">${hostAlertText('none')}</p>`}${alerts.active.length?html`<p class="note">${hostAlertText('kept')}</p>`:null}${alerts.pending?html`<p class="note">${hostAlertText('pending',alerts.pending)}</p>`:null}</section>`;
|
|
23
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import {html} from '/assets/app-html.js';
|
|
2
|
+
import {register,t} from '/assets/app-i18n.js';
|
|
3
|
+
import {displayBytes} from './host-health-model.js';
|
|
4
|
+
import {hostTime} from './host-time.js';
|
|
5
|
+
register('hostFootprint',{
|
|
6
|
+
en:{title:'Agent footprint',off:'Agent footprint is off. Enable it separately in Monitoring settings.',waiting:'Waiting for a bounded process sample.',unavailable:'Process attribution is unavailable. Missing readings are not zero.',coverage:'{0} of {1} agent roots covered',agent:'Agent',cpu:'CPU',memory:'RSS estimate',managed:'Known managed files',shared:'Shared service overhead',notes:'CPU is a percentage of this computer’s total capacity. RSS includes descendants and may count shared pages twice. Processes that start and exit between samples are not included. Managed sizes cover known output files only; workspaces are not measured.',retention:'Agent samples every 60 s; raw history up to 6 hours and rollups up to 7 days, within the shared 64 MiB cap.',previous:'Previous agents',next:'More agents',unknown:'Not measured',stale:'Stale sample',sample:'Sample: {0}',historyFor:'History: {0}',select:'Select agent history',agentCpu:'Agent CPU',agentMemory:'Agent RSS'},
|
|
7
|
+
'zh-TW':{title:'Agent 資源用量',off:'Agent 資源用量已關閉,請在監測設定中另外開啟。',waiting:'正在等待下一次行程取樣。',unavailable:'無法確認行程歸屬。缺少讀數不代表零。',coverage:'{1} 個 Agent 根行程中已確認 {0} 個',agent:'Agent',cpu:'CPU',memory:'記憶體(估)',managed:'管理檔案',shared:'共用服務',notes:'CPU 代表這台電腦總容量的百分比。RSS 包含子行程,共用記憶體頁可能重複計算。兩次取樣之間啟動又結束的行程不會列入。檔案大小只計算已知的輸出檔案,不量測工作區。',retention:'Agent 每 60 秒取樣;原始資料最多 6 小時,彙整最多 7 天,共用 64 MiB 上限。',previous:'上一頁 Agent',next:'更多 Agent',unknown:'未量測',stale:'取樣已過期',sample:'取樣:{0}',historyFor:'歷史:{0}',select:'選擇 Agent 歷史',agentCpu:'Agent CPU',agentMemory:'Agent RSS'}
|
|
8
|
+
});
|
|
9
|
+
export const footprintText=(key,...args)=>t('hostFootprint.'+key,...args);
|
|
10
|
+
const copy=footprintText;
|
|
11
|
+
export function HostFootprintView({snapshot,offset=0,onOffset,onSelect,selected,charts}){
|
|
12
|
+
const reading=snapshot?.reading,number=(value,unit)=>typeof value==='number'&&Number.isFinite(value)?unit==='percent'?value.toFixed(2)+'%':displayBytes(value):copy('unknown');
|
|
13
|
+
return html`<section class="card host-footprint"><h3>${copy('title')}</h3>${!snapshot?.enabled?html`<p>${copy('off')}</p>`:!reading?html`<p role="status">${copy(snapshot.status==='starting'?'waiting':'unavailable')}</p>`:html`
|
|
14
|
+
${snapshot.status==='stale'?html`<p class="notice warn">${copy('stale')}</p>`:null}<p class="note host-footprint-sample"><span>${copy('coverage',reading.covered,reading.total)}</span><span class="host-sample-time">${copy('sample',hostTime(reading.sampledAt))}</span></p>
|
|
15
|
+
<div class="table-wrap"><table><thead><tr><th>${copy('agent')}</th><th>${copy('cpu')}</th><th class="host-footprint-memory">${copy('memory')}</th><th class="host-footprint-managed">${copy('managed')}</th></tr></thead><tbody>${reading.rows.slice(0,50).map(row=>html`<tr key=${row.id}><th><button class="btn btn-sm" type="button" aria-label=${copy('select')+': '+(row.label||copy('agent'))} aria-pressed=${selected===row.id} onClick=${()=>onSelect?.(row.id)}>${row.label||copy('agent')}</button></th><td>${number(row.cpuPercent,'percent')}</td><td>${number(row.rssBytes,'bytes')}</td><td>${number(row.managedBytes,'bytes')}</td></tr>`)}<tr><th>${copy('shared')}</th><td>${number(reading.shared.cpuPercent,'percent')}</td><td>${number(reading.shared.rssBytes,'bytes')}</td><td>${copy('unknown')}</td></tr></tbody></table></div>
|
|
16
|
+
${offset>0||reading.hasMore?html`<div class="n-actions"><button class="btn btn-sm" type="button" disabled=${offset===0} onClick=${()=>onOffset?.(Math.max(0,offset-50))}>${copy('previous')}</button><button class="btn btn-sm" type="button" disabled=${!reading.hasMore} onClick=${()=>onOffset?.(offset+50)}>${copy('next')}</button></div>`:null}${charts?html`<section class="host-agent-history"><h4>${copy('historyFor',reading.rows.find(r=>r.id===selected)?.label||copy('agent'))}</h4>${charts}</section>`:null}<p class="note">${copy('notes')}</p><p class="note">${copy('retention')}</p>`}</section>`;
|
|
17
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Presentation only: these helpers cannot sample, open history or turn monitoring on.
|
|
2
|
+
export const HOST_RANGES = ["1h", "24h", "7d", "30d"];
|
|
3
|
+
export const numberOrNull = (value, maximum = Number.MAX_SAFE_INTEGER) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= maximum ? value : null;
|
|
4
|
+
export function metricState(metric, interval, now = Date.now()) {
|
|
5
|
+
if (metric?.status !== "ok") return metric?.status === "stale" ? "stale" : "unavailable";
|
|
6
|
+
return numberOrNull(metric.sampledAt) === null || now - metric.sampledAt >= interval * 2 ? "stale" : "ok";
|
|
7
|
+
}
|
|
8
|
+
export function displayBytes(value) {
|
|
9
|
+
const n = numberOrNull(value);if (n === null) return null;
|
|
10
|
+
if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(1)} GiB`;
|
|
11
|
+
if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(0)} MiB`;
|
|
12
|
+
return `${Math.round(n / 1024)} KiB`;
|
|
13
|
+
}
|
|
14
|
+
export function storageRows(snapshot) {
|
|
15
|
+
return (Array.isArray(snapshot?.disks?.value?.volumes) ? snapshot.disks.value.volumes : []).slice(0,8)
|
|
16
|
+
.filter(v => v && /^[a-f0-9]{16}$/.test(v.id) && Array.isArray(v.roles))
|
|
17
|
+
.sort((a,b) => (numberOrNull(a.availableBytes) ?? Infinity) - (numberOrNull(b.availableBytes) ?? Infinity));
|
|
18
|
+
}
|
|
19
|
+
export function historySeries(snapshot) {
|
|
20
|
+
return ["cpu.used", "memory.available", "memory.pressure", "swap.free", ...storageRows(snapshot).flatMap(v => [`disk.${v.id}.available`, `disk.${v.id}.used`])];
|
|
21
|
+
}
|
|
22
|
+
/** Null gaps break lines; even a damaged response cannot draw more than240 points. */
|
|
23
|
+
export function chartData(input) {
|
|
24
|
+
const buckets = Array.isArray(input) ? input.slice(0,240) : [];
|
|
25
|
+
const valid = b => b && numberOrNull(b.average) !== null && numberOrNull(b.min) !== null && numberOrNull(b.max) !== null && numberOrNull(b.count) > 0;
|
|
26
|
+
const values=buckets.filter(valid), min=values.length?Math.min(...values.map(b=>b.min)):null,max=values.length?Math.max(...values.map(b=>b.max)):null;
|
|
27
|
+
const ceiling=max===null?1:Math.max(1,max),segments=[];let points=[];
|
|
28
|
+
for(let i=0;i<buckets.length;i++) {
|
|
29
|
+
const b=buckets[i];if(!valid(b)){if(points.length)segments.push(points.join(' '));points=[];continue;}
|
|
30
|
+
points.push(`${(i*600/Math.max(1,buckets.length-1)).toFixed(2)},${(100-Math.min(100,b.average/ceiling*100)).toFixed(2)}`);
|
|
31
|
+
}
|
|
32
|
+
if(points.length)segments.push(points.join(' '));
|
|
33
|
+
const dots=segments.filter(s=>!s.includes(' ')).map(s=>{const [x,y]=s.split(',').map(Number);return{x,y};});
|
|
34
|
+
return {segments,dots,min,max,covered:values.length,total:buckets.length};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function sampleCoverage(snapshot,now=Date.now()) {
|
|
38
|
+
const volumes=storageRows(snapshot),missingBacking=snapshot?.platform==='wsl'&&!volumes.some(v=>v.roles.includes('wsl-backing'));
|
|
39
|
+
const cpu=metricState(snapshot?.cpu,30000,now)==='ok'&&numberOrNull(snapshot?.cpu?.value?.usedPercent,100)!==null;
|
|
40
|
+
const memory=metricState(snapshot?.memory,30000,now)==='ok'&&(numberOrNull(snapshot?.memory?.value?.availableBytes)!==null||['normal','elevated','critical'].includes(snapshot?.memory?.value?.pressure));
|
|
41
|
+
return {covered:Number(cpu)+Number(memory)+(metricState(snapshot?.disks,60000,now)==='ok'?volumes.filter(v=>numberOrNull(v.availableBytes)!==null).length:0),total:2+volumes.length+Number(missingBacking)};
|
|
42
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import {HostFootprintView,footprintText} from './host-footprint.js';
|
|
2
|
+
import {hostTime} from './host-time.js';
|
|
3
|
+
import {HostAlerts} from './host-alerts.js';
|
|
4
|
+
import {html,useEffect,useRef,useState} from '/assets/app-html.js';
|
|
5
|
+
import {register,t,lang} from '/assets/app-i18n.js';
|
|
6
|
+
import {PageHead} from '/assets/page-head.js';
|
|
7
|
+
import {Skeleton,ErrorState} from '/assets/ui-states.js';
|
|
8
|
+
import {Icon} from '/assets/ui-icons.js';
|
|
9
|
+
import {sectionPath} from '/assets/app-route.js';
|
|
10
|
+
import {HOST_RANGES,numberOrNull,metricState,displayBytes,storageRows,historySeries,chartData,sampleCoverage} from './host-health-model.js';
|
|
11
|
+
|
|
12
|
+
register('hostHealth',{
|
|
13
|
+
en:{title:'Host health',computer:'This computer',lead:'CPU, memory and storage from the latest recorded samples.',settings:'Monitoring settings',refresh:'Refresh',refreshing:'Refreshing…',unsupported:'Host monitoring is not available on this computer.',off:'Host monitoring is off',offHint:'Turn it on in Settings to collect samples and keep bounded local history.',admin:'Administrator sign-in required',adminHint:'Sign in as a Fleet administrator to see host metrics.',starting:'Waiting for the first samples',stopping:'Stopping monitoring',failedHint:'Monitoring could not complete. Check its settings and local storage permissions; history cleanup may still need attention.',failed:'Monitoring needs attention',unavailable:'Not available',stale:'Stale',lastLabel:'Last successful sample:',last:'Last successful sample: {0}',none:'No successful sample yet',wsl:'WSL 2',linux:'Linux',darwin:'macOS',wslNote:'CPU and memory describe WSL, not the physical Windows computer. The Windows backing drive is shown separately.',macNote:'APFS volumes may share free space. Do not add their free space together. Available memory is an estimate; pressure is shown separately.',linuxNote:'Local Linux filesystems and available memory. Unavailable fields are not treated as zero.',runtimeNote:'Paired Windows Runtimes are separate computers and are not included in these totals.',storage:'Storage',root:'Linux filesystem',state:'Fleet state',backing:'Windows backing drive',volume:'Local volume',drive:' ({0}:)',shared:'Shared APFS capacity',sharedHint:'Do not add free space across volumes.',free:'{0} available',used:'{0}% used',unknownDrive:'Windows drive not identified',chooseDrive:'Choose drive in Settings',unknownHint:'Linux free space alone does not show whether the Windows drive holding WSL has room.',cpu:'CPU',wslCpu:'WSL CPU',wslMemory:'WSL memory',cpuUsed:'{0}% used',cores:'{0} logical CPUs',loadLabel:'Load average:',load:'Load average: {0}',memory:'Memory',available:'{0} available of {1}',pressureLabel:'Memory pressure:',pressure:'Memory pressure: {0}',normal:'Normal',elevated:'Elevated',critical:'Critical',unknown:'Unknown',swap:'Swap free: {0}',history:'History',range:'History range',coverageSummary:'{0} of {1} readings have fresh data',collecting:'Collecting history…',noHistory:'No recorded samples in this range',historyUnavailable:'Recorded history is temporarily unavailable. Refresh to try again.',historyLoading:'Loading recorded history…',historyWaiting:'History has not started recording yet.',historyPaused:'History recording is paused.',historyFailed:'History could not be recorded. Current samples remain available.',lowSpace:'Low storage: keeping current samples in memory only.',recovering:'Waiting for both storage volumes to stay above 4 GiB for ten minutes.',diskUnavailable:'Storage data is unavailable; history is paused.',backingUnknown:'Identify the Windows backing drive before history can be recorded.',clockChanged:'The computer clock moved backwards; recording is waiting for it to catch up.',historyBusy:'History storage is busy; no additional write is queued.',minimum:'Minimum: {0}',maximum:'Peak: {0}',coverage:'{0} of {1} chart buckets contain recorded samples',gaps:'Gaps mean no sample was recorded; they are not zero.',retention:'History is capped at 64 MiB, with up to 24 hours of raw samples and 30 days of rollups. Older samples may be pruned earlier.',snapshotOnly:'Refresh reads saved snapshots. It does not start a new probe.',samples:'Host every 30 s · storage every 60 s',chart:'{0} history',usedHistory:'Storage used',freeHistory:'Available space trend',notMeasured:'Not measured'},
|
|
14
|
+
'zh-TW':{title:'主機狀態',computer:'這台電腦',lead:'依最新記錄的取樣查看 CPU、記憶體與儲存空間。',settings:'監測設定',refresh:'重新整理',refreshing:'重新整理中…',unsupported:'這台電腦尚未提供主機監測。',off:'主機監測已關閉',offHint:'請在設定中開啟,開始取樣並保留容量受限的本機歷史。',admin:'需要管理員登入',adminHint:'請以 Fleet 管理員身分登入,才能查看主機資料。',starting:'等待第一筆取樣',stopping:'正在停止監測',failedHint:'主機監測未能完成操作,請檢查設定與本機儲存空間權限;歷史資料可能仍需清理。',failed:'主機監測需要處理',unavailable:'無法取得',stale:'資料已過期',lastLabel:'最後成功取樣:',last:'最後成功取樣:{0}',none:'尚無成功的取樣',wsl:'WSL 2',linux:'Linux',darwin:'macOS',wslNote:'CPU 與記憶體代表 WSL,不是實體 Windows 電腦。存放 WSL 的 Windows 磁碟會另外列出。',macNote:'APFS 磁碟區可能共用空間,請勿把可用空間相加。可用記憶體是估算值,記憶體壓力會另外顯示。',linuxNote:'本機 Linux 檔案系統與可用記憶體。無法取得的欄位不會當作零。',runtimeNote:'配對的 Windows 電腦是另一台,不算在這裡的數字裡。',storage:'儲存空間',root:'Linux 檔案系統',state:'Fleet 狀態資料',backing:'存放 WSL 的 Windows 磁碟',volume:'本機磁碟區',drive:'({0}:)',shared:'共用 APFS 容量',sharedHint:'請勿把各磁碟區的可用空間相加。',free:'可用 {0}',used:'已使用 {0}%',unknownDrive:'尚未確認 Windows 磁碟',chooseDrive:'到設定選擇磁碟',unknownHint:'只有 Linux 的可用空間,無法判斷存放 WSL 的 Windows 磁碟是否還有空間。',cpu:'CPU',wslCpu:'WSL CPU',wslMemory:'WSL 記憶體',cpuUsed:'使用率 {0}%',cores:'{0} 個邏輯 CPU',loadLabel:'平均負載:',load:'平均負載:{0}',memory:'記憶體',available:'可用 {0},共 {1}',pressureLabel:'記憶體壓力:',pressure:'記憶體壓力:{0}',normal:'正常',elevated:'偏高',critical:'嚴重',unknown:'未知',swap:'Swap 可用:{0}',history:'歷史紀錄',range:'歷史期間',coverageSummary:'{1} 項讀數中,{0} 項有最新資料',collecting:'正在累積歷史紀錄…',noHistory:'這段期間尚無記錄的取樣',historyUnavailable:'暫時無法取得歷史紀錄,請重新整理再試。',historyLoading:'正在載入歷史紀錄…',historyWaiting:'歷史紀錄尚未開始取樣。',historyPaused:'歷史紀錄已暫停。',historyFailed:'無法記錄歷史,目前的取樣仍可查看。',lowSpace:'儲存空間不足:目前取樣只保留在記憶體中。',recovering:'等待兩個儲存空間持續十分鐘都超過 4 GiB。',diskUnavailable:'無法取得儲存空間資料,歷史紀錄已暫停。',backingUnknown:'請先確認存放 WSL 的 Windows 磁碟,再記錄歷史。',clockChanged:'電腦時間往回調整,正在等待時間追上後再記錄。',historyBusy:'歷史儲存空間忙碌中,不會排入額外的寫入。',minimum:'最低:{0}',maximum:'最高:{0}',coverage:'{1} 個圖表區間中,{0} 個有記錄取樣',gaps:'缺口代表沒有記錄取樣,不是零。',retention:'歷史資料最多 64 MiB;原始取樣最多保留 24 小時,彙整最多 30 天。較舊的取樣可能提早清除。',snapshotOnly:'重新整理只讀取已保存的取樣,不會啟動新的探測。',samples:'主機每 30 秒 · 儲存空間每 60 秒',chart:'{0} 歷史',usedHistory:'儲存空間使用率',freeHistory:'可用空間趨勢',notMeasured:'未量測'}
|
|
15
|
+
});
|
|
16
|
+
const text=(key,...values)=>t(`hostHealth.${key}`,...values);
|
|
17
|
+
const date=value=>numberOrNull(value)===null?text('none'):hostTime(value);
|
|
18
|
+
const sampleTime=value=>html`${text('lastLabel')}${lang()==='zh-TW'?'':' '}<span class="host-sample-time">${date(value)}</span>`;
|
|
19
|
+
const settingLink=()=>sectionPath('notifications')+'#host-monitoring';
|
|
20
|
+
const metricLabel=(metric,interval)=>metricState(metric,interval)==='ok'?null:text(metricState(metric,interval));
|
|
21
|
+
export function historyMessage(status){
|
|
22
|
+
const reason={low_space:'lowSpace',recovering_space:'recovering',disk_unavailable:'diskUnavailable',backing_drive_unknown:'backingUnknown',clock_changed:'clockChanged',history_busy:'historyBusy'}[status?.reason];
|
|
23
|
+
return text(reason||({waiting:'historyWaiting',paused:'historyPaused',failed:'historyFailed',stopping:'stopping'}[status?.state]||'historyWaiting'));
|
|
24
|
+
}
|
|
25
|
+
function HistoryChart({answer,id,label,unit='percent'}){
|
|
26
|
+
const model=chartData(answer?.series?.find(s=>s.id===id)?.buckets);
|
|
27
|
+
const value=n=>n===null?text('unavailable'):unit==='bytes'?displayBytes(n):unit==='pressure'?text(({1:'normal',2:'elevated',3:'critical'})[Math.round(n)]||'unknown'):`${n.toFixed(1)}%`;
|
|
28
|
+
return html`<figure class="host-chart"><figcaption>${label===text('freeHistory')?label:text('chart',label)}</figcaption>${model.covered>=4?html`<svg viewBox="0 0 600 110" role="img" aria-label=${`${label===text('freeHistory')?label:text('chart',label)}. ${text('minimum',value(model.min))}. ${text('maximum',value(model.max))}. ${text('coverage',model.covered,model.total)}`}><line x1="0" x2="600" y1="100" y2="100" />${model.segments.map((points,i)=>html`<polyline key=${i} points=${points} />`)}${model.dots.map((point,i)=>html`<circle key=${i} cx=${point.x} cy=${point.y} r="2.5"/>`)}</svg><p class="note">${text('minimum',value(model.min))} · ${text('maximum',value(model.max))}</p><p class="note">${text('coverage',model.covered,model.total)}</p>`:html`<p class="note host-no-history">${text(answer===undefined?'historyLoading':answer?.unavailable?'historyUnavailable':model.covered?'collecting':'noHistory')}</p>`}</figure>`;
|
|
29
|
+
}
|
|
30
|
+
function ValueState({metric,interval}){const state=metricLabel(metric,interval);return state?html`<span class="tag">${state}</span>`:null;}
|
|
31
|
+
function Storage({health,history}){
|
|
32
|
+
const rows=storageRows(health),state=metricState(health.disks,60000);
|
|
33
|
+
return html`<section class="card host-storage"><h3>${text('storage')}</h3>${health.platform==='wsl'&&health.disks?.value?.backingDrive!=='identified'?html`<div class="notice warn"><strong>${text('unknownDrive')}</strong><p>${text('unknownHint')}</p><a class="btn btn-sm" href=${settingLink()}>${text('chooseDrive')}</a></div>`:null}${!rows.length?html`<p class="note">${text('unavailable')}</p>`:rows.map(v=>{
|
|
34
|
+
const name=v.roles.includes('wsl-backing')?text('backing'):v.roles.filter(r=>r==='root'||r==='state').map(r=>text(r==='root'?(health.platform==='darwin'?'volume':'root'):'state')).join(' · ')||text('volume');
|
|
35
|
+
const known=state==='ok'&&numberOrNull(v.availableBytes)!==null;
|
|
36
|
+
return html`<article key=${v.id} class="host-volume"><div class="host-row"><h4>${name}${/^[A-Z]$/.test(v.drive||'')?html`<span class="note">${text('drive',v.drive)}</span>`:null}</h4>${state!=='ok'||!known?html`<span class="tag">${text(state==='stale'?'stale':'unavailable')}</span>`:null}</div><p class="host-value">${numberOrNull(v.availableBytes)!==null?text('free',displayBytes(v.availableBytes)):text('unavailable')}</p><p class="note">${numberOrNull(v.usedPercent,100)!==null?text('used',v.usedPercent.toFixed(1)):text('unavailable')} · ${sampleTime(v.sampledAt)}</p>${numberOrNull(v.usedPercent,100)===null?null:html`<progress class="host-space-meter" value=${v.usedPercent} max="100" aria-label=${text('used',v.usedPercent.toFixed(1))}></progress>`}${health.platform==='darwin'&&v.shared?html`<p class="note">${text('shared')} · ${text('sharedHint')}</p>`:null}<${HistoryChart} answer=${history} id=${`disk.${v.id}.available`} label=${text('freeHistory')} unit="bytes" /></article>`;
|
|
37
|
+
})}</section>`;
|
|
38
|
+
}
|
|
39
|
+
export function HostHealthView({health,history,busy,range,onRange,onRefresh,agentOffset=0,onAgentOffset,selectedAgent,onSelectedAgent}){
|
|
40
|
+
const at=[health?.cpu?.sampledAt,health?.memory?.sampledAt,health?.disks?.sampledAt].filter(v=>numberOrNull(v)!==null),last=at.length?Math.max(...at):null;
|
|
41
|
+
const cpu=health?.cpu?.value,memory=health?.memory?.value,coverage=sampleCoverage(health);
|
|
42
|
+
const populated=health?.enabled&&health?.platformSupported!==false,platform=text(['wsl','linux','darwin'].includes(health?.platform)?health.platform:'unavailable');
|
|
43
|
+
return html`<section class="host-health" aria-busy=${busy}><${PageHead} title=${text('title')} scope=${text('computer')+(populated?' · '+platform:'')} lead=${text('lead')} note=${html`${last===null?text('none'):sampleTime(last)}${populated?html` <span class="host-coverage">${text('coverageSummary',coverage.covered,coverage.total)}</span>`:''}`}><button type="button" class="btn btn-sm" disabled=${busy} onClick=${onRefresh}><${Icon} name="restart" size=${15}/>${text(busy?'refreshing':'refresh')}</button>${health?.platformSupported===false?null:html`<a class="btn btn-sm" href=${settingLink()}>${text('settings')}</a>`}</${PageHead}>
|
|
44
|
+
${!populated?html`<p class="note">${text('snapshotOnly')}</p>`:null}
|
|
45
|
+
${health?.platformSupported===false?html`<section class="card"><h3>${text('unsupported')}</h3></section>`:!health?.enabled?html`<section class="card host-off"><h3>${text(health?.state==='failed'?'failed':health?.state==='stopping'?'stopping':'off')}</h3><p>${text(health?.state==='failed'?'failedHint':health?.state==='stopping'?'stopping':'offHint')}</p><a class="btn btn-primary" href=${settingLink()}>${text('settings')}</a></section>`:html`
|
|
46
|
+
${health.state!=='sampling'?html`<div class="notice" role="status">${text(({starting:'starting',stopping:'stopping',failed:'failed'})[health.state]||'unavailable')}</div>`:null}
|
|
47
|
+
${health.history?.state!=='recording'?html`<p class="notice" role="status">${historyMessage(health.history)}</p>`:null}
|
|
48
|
+
<${HostAlerts} alerts=${health.alerts} onChange=${onRefresh}/>
|
|
49
|
+
<div class="host-range" role="group" aria-label=${text('range')}>${HOST_RANGES.map(r=>html`<button type="button" class=${`btn btn-sm${range===r?' active':''}`} aria-pressed=${range===r} onClick=${()=>onRange(r)}>${r}</button>`)}</div>
|
|
50
|
+
<div class="host-grid"><div class="host-compute"><section class="card"><div class="host-row"><h3>${text(health.platform==='wsl'?'wslCpu':'cpu')}</h3><${ValueState} metric=${health.cpu} interval=${30000}/></div><p class="host-value">${numberOrNull(cpu?.usedPercent,100)===null?text('unavailable'):text('cpuUsed',cpu.usedPercent.toFixed(1))}</p><p class="note">${numberOrNull(cpu?.logicalCpus)!==null?text('cores',cpu.logicalCpus):text('unavailable')}</p>${Array.isArray(cpu?.loadAverage)?html`<p class="note">${text('loadLabel')}${lang()==='zh-TW'?'':' '}<span class="host-load-value">${cpu.loadAverage.slice(0,3).map(n=>numberOrNull(n)===null?'—':n.toFixed(2)).join(' / ')}</span></p>`:null}<p class="note">${sampleTime(health.cpu?.sampledAt)}</p><${HistoryChart} answer=${history} id="cpu.used" label=${text('cpu')}/></section>
|
|
51
|
+
<section class="card"><div class="host-row"><h3>${text(health.platform==='wsl'?'wslMemory':'memory')}</h3><${ValueState} metric=${health.memory} interval=${30000}/></div><p class="host-value">${text('pressureLabel')}${lang()==='zh-TW'?'':' '}<span class="host-pressure-value">${text(metricState(health.memory,30000)==='ok'&&['normal','elevated','critical'].includes(memory?.pressure)?memory.pressure:'unknown')}</span></p><p class="note">${numberOrNull(memory?.availableBytes)===null?text('unavailable'):text('available',displayBytes(memory.availableBytes),displayBytes(memory.totalBytes)||text('unavailable'))}</p><p class="note">${text('swap',displayBytes(memory?.swapFreeBytes)||text('unavailable'))}</p><p class="note">${sampleTime(health.memory?.sampledAt)}</p><${HistoryChart} answer=${history} id="memory.available" label=${text('memory')} unit="bytes" /></section></div>
|
|
52
|
+
<${Storage} health=${health} history=${history}/></div><p class="note">${text(health.platform==='wsl'?'wslNote':health.platform==='darwin'?'macNote':'linuxNote')}</p><p class="note">${text('samples')} · ${text('snapshotOnly')}</p><p class="note">${text('runtimeNote')}</p><p class="note">${text('gaps')}</p><p class="note">${text('retention')}</p><${HostFootprintView} snapshot=${health.footprint} offset=${agentOffset} onOffset=${onAgentOffset} onSelect=${onSelectedAgent} selected=${selectedAgent} charts=${selectedAgent&&health.footprint?.enabled?html`<${HistoryChart} answer=${history} id=${`agent.${selectedAgent}.cpu`} label=${footprintText('agentCpu')}/><${HistoryChart} answer=${history} id=${`agent.${selectedAgent}.rss`} label=${footprintText('agentMemory')} unit="bytes"/>`:null}/>`}
|
|
53
|
+
</section>`;
|
|
54
|
+
}
|
|
55
|
+
export function HostHealth({lease}){
|
|
56
|
+
const [agentOffset,setAgentOffset]=useState(0),[selectedAgent,setSelectedAgent]=useState(null);
|
|
57
|
+
const [data,setData]=useState(null),[history,setHistory]=useState(null),[range,setRange]=useState('1h'),[busy,setBusy]=useState(false),[error,setReadState]=useState(null),seq=useRef(0),inflight=useRef(false),pending=useRef(false),latest=useRef(null),alive=useRef(true);
|
|
58
|
+
const load=async()=>{
|
|
59
|
+
if(!alive.current||!lease.current())return;if(inflight.current){pending.current=true;return;}inflight.current=true;const mine=++seq.current;setBusy(true);
|
|
60
|
+
try{
|
|
61
|
+
const response=await lease.fetch('/ui/host-health'+(agentOffset?'?agentOffset='+agentOffset:''),{cache:'no-store'});if(!alive.current||!lease.current()||mine!==seq.current)return;
|
|
62
|
+
if(response.status===401||response.status===403){setData(null);setHistory(null);setReadState('admin');return;}if(!response.ok)throw Error('read failed');
|
|
63
|
+
const health=await response.json();if(!alive.current||!lease.current()||mine!==seq.current)return;setData(health);setReadState(null);
|
|
64
|
+
if(!health.enabled||health.history?.state!=='recording'){setHistory(null);return;}
|
|
65
|
+
const params=new URLSearchParams({range});for(const id of [...historySeries(health),...(selectedAgent?[`agent.${selectedAgent}.cpu`,`agent.${selectedAgent}.rss`]:[])])params.append('series',id);
|
|
66
|
+
const r=await lease.fetch('/ui/host-history?'+params,{cache:'no-store'});if(!alive.current||!lease.current()||mine!==seq.current)return;
|
|
67
|
+
if(r.status===401||r.status===403){setData(null);setHistory(null);setReadState('admin');return;}
|
|
68
|
+
const result=r.ok?await r.json():null;if(alive.current&&lease.current()&&mine===seq.current)setHistory({range,value:result?.ok?result.value:{unavailable:true}});
|
|
69
|
+
}catch{if(alive.current&&lease.current()&&mine===seq.current)setReadState('load');}finally{inflight.current=false;if(alive.current&&lease.current()&&mine===seq.current)setBusy(false);if(pending.current){pending.current=false;void latest.current?.();}}
|
|
70
|
+
};
|
|
71
|
+
latest.current=load;
|
|
72
|
+
useEffect(()=>{alive.current=true;return()=>{alive.current=false;seq.current++;};},[lease]);
|
|
73
|
+
useEffect(()=>{seq.current++;void load();},[lease,range,agentOffset,selectedAgent]);
|
|
74
|
+
// Only an enabled visible page refreshes its cache. Off/unmounted pages own no monitoring poll.
|
|
75
|
+
useEffect(()=>{if(!data?.enabled)return;const timer=lease.interval(()=>{if(typeof document==='undefined'||!document.hidden)void latest.current?.();},30000);return()=>lease.clear(timer);},[lease,data?.enabled,range]);
|
|
76
|
+
if(error==='admin')return html`<section class="card"><h2>${text('admin')}</h2><p>${text('adminHint')}</p></section>`;
|
|
77
|
+
if(!data)return error?html`<${ErrorState} onRetry=${load}/>`:html`<${Skeleton} lines=${5}/>`;
|
|
78
|
+
return html`<div>${error?html`<${ErrorState} onRetry=${load}/>`:null}<${HostHealthView} health=${data} history=${history?.range===range?history.value:busy?undefined:null} agentOffset=${agentOffset} onAgentOffset=${value=>{setAgentOffset(value);setSelectedAgent(null);}} selectedAgent=${selectedAgent} onSelectedAgent=${setSelectedAgent} range=${range} onRange=${setRange} onRefresh=${load} busy=${busy}/></div>`;
|
|
79
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import {lang} from '/assets/app-i18n.js';
|
|
2
|
+
/** Shared compact host timestamp: one local 24-hour format on cards and incident updates. */
|
|
3
|
+
export function hostTime(value){
|
|
4
|
+
return new Date(value).toLocaleString(lang()==='zh-TW'?'zh-TW':'en-GB',{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit',second:'2-digit',hour12:false});
|
|
5
|
+
}
|