@koinzhang/paseo-plugin-activity 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +78 -1
  2. package/README.md +15 -8
  3. package/client/activity-heatmap.tsx +126 -93
  4. package/client/agent-creations.tsx +216 -0
  5. package/client/attention-pill.tsx +16 -5
  6. package/client/attention-popover.tsx +19 -23
  7. package/client/color-mix.test.ts +27 -0
  8. package/client/color-mix.ts +38 -0
  9. package/client/design-tokens.test.ts +39 -0
  10. package/client/design-tokens.ts +168 -0
  11. package/client/fit-text.test.ts +41 -0
  12. package/client/fit-text.ts +33 -0
  13. package/client/formatted-time.tsx +4 -4
  14. package/client/global-surface.tsx +316 -275
  15. package/client/header-button.ts +136 -0
  16. package/client/hourly-activity-timeline.tsx +425 -0
  17. package/client/measured-width.ts +72 -0
  18. package/client/panel-visibility.test.ts +25 -0
  19. package/client/panel-visibility.ts +45 -0
  20. package/client/panel.tsx +83 -108
  21. package/client/provider-dropdown.tsx +131 -0
  22. package/client/provider-filter.test.ts +17 -13
  23. package/client/provider-filter.ts +5 -7
  24. package/client/range.test.ts +44 -0
  25. package/client/range.ts +14 -0
  26. package/client/rank-color.test.ts +108 -14
  27. package/client/rank-color.ts +261 -48
  28. package/client/ranking-bars.tsx +291 -0
  29. package/client/ui.tsx +339 -0
  30. package/client/usage-popover.tsx +62 -134
  31. package/client/usage-stats.tsx +137 -8
  32. package/client/use-agent-turn-end.ts +2 -1
  33. package/client/use-app-language.ts +17 -0
  34. package/client/web.ts +73 -18
  35. package/client/workspace/agent-row.tsx +18 -25
  36. package/client/workspace/agents-section.tsx +23 -20
  37. package/client/workspace/constants.ts +6 -6
  38. package/client/workspace/display-menu.tsx +5 -4
  39. package/client/workspace/filters.test.ts +1 -1
  40. package/client/workspace/filters.ts +4 -2
  41. package/client/workspace/panel.tsx +176 -104
  42. package/client/workspace/rank-section.tsx +157 -44
  43. package/client/workspace/terminals-section.tsx +13 -9
  44. package/index.client.tsx +40 -20
  45. package/index.server.ts +63 -31
  46. package/package.json +2 -2
  47. package/paseo-plugin.json +2 -1
  48. package/server/agents.ts +20 -2
  49. package/server/background-sync.test.ts +43 -0
  50. package/server/background-sync.ts +43 -4
  51. package/server/handlers-query.test.ts +252 -1
  52. package/server/handlers.ts +174 -13
  53. package/server/ingest.test.ts +8 -0
  54. package/server/messages.test.ts +96 -1
  55. package/server/prompt-dedupe.ts +52 -0
  56. package/server/rpc-cache.test.ts +74 -0
  57. package/server/rpc-cache.ts +48 -0
  58. package/server/store.test.ts +122 -0
  59. package/server/store.ts +313 -19
  60. package/server/ttl-cache.ts +3 -0
  61. package/shared/activity.test.ts +159 -6
  62. package/shared/activity.ts +140 -5
  63. package/shared/classify.test.ts +1 -0
  64. package/shared/classify.ts +4 -1
  65. package/shared/explorer-agent-display.test.ts +61 -0
  66. package/shared/explorer-agent-display.ts +21 -2
  67. package/shared/format.test.ts +28 -3
  68. package/shared/format.ts +25 -2
  69. package/shared/i18n.test.ts +34 -0
  70. package/shared/i18n.ts +363 -0
  71. package/shared/insights.test.ts +162 -80
  72. package/shared/insights.ts +136 -61
  73. package/shared/usage.test.ts +330 -0
  74. package/shared/usage.ts +471 -0
