paseo-office 0.2.4 → 0.2.6

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.
@@ -0,0 +1,446 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { StyleSheet, Text, View, type ViewStyle } from "react-native";
3
+ import { Icon } from "@getpaseo/plugin/client/ui";
4
+ import { useRpc } from "@getpaseo/plugin/client";
5
+ import { timelineRpc } from "../shared/contracts.js";
6
+ import {
7
+ DAY_MS,
8
+ REPLAY_SPEEDS,
9
+ TIMELINE_RANGES,
10
+ doingAt,
11
+ durationText,
12
+ weekRecap,
13
+ type ReplaySpeed,
14
+ type Timeline,
15
+ type TimelineLane,
16
+ type TimelineRange,
17
+ type TimelineState,
18
+ } from "../shared/timeline.js";
19
+ import { ActionButton } from "./action-button.js";
20
+ import { OfficeModal as Modal } from "./office-modal.js";
21
+ import { SegmentPill } from "./segment-pill.js";
22
+ import type { OfficeStyles } from "./styles.js";
23
+
24
+ type Tab = TimelineRange | "week";
25
+ const WEEK_MS = 7 * DAY_MS;
26
+ /** A replay's head moves this often; each move is this long times the speed. */
27
+ const TICK_MS = 100;
28
+ /** While nothing is replayed the lanes are read again this often. */
29
+ const REFRESH_MS = 30_000;
30
+
31
+ const layout = StyleSheet.create({
32
+ lanes: { gap: 10 },
33
+ lane: { gap: 4 },
34
+ laneHead: { flexDirection: "row", justifyContent: "space-between", gap: 8 },
35
+ laneName: { flexShrink: 1 },
36
+ track: { height: 14, borderRadius: 4, overflow: "hidden" },
37
+ piece: { position: "absolute", top: 0, bottom: 0 },
38
+ step: { position: "absolute", top: 0, bottom: 0, width: 1, opacity: 0.55 },
39
+ head: { position: "absolute", top: 0, bottom: 0, width: 2 },
40
+ controls: { flexDirection: "row", flexWrap: "wrap", alignItems: "center", gap: 8 },
41
+ figures: { flexDirection: "row", flexWrap: "wrap", gap: 12 },
42
+ figure: { flexBasis: 120, flexGrow: 1, gap: 2 },
43
+ bars: { flexDirection: "row", alignItems: "flex-end", gap: 6, height: 72 },
44
+ barColumn: { flex: 1, alignItems: "center", justifyContent: "flex-end", gap: 4, height: "100%" },
45
+ bar: { width: "100%", borderRadius: 3, minHeight: 2 },
46
+ });
47
+
48
+ function clockText(at: number): string {
49
+ const date = new Date(at);
50
+ const pad = (value: number) => String(value).padStart(2, "0");
51
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
52
+ }
53
+
54
+ const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
55
+
56
+ function stateColor(styles: OfficeStyles, state: TimelineState): string {
57
+ const dot = { work: "running", wait: "warning", fail: "danger", rest: "idle" } as const;
58
+ return String(styles.dot[dot[state]].backgroundColor);
59
+ }
60
+
61
+ interface LaneProps {
62
+ lane: TimelineLane;
63
+ from: number;
64
+ to: number;
65
+ /** Where the replay is; null while nothing is replayed. */
66
+ head: number | null;
67
+ styles: OfficeStyles;
68
+ }
69
+
70
+ function Lane({ lane, from, to, head, styles }: LaneProps) {
71
+ const width = to - from;
72
+ const pieces = useMemo(() => {
73
+ const percent = (at: number) => `${((at - from) / width) * 100}%` as const;
74
+ return {
75
+ spans: lane.spans.map((span) => ({
76
+ key: `${span.from}`,
77
+ style: [
78
+ layout.piece,
79
+ {
80
+ left: percent(span.from),
81
+ width: percent(from + (span.to - span.from)),
82
+ backgroundColor: stateColor(styles, span.state),
83
+ opacity: span.state === "rest" ? 0.3 : 1,
84
+ } satisfies ViewStyle,
85
+ ],
86
+ })),
87
+ steps: lane.steps.map((step, index) => ({
88
+ key: `${step.at}:${index}`,
89
+ style: [
90
+ layout.step,
91
+ { left: percent(step.at), backgroundColor: String(styles.host.name.color) },
92
+ ],
93
+ })),
94
+ };
95
+ }, [lane, from, width, styles]);
96
+ const headStyle = useMemo(
97
+ () =>
98
+ head === null
99
+ ? null
100
+ : [
101
+ layout.head,
102
+ {
103
+ left: `${((head - from) / width) * 100}%` as const,
104
+ backgroundColor: String(styles.host.name.color),
105
+ },
106
+ ],
107
+ [head, from, width, styles],
108
+ );
109
+ const doing = doingAt(lane, head ?? to - 1);
110
+ const track = useMemo(() => [styles.host.track, layout.track], [styles]);
111
+ const name = useMemo(() => [styles.host.name, layout.laneName], [styles]);
112
+ return (
113
+ <View
114
+ accessible
115
+ accessibilityRole="text"
116
+ accessibilityLabel={`${lane.name}, ${lane.team}: ${doing}`}
117
+ style={layout.lane}
118
+ >
119
+ <View style={layout.laneHead}>
120
+ <Text style={name} numberOfLines={1}>
121
+ {lane.name}
122
+ </Text>
123
+ <Text style={styles.host.note} numberOfLines={1}>
124
+ {lane.team} · {doing}
125
+ </Text>
126
+ </View>
127
+ <View style={track}>
128
+ {pieces.spans.map((piece) => (
129
+ <View key={piece.key} style={piece.style} />
130
+ ))}
131
+ {pieces.steps.map((piece) => (
132
+ <View key={piece.key} style={piece.style} />
133
+ ))}
134
+ {headStyle && <View style={headStyle} />}
135
+ </View>
136
+ </View>
137
+ );
138
+ }
139
+
140
+ function Figure({ label, value, styles }: { label: string; value: string; styles: OfficeStyles }) {
141
+ return (
142
+ <View accessible accessibilityLabel={`${label}: ${value}`} style={layout.figure}>
143
+ <Text style={styles.host.title}>{value}</Text>
144
+ <Text style={styles.host.note}>{label}</Text>
145
+ </View>
146
+ );
147
+ }
148
+
149
+ function Week({ timeline, styles }: { timeline: Timeline; styles: OfficeStyles }) {
150
+ const recap = useMemo(() => weekRecap(timeline), [timeline]);
151
+ const most = Math.max(1, ...recap.days.map((day) => day.workMs));
152
+ const bars = useMemo(
153
+ () =>
154
+ recap.days.map((day) => ({
155
+ key: String(day.from),
156
+ // The day a bar's 24 hours end in: the last one is today.
157
+ label: WEEKDAYS[new Date(day.from + DAY_MS - 1).getDay()],
158
+ text: durationText(day.workMs),
159
+ style: [
160
+ layout.bar,
161
+ {
162
+ height: `${(day.workMs / most) * 100}%` as const,
163
+ backgroundColor: stateColor(styles, "work"),
164
+ opacity: day.workMs === 0 ? 0.25 : 1,
165
+ },
166
+ ],
167
+ })),
168
+ [recap.days, most, styles],
169
+ );
170
+ if (recap.workMs === 0) {
171
+ return (
172
+ <Text style={styles.host.empty}>
173
+ Nobody was seen at work in the last seven days. The office sees only while it is open.
174
+ </Text>
175
+ );
176
+ }
177
+ return (
178
+ <View style={styles.host.body}>
179
+ <View style={layout.figures}>
180
+ <Figure label="At work" value={durationText(recap.workMs)} styles={styles} />
181
+ <Figure label="Turns" value={String(recap.prompts)} styles={styles} />
182
+ <Figure label="Edits" value={String(recap.edits)} styles={styles} />
183
+ <Figure label="Commands" value={String(recap.commands)} styles={styles} />
184
+ <Figure
185
+ label="Cost"
186
+ value={recap.costUsd === null ? "Not reported" : `$${recap.costUsd.toFixed(2)}`}
187
+ styles={styles}
188
+ />
189
+ <Figure label="Busiest team" value={recap.busiestTeam ?? "None"} styles={styles} />
190
+ </View>
191
+ <View style={layout.bars}>
192
+ {bars.map((bar) => (
193
+ <View
194
+ key={bar.key}
195
+ accessible
196
+ accessibilityLabel={`${bar.label}: ${bar.text} at work`}
197
+ style={layout.barColumn}
198
+ >
199
+ <View style={bar.style} />
200
+ <Text style={styles.host.note}>{bar.label}</Text>
201
+ </View>
202
+ ))}
203
+ </View>
204
+ <Text style={styles.host.note}>
205
+ Counted from what the office saw while it was open, in the 24 hours each bar ends.
206
+ </Text>
207
+ </View>
208
+ );
209
+ }
210
+
211
+ interface Replay {
212
+ head: number;
213
+ playing: boolean;
214
+ }
215
+
216
+ /** A replay's head, moved while it plays; it stops at the end. */
217
+ function useReplay(timeline: Timeline | null, speed: ReplaySpeed) {
218
+ const [replay, setReplay] = useState<Replay | null>(null);
219
+ const end = timeline?.to ?? 0;
220
+ const playing = replay?.playing ?? false;
221
+ useEffect(() => {
222
+ if (!playing) return undefined;
223
+ const timer = setInterval(() => {
224
+ setReplay((now) => {
225
+ if (now === null || !now.playing) return now;
226
+ const head = now.head + TICK_MS * speed;
227
+ return head >= end ? { head: end, playing: false } : { head, playing: true };
228
+ });
229
+ }, TICK_MS);
230
+ return () => clearInterval(timer);
231
+ }, [playing, speed, end]);
232
+ const toggle = useCallback(() => {
233
+ if (timeline === null) return;
234
+ setReplay((now) => {
235
+ // From the start when there is none, and again when the last one reached the end.
236
+ if (now === null || now.head >= timeline.to) return { head: timeline.from, playing: true };
237
+ return { head: now.head, playing: !now.playing };
238
+ });
239
+ }, [timeline]);
240
+ const stop = useCallback(() => setReplay(null), []);
241
+ return { replay, toggle, stop };
242
+ }
243
+
244
+ interface LanesProps {
245
+ timeline: Timeline;
246
+ replay: Replay | null;
247
+ speed: ReplaySpeed;
248
+ onSpeed(next: ReplaySpeed): void;
249
+ onToggle(): void;
250
+ onStop(): void;
251
+ styles: OfficeStyles;
252
+ }
253
+
254
+ /** The replay's controls over a lane per agent. */
255
+ function Lanes({ timeline, replay, speed, onSpeed, onToggle, onStop, styles }: LanesProps) {
256
+ let playLabel = "Replay";
257
+ if (replay?.playing) playLabel = "Pause";
258
+ else if (replay !== null && replay.head < timeline.to) playLabel = "Resume";
259
+ return (
260
+ <>
261
+ <View style={layout.controls}>
262
+ <ActionButton
263
+ label={playLabel}
264
+ pendingLabel={playLabel}
265
+ onPress={onToggle}
266
+ disabled={timeline.lanes.length === 0}
267
+ styles={styles}
268
+ primary
269
+ />
270
+ {replay !== null && (
271
+ <ActionButton label="Now" pendingLabel="Now" onPress={onStop} styles={styles} />
272
+ )}
273
+ <View role="group" aria-label="Replay speed" style={styles.segments}>
274
+ {REPLAY_SPEEDS.map((value) => (
275
+ <SegmentPill
276
+ key={value}
277
+ value={value}
278
+ name={`${value} times the clock`}
279
+ text={`${value}×`}
280
+ on={speed === value}
281
+ disabled={false}
282
+ onPress={onSpeed}
283
+ styles={styles}
284
+ />
285
+ ))}
286
+ </View>
287
+ <Text accessibilityLiveRegion="none" style={styles.machineValue}>
288
+ {clockText(replay?.head ?? timeline.to)}
289
+ </Text>
290
+ </View>
291
+ {timeline.lanes.length === 0 ? (
292
+ <Text style={styles.host.empty}>
293
+ Nobody was seen in this time. The office sees only while it is open.
294
+ </Text>
295
+ ) : (
296
+ <View style={layout.lanes}>
297
+ {timeline.lanes.map((lane) => (
298
+ <Lane
299
+ key={lane.id}
300
+ lane={lane}
301
+ from={timeline.from}
302
+ to={timeline.to}
303
+ head={replay?.head ?? null}
304
+ styles={styles}
305
+ />
306
+ ))}
307
+ </View>
308
+ )}
309
+ <Text style={styles.host.note}>
310
+ Green is at work, amber waiting for you, red stopped on an error, grey resting. A gap is a
311
+ time the office was closed. The marks are tool calls.
312
+ </Text>
313
+ </>
314
+ );
315
+ }
316
+
317
+ interface Read {
318
+ timeline: Timeline | null;
319
+ problem: string | null;
320
+ }
321
+
322
+ /** The lanes of the last `ms`, read when the card shows and again while `fresh`. */
323
+ function useTimeline(open: boolean, ms: number, fresh: boolean): Read {
324
+ const ask = useRpc(timelineRpc);
325
+ // Kept in a ref: the read restarts with the range, not with the call's identity.
326
+ const asking = useRef(ask);
327
+ asking.current = ask;
328
+ const [read, setRead] = useState<Read & { ms: number }>({ timeline: null, problem: null, ms });
329
+ useEffect(() => {
330
+ if (!open) return undefined;
331
+ let ended = false;
332
+ const load = async () => {
333
+ const to = Date.now();
334
+ try {
335
+ const answer = await asking.current({ from: to - ms, to });
336
+ if (ended) return;
337
+ setRead(
338
+ answer.ok
339
+ ? { timeline: answer.timeline, problem: null, ms }
340
+ : { timeline: null, problem: answer.problem, ms },
341
+ );
342
+ } catch (error) {
343
+ const problem = error instanceof Error ? error.message : String(error);
344
+ if (!ended) setRead({ timeline: null, problem, ms });
345
+ }
346
+ };
347
+ void load();
348
+ const timer = fresh ? setInterval(() => void load(), REFRESH_MS) : null;
349
+ return () => {
350
+ ended = true;
351
+ if (timer !== null) clearInterval(timer);
352
+ };
353
+ }, [open, ms, fresh]);
354
+ // Another range's lanes are not shown under this one's pills.
355
+ return read.ms === ms ? read : { timeline: null, problem: null };
356
+ }
357
+
358
+ export interface TimelineCardProps {
359
+ open: boolean;
360
+ styles: OfficeStyles;
361
+ onClose(): void;
362
+ }
363
+
364
+ /**
365
+ * What each agent was at over the last hours, a lane each, replayed at up to 120 times the
366
+ * clock; and the week in figures. It shows what the office saw while it was open.
367
+ */
368
+ export function TimelineCard({ open, styles, onClose }: TimelineCardProps) {
369
+ const [tab, setTab] = useState<Tab>("1h");
370
+ const [speed, setSpeed] = useState<ReplaySpeed>(60);
371
+ const ms = tab === "week" ? WEEK_MS : (TIMELINE_RANGES.find((r) => r.id === tab)?.ms ?? 0);
372
+ const [replaying, setReplaying] = useState(false);
373
+ const { timeline, problem } = useTimeline(open, ms, !replaying);
374
+ const { replay, toggle, stop } = useReplay(tab === "week" ? null : timeline, speed);
375
+ useEffect(() => setReplaying(replay !== null), [replay]);
376
+ const choose = useCallback(
377
+ (next: Tab) => {
378
+ stop();
379
+ setTab(next);
380
+ },
381
+ [stop],
382
+ );
383
+ const change = useCallback(
384
+ (next: boolean) => {
385
+ if (next) return;
386
+ stop();
387
+ onClose();
388
+ },
389
+ [onClose, stop],
390
+ );
391
+ const icon = useMemo(
392
+ () => <Icon name="History" size={18} color={String(styles.host.label.color)} />,
393
+ [styles],
394
+ );
395
+ return (
396
+ <Modal icon={icon} title="Timeline" open={open} onOpenChange={change}>
397
+ <Modal.Content>
398
+ {open && (
399
+ <View style={styles.host.body}>
400
+ <View role="group" aria-label="Range" style={styles.segments}>
401
+ {TIMELINE_RANGES.map((range) => (
402
+ <SegmentPill
403
+ key={range.id}
404
+ value={range.id}
405
+ name={range.label}
406
+ on={tab === range.id}
407
+ disabled={false}
408
+ onPress={choose}
409
+ styles={styles}
410
+ />
411
+ ))}
412
+ <SegmentPill
413
+ value="week"
414
+ name="This week"
415
+ on={tab === "week"}
416
+ disabled={false}
417
+ onPress={choose}
418
+ styles={styles}
419
+ />
420
+ </View>
421
+ {problem && (
422
+ <Text accessibilityRole="alert" style={styles.actionError}>
423
+ The timeline cannot be read: {problem}
424
+ </Text>
425
+ )}
426
+ {timeline === null && problem === null && (
427
+ <Text style={styles.host.empty}>Reading the timeline...</Text>
428
+ )}
429
+ {timeline !== null && tab === "week" && <Week timeline={timeline} styles={styles} />}
430
+ {timeline !== null && tab !== "week" && (
431
+ <Lanes
432
+ timeline={timeline}
433
+ replay={replay}
434
+ speed={speed}
435
+ onSpeed={setSpeed}
436
+ onToggle={toggle}
437
+ onStop={stop}
438
+ styles={styles}
439
+ />
440
+ )}
441
+ </View>
442
+ )}
443
+ </Modal.Content>
444
+ </Modal>
445
+ );
446
+ }
@@ -0,0 +1,7 @@
1
+ import { createContext } from "react";
2
+
3
+ /** Opens the Timeline card; absent while the office's data is not live. */
4
+ export const OpenTimelineContext = createContext<(() => void) | undefined>(undefined);
5
+
6
+ /** Opens the History card; absent while the office's data is not live. */
7
+ export const OpenHistoryContext = createContext<(() => void) | undefined>(undefined);