@@ -0,0 +1,136 @@
1
+ import type { PluginButtonRegistration, PluginClientContext } from "@getpaseo/plugin/client";
2
+ import { messagesFor } from "../shared/i18n.ts";
3
+ import { isPanelMounted, watchPanelPresence } from "./panel-visibility.ts";
4
+ import { currentAppLanguage, watchAppLanguage } from "./use-app-language.ts";
5
+
6
+ type WorkspacesApi = PluginClientContext["paseo"]["workspaces"];
7
+ type ListResult = Awaited<ReturnType<WorkspacesApi["list"]>>;
8
+
9
+ const BUTTON_ID = "workspace-activity";
10
+ const PANEL_ID = "workspace-activity";
11
+ const PAGE_LIMIT = 200;
12
+
13
+ const buttonTitle = () => messagesFor(currentAppLanguage()).commands.workspaceActivity;
14
+
15
+ /** One header button per workspace, following an entry-owned workspace directory subscription. */
16
+ export function contributeHeaderButtons(
17
+ client: PluginClientContext,
18
+ intervalMs = 15_000,
19
+ ): () => void {
20
+ const workspaces = client.paseo.workspaces;
21
+ const buttons = new Map<string, PluginButtonRegistration>();
22
+ const report = (error: unknown) => console.error("[activity] workspace directory failed", error);
23
+ let disposed = false;
24
+ let connecting = false;
25
+ let generation = 0;
26
+ let release: (() => Promise<void>) | undefined;
27
+
28
+ function add(workspaceId: string) {
29
+ if (disposed || buttons.has(workspaceId)) return;
30
+ buttons.set(workspaceId, client.addHeaderButton({
31
+ id: BUTTON_ID,
32
+ workspaceId,
33
+ button: {
34
+ title: buttonTitle(),
35
+ icon: "Activity",
36
+ visible: !isPanelMounted(workspaceId),
37
+ behavior: {
38
+ kind: "action",
39
+ onPress() {
40
+ client.openPanel(PANEL_ID, { workspaceId, location: "explorer" });
41
+ },
42
+ },
43
+ },
44
+ }));
45
+ }
46
+
47
+ function remove(workspaceId: string) {
48
+ buttons.get(workspaceId)?.remove();
49
+ buttons.delete(workspaceId);
50
+ }
51
+
52
+ async function read(first?: ListResult) {
53
+ const run = ++generation;
54
+ try {
55
+ const ids = new Set<string>();
56
+ let page = first ?? await workspaces.list({ page: { limit: PAGE_LIMIT } });
57
+ for (let pages = 0; ; pages++) {
58
+ if (disposed || run !== generation) return;
59
+ for (const workspace of page.entries) ids.add(workspace.id);
60
+ if (!page.pageInfo.hasMore) break;
61
+ if (!page.pageInfo.nextCursor || pages >= 99) throw new Error("Incomplete workspace pagination");
62
+ page = await workspaces.list({ page: { limit: PAGE_LIMIT, cursor: page.pageInfo.nextCursor } });
63
+ }
64
+ for (const id of [...buttons.keys()]) if (!ids.has(id)) remove(id);
65
+ for (const id of ids) add(id);
66
+ } catch (error) {
67
+ if (!disposed && run === generation) report(error);
68
+ }
69
+ }
70
+
71
+ async function connect() {
72
+ if (disposed || connecting || release) return;
73
+ connecting = true;
74
+ try {
75
+ const result = await workspaces.list({ page: { limit: PAGE_LIMIT }, subscribe: {} });
76
+ if (disposed) {
77
+ await result.subscription.release();
78
+ return;
79
+ }
80
+ release = () => result.subscription.release();
81
+ result.subscription.subscribe({
82
+ // Called immediately and again after reconnect.
83
+ snapshot: (page) => { void read(page); },
84
+ update: (message) => {
85
+ if (disposed || message.type !== "workspace_update") return;
86
+ const update = message.payload;
87
+ if (update.kind === "upsert") add(update.workspace.id);
88
+ else remove(update.id);
89
+ },
90
+ error: (error) => {
91
+ if (disposed) return;
92
+ report(error);
93
+ const stop = release;
94
+ release = undefined;
95
+ if (stop) void stop().catch(report);
96
+ void read();
97
+ },
98
+ });
99
+ } catch (error) {
100
+ if (!disposed) {
101
+ report(error);
102
+ await read();
103
+ }
104
+ } finally {
105
+ connecting = false;
106
+ }
107
+ }
108
+
109
+ const timer = setInterval(() => {
110
+ if (!release) void connect();
111
+ else void read();
112
+ }, intervalMs);
113
+ void connect();
114
+
115
+ const stopLanguage = watchAppLanguage(() => {
116
+ const title = buttonTitle();
117
+ for (const button of buttons.values()) button.update({ title });
118
+ });
119
+
120
+ const stopPresence = watchPanelPresence((workspaceId) => {
121
+ buttons.get(workspaceId)?.update({ visible: !isPanelMounted(workspaceId) });
122
+ });
123
+
124
+ return () => {
125
+ disposed = true;
126
+ ++generation;
127
+ clearInterval(timer);
128
+ stopLanguage();
129
+ stopPresence();
130
+ const stop = release;
131
+ release = undefined;
132
+ if (stop) void stop().catch(report);
133
+ buttons.forEach((button) => button.remove());
134
+ buttons.clear();
135
+ };
136
+ }
@@ -0,0 +1,425 @@
1
+ import { useEffect, useMemo, useRef, useState } from "react";
2
+ import { Animated, Easing, PanResponder, Pressable, ScrollView, Text, View } from "react-native";
3
+ import type { ActivityHour } from "../shared/usage.ts";
4
+ import { metricValue, type ActivityMetric } from "../shared/activity.ts";
5
+ import { useMeasuredWidth } from "./measured-width.ts";
6
+ import { mixColor } from "./color-mix.ts";
7
+ import { CHART_MOTION, TEXT, sectionTitle, titleGap } from "./design-tokens.ts";
8
+ import { messagesFor } from "../shared/i18n.ts";
9
+ import { ChartTooltip, InlineEmpty, MetricStepper } from "./ui.tsx";
10
+
11
+ type ThemeColors = {
12
+ accent: string;
13
+ border: string;
14
+ foreground: string;
15
+ foregroundMuted: string;
16
+ surface2: string;
17
+ };
18
+
19
+ /** Hours visible in one viewport; the step follows from the measured width. */
20
+ const VISIBLE_HOURS = 24;
21
+ const STROKE = 2;
22
+ /** A day label ("Sep 24") plus the right-pinned "Now" must fit, or the label overflows the scroll content. */
23
+ const NOW_LABEL_CLEARANCE = 72;
24
+
25
+ function hourRangeLabel(start: string, locale: string): string {
26
+ const from = new Date(start);
27
+ const to = new Date(from.getTime() + 60 * 60 * 1000);
28
+ const day = from.toLocaleDateString(locale, {
29
+ weekday: "short",
30
+ month: "short",
31
+ day: "numeric",
32
+ });
33
+ const time = (value: Date) =>
34
+ value.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit", hour12: false });
35
+ return `${day} · ${time(from)}–${time(to)}`;
36
+ }
37
+
38
+ /**
39
+ * Filled line series drawn with React Native primitives only (no SVG on the
40
+ * host). Clipped `skewY` cells paint the area; rotated strokes and round
41
+ * joints draw one continuous-looking line above it.
42
+ */
43
+ function AreaSeries({
44
+ values,
45
+ max,
46
+ height,
47
+ slot,
48
+ stroke,
49
+ fill,
50
+ }: {
51
+ values: readonly number[];
52
+ max: number;
53
+ height: number;
54
+ slot: number;
55
+ stroke: string;
56
+ fill: string;
57
+ }) {
58
+ // Leave room for the line so the peak is never clipped.
59
+ const usable = Math.max(1, height - STROKE - 1);
60
+ const scale = (value: number) => (max > 0 ? (value / max) * usable : 0);
61
+ const heights = values.map(scale);
62
+
63
+ return (
64
+ <View
65
+ style={{
66
+ height,
67
+ flexDirection: "row",
68
+ overflow: "hidden",
69
+ }}
70
+ >
71
+ {heights.slice(0, -1).map((left, index) => {
72
+ const right = heights[index + 1] ?? 0;
73
+ // skewY(a) maps y -> y + (x - slot/2)·tan(a), so tan is the segment slope.
74
+ const tan = (left - right) / slot;
75
+ const angle = (Math.atan(tan) * 180) / Math.PI;
76
+ return (
77
+ <View key={index} style={{ width: slot, height, overflow: "hidden" }}>
78
+ <View
79
+ style={{
80
+ position: "absolute",
81
+ left: 0,
82
+ width: slot,
83
+ // Place the sheared top edge on the two hour values.
84
+ top: height - left + (slot / 2) * tan,
85
+ height: height * 2 + slot * Math.abs(tan),
86
+ backgroundColor: fill,
87
+ transform: [{ skewY: `${angle}deg` }],
88
+ }}
89
+ />
90
+ </View>
91
+ );
92
+ })}
93
+ {heights.slice(0, -1).map((left, index) => {
94
+ const right = heights[index + 1] ?? 0;
95
+ const rise = left - right;
96
+ const length = Math.hypot(slot, rise);
97
+ return (
98
+ <View
99
+ key={`line-${index}`}
100
+ style={{
101
+ position: "absolute",
102
+ left: index * slot + (slot - length) / 2,
103
+ top: height - (left + right) / 2 - STROKE / 2,
104
+ width: length,
105
+ height: STROKE,
106
+ borderRadius: STROKE / 2,
107
+ backgroundColor: stroke,
108
+ transform: [{ rotate: `${(Math.atan2(rise, slot) * 180) / Math.PI}deg` }],
109
+ }}
110
+ />
111
+ );
112
+ })}
113
+ {heights.slice(1, -1).map((value, index) => (
114
+ <View
115
+ key={`joint-${index}`}
116
+ style={{
117
+ position: "absolute",
118
+ left: (index + 1) * slot - STROKE / 2,
119
+ top: height - value - STROKE / 2,
120
+ width: STROKE,
121
+ height: STROKE,
122
+ borderRadius: STROKE / 2,
123
+ backgroundColor: stroke,
124
+ }}
125
+ />
126
+ ))}
127
+ </View>
128
+ );
129
+ }
130
+
131
+ export function HourlyActivityTimeline({
132
+ hours,
133
+ colors,
134
+ compact,
135
+ locale,
136
+ resetKey,
137
+ }: {
138
+ hours: readonly ActivityHour[];
139
+ colors: ThemeColors;
140
+ compact?: boolean;
141
+ locale: string;
142
+ /** Provider change re-anchors the timeline to Now. */
143
+ resetKey: string;
144
+ }) {
145
+ const scrollRef = useRef<ScrollView>(null);
146
+ /** Scroll state lives in refs so panning never triggers a re-render. */
147
+ const offsetRef = useRef(0);
148
+ const maxOffsetRef = useRef(0);
149
+ const dragOriginRef = useRef(0);
150
+ const pinnedRight = useRef(true);
151
+ const [width, widthRef, onWidthLayout] = useMeasuredWidth("global:timeline");
152
+ const [hovered, setHovered] = useState<string | null>(null);
153
+ const [plotTop, setPlotTop] = useState(0);
154
+ const [metric, setMetric] = useState<ActivityMetric>("sessions");
155
+ const m = messagesFor(locale);
156
+
157
+ const plotHeight = compact ? 67 : 89;
158
+ const gaps = Math.max(1, hours.length - 1);
159
+ const slot = width > 0 ? width / VISIBLE_HOURS : 0;
160
+ const contentWidth = slot > 0 ? gaps * slot : 0;
161
+ const maxOffset = Math.max(0, contentWidth - width);
162
+ maxOffsetRef.current = maxOffset;
163
+
164
+ /**
165
+ * Press-and-drag panning: the host's mouse users have no horizontal wheel and
166
+ * the scrollbar is hidden. Claimed only once the gesture is clearly
167
+ * horizontal, so hover and click on an hour still reach the hotspots.
168
+ */
169
+ const pan = useMemo(
170
+ () =>
171
+ PanResponder.create({
172
+ onMoveShouldSetPanResponder: (_event, gesture) =>
173
+ Math.abs(gesture.dx) > 3 && Math.abs(gesture.dx) > Math.abs(gesture.dy),
174
+ onPanResponderGrant: () => {
175
+ dragOriginRef.current = offsetRef.current;
176
+ // A drag steals the pointer from the hotspots; drop the stale cursor.
177
+ setHovered(null);
178
+ },
179
+ onPanResponderMove: (_event, gesture) => {
180
+ const target = Math.max(
181
+ 0,
182
+ Math.min(maxOffsetRef.current, dragOriginRef.current - gesture.dx),
183
+ );
184
+ offsetRef.current = target;
185
+ scrollRef.current?.scrollTo({ x: target, animated: false });
186
+ },
187
+ onPanResponderRelease: () => {
188
+ pinnedRight.current = offsetRef.current >= maxOffsetRef.current - 2;
189
+ },
190
+ }),
191
+ [],
192
+ );
193
+
194
+ useEffect(() => {
195
+ pinnedRight.current = true;
196
+ setHovered(null);
197
+ scrollRef.current?.scrollToEnd({ animated: false });
198
+ }, [resetKey]);
199
+
200
+ const { values, peak } = useMemo(() => {
201
+ const values = hours.map((hour) => metricValue(hour, metric));
202
+ return { values, peak: values.reduce((max, value) => Math.max(max, value), 0) };
203
+ }, [hours, metric]);
204
+
205
+ /** Local midnights become axis ticks. */
206
+ const dayTicks = useMemo(
207
+ () =>
208
+ hours.flatMap((hour, index) => {
209
+ const date = new Date(hour.start);
210
+ if (date.getHours() !== 0) return [];
211
+ return [
212
+ {
213
+ index,
214
+ label: date.toLocaleDateString(locale, { month: "short", day: "numeric" }),
215
+ },
216
+ ];
217
+ }),
218
+ [hours, locale],
219
+ );
220
+
221
+ const activeIndex = hours.findIndex((hour) => hour.key === hovered);
222
+ const active = activeIndex >= 0 ? hours[activeIndex] : undefined;
223
+
224
+ const fill = mixColor(colors.surface2, colors.accent, 0.22);
225
+ // Softened toward the surface so the hover cursor reads grey, not near-black.
226
+ const cursorColor = mixColor(colors.surface2, colors.foregroundMuted, 0.55);
227
+
228
+ const ready = hours.length > 0 && slot > 0;
229
+ const grow = useRef(new Animated.Value(0)).current;
230
+ const revealedRef = useRef(false);
231
+ useEffect(() => {
232
+ if (!ready) return;
233
+ const first = !revealedRef.current;
234
+ grow.setValue(0);
235
+ const animation = Animated.timing(grow, {
236
+ toValue: 1,
237
+ duration: first ? CHART_MOTION.reveal : CHART_MOTION.refresh,
238
+ easing: Easing.out(Easing.cubic),
239
+ useNativeDriver: false,
240
+ });
241
+ animation.start(() => {
242
+ revealedRef.current = true;
243
+ });
244
+ return () => animation.stop();
245
+ }, [ready, metric, resetKey, grow]);
246
+
247
+ // Stable element identity: hovering must not rebuild ~330 skewed segments.
248
+ const series = useMemo(
249
+ () => (
250
+ <>
251
+ <Animated.View
252
+ style={{
253
+ // scaleY pivots on the center; the shift pins the plot to its baseline.
254
+ transform: [
255
+ { translateY: grow.interpolate({ inputRange: [0, 1], outputRange: [plotHeight / 2, 0] }) },
256
+ { scaleY: grow },
257
+ ],
258
+ }}
259
+ >
260
+ <AreaSeries values={values} max={peak} height={plotHeight} slot={slot} stroke={colors.accent} fill={fill} />
261
+ </Animated.View>
262
+ <View style={{ height: 1, backgroundColor: colors.border }} />
263
+ </>
264
+ ),
265
+ [values, peak, plotHeight, slot, colors.accent, colors.border, fill, grow],
266
+ );
267
+
268
+ const hotspots = useMemo(
269
+ () => (
270
+ <View
271
+ // Clipped: the edge hotspots overhang by half a slot, and that overhang
272
+ // would otherwise widen the scroll content past the last hour.
273
+ style={{
274
+ position: "absolute",
275
+ left: 0,
276
+ top: 0,
277
+ width: contentWidth,
278
+ height: plotHeight,
279
+ overflow: "hidden",
280
+ }}
281
+ >
282
+ {hours.map((hour, index) => (
283
+ <Pressable
284
+ key={hour.key}
285
+ focusable
286
+ accessibilityLabel={`${hourRangeLabel(hour.start, locale)}: ${m.units.sessions(hour.agents)}, ${m.units.prompts(hour.messages)}, ${m.units.skills(hour.skills)}, ${m.units.mcp(hour.mcp)}`}
287
+ onHoverIn={() => setHovered(hour.key)}
288
+ onHoverOut={() => setHovered(null)}
289
+ onFocus={() => setHovered(hour.key)}
290
+ onBlur={() => setHovered(null)}
291
+ style={{
292
+ position: "absolute",
293
+ left: Math.max(0, index * slot - slot / 2),
294
+ top: 0,
295
+ width: slot,
296
+ height: plotHeight,
297
+ }}
298
+ />
299
+ ))}
300
+ </View>
301
+ ),
302
+ [hours, slot, contentWidth, plotHeight, locale, m],
303
+ );
304
+
305
+ return (
306
+ <View
307
+ ref={widthRef}
308
+ style={{ gap: titleGap(compact) }}
309
+ onLayout={onWidthLayout}
310
+ >
311
+ <View
312
+ style={{
313
+ flexDirection: "row",
314
+ flexWrap: "wrap",
315
+ alignItems: "center",
316
+ justifyContent: "space-between",
317
+ gap: 12,
318
+ }}
319
+ >
320
+ <Text style={{ ...sectionTitle(compact), color: colors.foreground }}>
321
+ {m.timeline.title}
322
+ </Text>
323
+ <MetricStepper value={metric} onChange={setMetric} colors={colors} />
324
+ </View>
325
+
326
+ {hours.length === 0 || slot === 0 ? (
327
+ <View style={{ height: plotHeight, justifyContent: "center" }}>
328
+ {hours.length === 0 ? <InlineEmpty text={m.timeline.empty} color={colors.foregroundMuted} /> : null}
329
+ </View>
330
+ ) : (
331
+ <ScrollView
332
+ ref={scrollRef}
333
+ horizontal
334
+ onLayout={(event) => setPlotTop(event.nativeEvent.layout.y)}
335
+ nestedScrollEnabled
336
+ showsHorizontalScrollIndicator={false}
337
+ scrollEventThrottle={16}
338
+ {...pan.panHandlers}
339
+ onScroll={(event) => {
340
+ offsetRef.current = event.nativeEvent.contentOffset.x;
341
+ pinnedRight.current = offsetRef.current >= maxOffset - 2;
342
+ }}
343
+ // Fires on mount and on every resize; keeps Now on screen unless the
344
+ // user has scrolled into history.
345
+ onContentSizeChange={() => {
346
+ if (pinnedRight.current) scrollRef.current?.scrollToEnd({ animated: false });
347
+ }}
348
+ >
349
+ <View style={{ width: contentWidth, paddingBottom: 2 }}>
350
+ {series}
351
+
352
+ {active ? (
353
+ <View
354
+ pointerEvents="none"
355
+ style={{
356
+ position: "absolute",
357
+ left: Math.min(contentWidth - 1, activeIndex * slot),
358
+ top: 0,
359
+ width: 1,
360
+ height: plotHeight,
361
+ backgroundColor: cursorColor,
362
+ }}
363
+ />
364
+ ) : null}
365
+
366
+ {hotspots}
367
+
368
+ <View style={{ height: 16, marginTop: 4 }}>
369
+ {dayTicks
370
+ .filter((tick) => tick.index * slot <= contentWidth - NOW_LABEL_CLEARANCE)
371
+ .map((tick) => (
372
+ <View
373
+ key={tick.index}
374
+ style={{ position: "absolute", left: tick.index * slot, top: -4 }}
375
+ >
376
+ <View style={{ width: 1, height: 3, backgroundColor: colors.border }} />
377
+ <Text
378
+ numberOfLines={1}
379
+ style={{ ...TEXT.caption, color: colors.foregroundMuted, marginTop: 2 }}
380
+ >
381
+ {tick.label}
382
+ </Text>
383
+ </View>
384
+ ))}
385
+ <Text
386
+ style={{
387
+ position: "absolute",
388
+ right: 0,
389
+ top: 1,
390
+ ...TEXT.caption,
391
+ color: colors.foregroundMuted,
392
+ }}
393
+ >
394
+ {m.common.now}
395
+ </Text>
396
+ </View>
397
+ </View>
398
+ </ScrollView>
399
+ )}
400
+
401
+ {active && slot > 0 ? (
402
+ <ChartTooltip
403
+ anchorX={activeIndex * slot - offsetRef.current}
404
+ anchorY={plotTop}
405
+ containerWidth={width}
406
+ clampTop={false}
407
+ title={hourRangeLabel(active.start, locale)}
408
+ rows={(
409
+ [
410
+ ["sessions", m.common.sessions],
411
+ ["prompts", m.common.prompts],
412
+ ["skills", m.common.skills],
413
+ ["mcp", m.common.mcp],
414
+ ] as const
415
+ ).map(([id, label]) => ({
416
+ label,
417
+ value: metricValue(active, id).toLocaleString(locale),
418
+ color: id === metric ? colors.accent : undefined,
419
+ }))}
420
+ colors={colors}
421
+ />
422
+ ) : null}
423
+ </View>
424
+ );
425
+ }
@@ -0,0 +1,72 @@
1
+ import { useCallback, useLayoutEffect, useRef, useState, type Ref } from "react";
2
+ import type { LayoutChangeEvent, View } from "react-native";
3
+
4
+ /**
5
+ * Measured container width for a section that has to know its pixel width (062).
6
+ *
7
+ * Two host behaviours make the naive `useState(0)` + `onLayout` version flash:
8
+ *
9
+ * 1. A surface stays mounted when the user switches pages — the host hides it
10
+ * (0-width container), which reports `width: 0` to `onLayout`. Coming back
11
+ * reports the real width again, so the section collapses to nothing and
12
+ * re-expands: the visible "re-layout" on every switch back.
13
+ * 2. While the app window is hidden or occluded the renderer runs no rendering
14
+ * updates, so `onLayout` (a ResizeObserver) never fires at all — the first
15
+ * frame after the window reappears is the one that finally measures.
16
+ *
17
+ * So: never accept a zero width (keep the last real one), seed a remount from
18
+ * the last measured value, and re-measure synchronously from the DOM node when
19
+ * the window becomes visible or resizes, which lands before the next paint.
20
+ */
21
+ const widths = new Map<string, number>();
22
+
23
+ /** react-native-web forwards refs to the host DOM node; other hosts have no DOM. */
24
+ type MeasurableElement = { getBoundingClientRect?: () => { width: number } };
25
+
26
+ type ResizableWindow = {
27
+ addEventListener?: (type: string, listener: () => void) => void;
28
+ removeEventListener?: (type: string, listener: () => void) => void;
29
+ document?: {
30
+ addEventListener?: (type: string, listener: () => void) => void;
31
+ removeEventListener?: (type: string, listener: () => void) => void;
32
+ };
33
+ };
34
+
35
+ /** `[width, ref, onLayout]` — width starts at the last measured value for `key`. */
36
+ export function useMeasuredWidth(key: string): [number, Ref<View>, (event: LayoutChangeEvent) => void] {
37
+ const [width, setWidth] = useState(() => widths.get(key) ?? 0);
38
+ const ref = useRef<MeasurableElement | null>(null);
39
+
40
+ const apply = useCallback((next: number) => {
41
+ // Hidden containers and not-yet-laid-out frames report 0; keeping the last
42
+ // real width is what stops the collapse-and-re-expand.
43
+ if (!(next > 0)) return;
44
+ widths.set(key, next);
45
+ setWidth(next);
46
+ }, [key]);
47
+
48
+ const measure = useCallback(() => {
49
+ const rect = ref.current?.getBoundingClientRect?.();
50
+ if (rect) apply(rect.width);
51
+ }, [apply]);
52
+
53
+ useLayoutEffect(() => {
54
+ measure();
55
+ const win = globalThis as unknown as ResizableWindow;
56
+ win.addEventListener?.("resize", measure);
57
+ win.document?.addEventListener?.("visibilitychange", measure);
58
+ return () => {
59
+ win.removeEventListener?.("resize", measure);
60
+ win.document?.removeEventListener?.("visibilitychange", measure);
61
+ };
62
+ }, [measure]);
63
+
64
+ const onLayout = useCallback(
65
+ (event: LayoutChangeEvent) => apply(event.nativeEvent.layout.width),
66
+ [apply],
67
+ );
68
+
69
+ // The DOM node is the real measuring target on web; the RN `View` ref type
70
+ // describes the native component, which has no getBoundingClientRect.
71
+ return [width, ref as unknown as Ref<View>, onLayout];
72
+ }
@@ -0,0 +1,25 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { isPanelMounted, setPanelMounted, watchPanelPresence } from "./panel-visibility.ts";
4
+
5
+ test("panel presence tracks instances per workspace and notifies on flips only", () => {
6
+ const events: string[] = [];
7
+ const stop = watchPanelPresence((id) => events.push(`${id}:${isPanelMounted(id)}`));
8
+ const a = {};
9
+ const b = {};
10
+
11
+ setPanelMounted("w1", a, true);
12
+ setPanelMounted("w1", b, true);
13
+ setPanelMounted("w1", a, false);
14
+ assert.equal(isPanelMounted("w1"), true);
15
+ setPanelMounted("w1", b, false);
16
+ setPanelMounted("w1", b, false);
17
+ assert.equal(isPanelMounted("w1"), false);
18
+ assert.equal(isPanelMounted("w2"), false);
19
+ assert.deepEqual(events, ["w1:true", "w1:false"]);
20
+
21
+ stop();
22
+ setPanelMounted("w1", a, true);
23
+ assert.deepEqual(events, ["w1:true", "w1:false"]);
24
+ setPanelMounted("w1", a, false);
25
+ });
@@ -0,0 +1,45 @@
1
+ import { useEffect, useRef } from "react";
2
+
3
+ /**
4
+ * Which workspaces currently have a mounted Workspace Activity panel (067).
5
+ *
6
+ * Inactive tabs and a collapsed Explorer stay mounted. The host can still
7
+ * evict an inactive tab after its retained-tab limit is reached.
8
+ */
9
+ const mounted = new Map<string, Set<object>>();
10
+ const listeners = new Set<(workspaceId: string) => void>();
11
+
12
+ export function setPanelMounted(workspaceId: string, instance: object, isMounted: boolean): void {
13
+ const instances = mounted.get(workspaceId);
14
+ const was = instances != null && instances.size > 0;
15
+ if (isMounted) {
16
+ if (instances) instances.add(instance);
17
+ else mounted.set(workspaceId, new Set([instance]));
18
+ } else if (instances) {
19
+ instances.delete(instance);
20
+ if (instances.size === 0) mounted.delete(workspaceId);
21
+ }
22
+ if (was === isPanelMounted(workspaceId)) return;
23
+ for (const listener of listeners) listener(workspaceId);
24
+ }
25
+
26
+ export function isPanelMounted(workspaceId: string): boolean {
27
+ return (mounted.get(workspaceId)?.size ?? 0) > 0;
28
+ }
29
+
30
+ /** Called with the workspace id whenever its mounted state flips. */
31
+ export function watchPanelPresence(listener: (workspaceId: string) => void): () => void {
32
+ listeners.add(listener);
33
+ return () => {
34
+ listeners.delete(listener);
35
+ };
36
+ }
37
+
38
+ /** Registers a panel until unmount or workspace change. */
39
+ export function usePanelPresenceReport(workspaceId: string): void {
40
+ const instance = useRef({}).current;
41
+ useEffect(() => {
42
+ setPanelMounted(workspaceId, instance, true);
43
+ return () => setPanelMounted(workspaceId, instance, false);
44
+ }, [workspaceId, instance]);
45
+ }