@koinzhang/paseo-plugin-activity 0.4.0 → 0.6.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 (52) hide show
  1. package/CHANGELOG.md +61 -2
  2. package/README.md +3 -3
  3. package/client/activity-heatmap.tsx +17 -25
  4. package/client/agent-creations.tsx +207 -0
  5. package/client/agent-directory.test.ts +191 -0
  6. package/client/agent-directory.ts +150 -0
  7. package/client/attention-pill.tsx +17 -105
  8. package/client/color-mix.test.ts +27 -0
  9. package/client/color-mix.ts +38 -0
  10. package/client/fit-text.test.ts +41 -0
  11. package/client/fit-text.ts +33 -0
  12. package/client/global-surface.tsx +104 -31
  13. package/client/hourly-activity-timeline.tsx +392 -0
  14. package/client/measured-width.ts +72 -0
  15. package/client/pill-directory.ts +20 -68
  16. package/client/range.test.ts +44 -0
  17. package/client/range.ts +14 -0
  18. package/client/rank-color.test.ts +108 -14
  19. package/client/rank-color.ts +261 -48
  20. package/client/usage-stats.tsx +116 -5
  21. package/client/use-agent-turn-end.ts +19 -2
  22. package/client/use-workspace-agent-statuses.ts +18 -42
  23. package/client/workspace/constants.ts +2 -0
  24. package/client/workspace/host-archive-sync.test.ts +46 -0
  25. package/client/workspace/host-archive-sync.ts +15 -0
  26. package/client/workspace/list-host-agents.test.ts +11 -63
  27. package/client/workspace/list-host-agents.ts +4 -58
  28. package/client/workspace/panel.tsx +99 -12
  29. package/client/workspace/rank-section.tsx +150 -11
  30. package/index.server.ts +30 -0
  31. package/package.json +3 -3
  32. package/paseo-plugin.json +1 -1
  33. package/server/background-sync.test.ts +43 -0
  34. package/server/background-sync.ts +9 -0
  35. package/server/handlers-query.test.ts +225 -0
  36. package/server/handlers.ts +117 -0
  37. package/shared/activity.test.ts +123 -6
  38. package/shared/activity.ts +103 -5
  39. package/shared/classify.test.ts +10 -0
  40. package/shared/classify.ts +10 -0
  41. package/shared/explorer-agent-display.test.ts +61 -0
  42. package/shared/explorer-agent-display.ts +21 -2
  43. package/shared/format.test.ts +28 -3
  44. package/shared/format.ts +22 -2
  45. package/shared/insights.test.ts +113 -70
  46. package/shared/insights.ts +53 -39
  47. package/shared/usage.test.ts +209 -0
  48. package/shared/usage.ts +283 -1
  49. package/client/pill-directory.test.ts +0 -92
  50. package/client/workspace/agent-live-status-sync.tsx +0 -103
  51. package/client/workspace/status-cache.test.ts +0 -62
  52. package/client/workspace/status-cache.ts +0 -23
@@ -12,8 +12,11 @@ import {
12
12
  type ViewStyle,
13
13
  } from "react-native";
14
14
  import {
15
+ usageActivityByHourRpc,
15
16
  providerLabel,
16
17
  usageActivityByDayRpc,
18
+ usageAgentCreationsRpc,
19
+ usageAgentLifetimeRpc,
17
20
  usageByProviderRpc,
18
21
  type ProviderUsageItem,
19
22
  } from "../shared/usage.ts";
@@ -23,18 +26,24 @@ import {
23
26
  computeStreaks,
24
27
  type HeatmapMode,
25
28
  } from "./activity-heatmap.tsx";
29
+ import { AgentCreations } from "./agent-creations.tsx";
30
+ import { HourlyActivityTimeline } from "./hourly-activity-timeline.tsx";
26
31
 
27
32
  import { UsageStats } from "./usage-stats.tsx";
28
- import { mcpServerColor } from "./rank-color.ts";
33
+ import { chartColorScheme, entityColor } from "./rank-color.ts";
29
34
  import { selectProviderOptions } from "./provider-filter.ts";
30
35
  import { useAppLanguage } from "./use-app-language.ts";
31
- import { buildActivityInsights, ACTIVITY_LIST_LIMIT } from "../shared/insights.ts";
32
- import { rangeFrom, RANGE_OPTIONS, type RangeId } from "./range.ts";
36
+ import { buildActivityInsights, buildActivityKpi, ACTIVITY_LIST_LIMIT } from "../shared/insights.ts";
37
+ import { fixedWindowFrom, rangeFrom, RANGE_OPTIONS, type RangeId } from "./range.ts";
33
38
  import { useRegisterOpenAgent } from "./open-agent.ts";
34
39
 
35
40
  /** Max rows for Activity insights and Most used skills / MCP. */
36
41
  const LIST_LIMIT = ACTIVITY_LIST_LIMIT;
37
42
 
43
+ /** Fixed width of the creations histogram, independent of the range chips (050). */
44
+ const CREATIONS_WINDOW_DAYS = 30;
45
+ const HOURLY_WINDOW_HOURS = 7 * 24;
46
+
38
47
  /** Zeroed provider row when the chip exists all-time but the time window has no rows. */
39
48
  function emptyProviderUsage(provider: string, label?: string): ProviderUsageItem {
40
49
  return {
@@ -62,12 +71,6 @@ function emptyProviderUsage(provider: string, label?: string): ProviderUsageItem
62
71
 
63
72
 
64
73
 
65
- function formatCount(value: number): string {
66
- if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`;
67
- if (value >= 10_000) return `${(value / 1_000).toFixed(1).replace(/\.0$/, "")}k`;
68
- return String(value);
69
- }
70
-
71
74
  function TextTabs({
72
75
  options,
73
76
  value,
@@ -162,7 +165,7 @@ function RankList({
162
165
  rankMeta: TextStyle;
163
166
  emptyHint: TextStyle;
164
167
  };
165
- colors: { accent: string; foregroundMuted: string };
168
+ colors: { accent: string; foregroundMuted: string; surface0: string };
166
169
  headerAction?: {
167
170
  icon: "Sparkles" | "Plug" | "Bot";
168
171
  accessibilityLabel: string;
@@ -195,7 +198,7 @@ function RankList({
195
198
  size={14}
196
199
  color={
197
200
  item.kind === "mcp"
198
- ? mcpServerColor(item.server ?? "", colors.accent)
201
+ ? entityColor(item.server ?? "", chartColorScheme(colors.surface0))
199
202
  : colors.accent
200
203
  }
201
204
  />
@@ -225,6 +228,9 @@ export function GlobalUsageSurface({ theme, layout, navigation }: PluginSurfaceP
225
228
  const padding = layout.compact ? 16 : 20;
226
229
  const byProvider = useRpc(usageByProviderRpc);
227
230
  const activityByDay = useRpc(usageActivityByDayRpc);
231
+ const activityByHour = useRpc(usageActivityByHourRpc);
232
+ const agentLifetime = useRpc(usageAgentLifetimeRpc);
233
+ const agentCreations = useRpc(usageAgentCreationsRpc);
228
234
 
229
235
  const filter = from ? { from } : {};
230
236
 
@@ -259,6 +265,42 @@ export function GlobalUsageSurface({ theme, layout, navigation }: PluginSurfaceP
259
265
  placeholderData: keepPreviousData,
260
266
  });
261
267
 
268
+ const lifetimeQuery = useQuery({
269
+ refetchInterval: 15_000,
270
+ retry: false,
271
+ // Lifetime is all-time by design (049): only the provider filter applies.
272
+ queryKey: ["activity", "agent-lifetime", providerFilter],
273
+ queryFn: () =>
274
+ agentLifetime({ provider: providerFilter === "all" ? undefined : providerFilter }),
275
+ placeholderData: keepPreviousData,
276
+ });
277
+
278
+ const histogramQuery = useQuery({
279
+ refetchInterval: 15_000,
280
+ retry: false,
281
+ // Fixed window (050): the creations histogram ignores the range chips.
282
+ queryKey: ["activity", "agent-creations", "last30", providerFilter],
283
+ queryFn: () =>
284
+ agentCreations({
285
+ from: fixedWindowFrom(CREATIONS_WINDOW_DAYS),
286
+ provider: providerFilter === "all" ? undefined : providerFilter,
287
+ }),
288
+ placeholderData: keepPreviousData,
289
+ });
290
+
291
+ const hourlyQuery = useQuery({
292
+ refetchInterval: 15_000,
293
+ retry: false,
294
+ // Independent fixed window (059): range chips do not affect the hourly stream.
295
+ queryKey: ["activity", "activity-by-hour", "last168", providerFilter],
296
+ queryFn: () =>
297
+ activityByHour({
298
+ hours: HOURLY_WINDOW_HOURS,
299
+ provider: providerFilter === "all" ? undefined : providerFilter,
300
+ }),
301
+ placeholderData: keepPreviousData,
302
+ });
303
+
262
304
  const providers = query.data?.providers ?? [];
263
305
  const catalogProviders = catalogQuery.data?.providers ?? providers;
264
306
 
@@ -444,28 +486,37 @@ export function GlobalUsageSurface({ theme, layout, navigation }: PluginSurfaceP
444
486
  messages: summary.messages,
445
487
  codingAgents: summary.codingAgents,
446
488
  chatAgents: summary.chatAgents,
447
- longestStreak: streaks.longest,
448
489
  },
449
- providers: filteredProviders,
450
- providerFilter,
490
+ workspaces: summary.workspaces,
451
491
  locale,
452
- limit: LIST_LIMIT,
453
492
  });
454
- }, [activityQuery.data?.days, filteredProviders, locale, providerFilter, streaks.longest, summary]);
493
+ }, [activityQuery.data?.days, locale, summary]);
455
494
 
456
495
  const kpi = useMemo(
457
- () => [
458
- { value: formatCount(summary.messages), label: "Messages" },
459
- { value: formatCount(summary.agents), label: "Agents" },
460
- { value: formatCount(summary.workspaces), label: "Workspaces" },
461
- { value: formatCount(summary.skills), label: "Skill calls" },
462
- { value: formatCount(summary.mcp), label: "MCP calls" },
463
- {
464
- value: `${streaks.current} day${streaks.current === 1 ? "" : "s"}`,
465
- label: "Current streak",
466
- },
496
+ () =>
497
+ buildActivityKpi({
498
+ agents: summary.agents,
499
+ days: activityQuery.data?.days ?? [],
500
+ locale,
501
+ longestStreak: streaks.longest,
502
+ longestAgent: lifetimeQuery.data?.longest
503
+ ? {
504
+ durationMs: lifetimeQuery.data.longest.durationMs,
505
+ active: lifetimeQuery.data.longest.archivedAt == null,
506
+ }
507
+ : null,
508
+ providers: filteredProviders,
509
+ providerFilter,
510
+ }),
511
+ [
512
+ activityQuery.data?.days,
513
+ filteredProviders,
514
+ lifetimeQuery.data,
515
+ locale,
516
+ providerFilter,
517
+ streaks.longest,
518
+ summary.agents,
467
519
  ],
468
- [summary, streaks],
469
520
  );
470
521
 
471
522
  const styles = useMemo(
@@ -520,7 +571,8 @@ export function GlobalUsageSurface({ theme, layout, navigation }: PluginSurfaceP
520
571
  alignItems: "center" as const,
521
572
  justifyContent: "space-between" as const,
522
573
  gap: 8,
523
- marginBottom: 10,
574
+ // + block gap 2 = 10 (compact) / 12 (regular), the chart sections' title gap.
575
+ marginBottom: layout.compact ? 8 : 10,
524
576
  },
525
577
  blockTitle: {
526
578
  color: theme.colors.foreground,
@@ -591,8 +643,9 @@ export function GlobalUsageSurface({ theme, layout, navigation }: PluginSurfaceP
591
643
  // Keep prior results visible while refetching; spinner only on cold start.
592
644
  const loading =
593
645
  (!query.data && query.isLoading) ||
594
- (!activityQuery.data && activityQuery.isLoading);
595
- const error = query.error ?? activityQuery.error;
646
+ (!activityQuery.data && activityQuery.isLoading) ||
647
+ (!hourlyQuery.data && hourlyQuery.isLoading);
648
+ const error = query.error ?? activityQuery.error ?? hourlyQuery.error;
596
649
  const showContent = filteredProviders.length > 0;
597
650
 
598
651
  return (
@@ -648,11 +701,31 @@ export function GlobalUsageSurface({ theme, layout, navigation }: PluginSurfaceP
648
701
  />
649
702
  ) : null}
650
703
 
704
+ {showContent ? (
705
+ <AgentCreations
706
+ days={histogramQuery.data?.days ?? []}
707
+ windowDays={CREATIONS_WINDOW_DAYS}
708
+ colors={theme.colors}
709
+ compact={layout.compact}
710
+ locale={locale}
711
+ />
712
+ ) : null}
713
+
714
+ {showContent ? (
715
+ <HourlyActivityTimeline
716
+ hours={hourlyQuery.data?.hours ?? []}
717
+ colors={theme.colors}
718
+ compact={layout.compact}
719
+ locale={locale}
720
+ resetKey={providerFilter}
721
+ />
722
+ ) : null}
723
+
651
724
  {showContent ? (
652
725
  <View style={styles.columns}>
653
726
  <View style={styles.column}>
654
727
  <View style={styles.block}>
655
- <Text style={[styles.blockTitle, { marginBottom: 10 }]}>Activity insights</Text>
728
+ <Text style={[styles.blockTitle, { marginBottom: layout.compact ? 8 : 10 }]}>Activity insights</Text>
656
729
  {insights.map((row) => (
657
730
  <View key={row.label} style={styles.insightRow}>
658
731
  <Text style={styles.insightLabel}>{row.label}</Text>
@@ -0,0 +1,392 @@
1
+ import { useEffect, useMemo, useRef, useState } from "react";
2
+ import { PanResponder, Pressable, ScrollView, Text, View } from "react-native";
3
+ import type { ActivityHour } from "../shared/usage.ts";
4
+ import { useMeasuredWidth } from "./measured-width.ts";
5
+ import { mixColor } from "./color-mix.ts";
6
+
7
+ type ThemeColors = {
8
+ accent: string;
9
+ border: string;
10
+ foreground: string;
11
+ foregroundMuted: string;
12
+ surface2: string;
13
+ };
14
+
15
+ /** Hours visible in one viewport; the step follows from the measured width. */
16
+ const VISIBLE_HOURS = 24;
17
+ const STROKE = 2;
18
+ /** Guards against a near-vertical segment asking for an absurd border band. */
19
+ const MAX_STROKE_BAND = 48;
20
+
21
+ function hourRangeLabel(start: string, locale: string): string {
22
+ const from = new Date(start);
23
+ const to = new Date(from.getTime() + 60 * 60 * 1000);
24
+ const day = from.toLocaleDateString(locale, {
25
+ weekday: "short",
26
+ month: "short",
27
+ day: "numeric",
28
+ });
29
+ const time = (value: Date) =>
30
+ value.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit", hour12: false });
31
+ return `${day} · ${time(from)}–${time(to)}`;
32
+ }
33
+
34
+ /**
35
+ * Filled line series drawn with React Native primitives only (no SVG on the
36
+ * host). Each hour gap is one clipped cell holding a `skewY` parallelogram:
37
+ * its top edge is the polyline segment, its body is the area fill.
38
+ */
39
+ function AreaSeries({
40
+ values,
41
+ max,
42
+ height,
43
+ slot,
44
+ stroke,
45
+ fill,
46
+ flip,
47
+ }: {
48
+ values: readonly number[];
49
+ max: number;
50
+ height: number;
51
+ slot: number;
52
+ stroke: string;
53
+ fill: string;
54
+ /** Mirror the series below the axis. */
55
+ flip?: boolean;
56
+ }) {
57
+ // Leave room for the stroke band so the peak is never clipped.
58
+ const usable = Math.max(1, height - STROKE - 1);
59
+ const scale = (value: number) => (max > 0 ? (value / max) * usable : 0);
60
+
61
+ return (
62
+ <View
63
+ style={{
64
+ height,
65
+ flexDirection: "row",
66
+ overflow: "hidden",
67
+ transform: flip ? [{ scaleY: -1 }] : undefined,
68
+ }}
69
+ >
70
+ {values.slice(0, -1).map((value, index) => {
71
+ const left = scale(value);
72
+ const right = scale(values[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
+ // Vertical band that renders as a STROKE-thick perpendicular line.
77
+ const band = Math.min(MAX_STROKE_BAND, STROKE * Math.hypot(1, tan));
78
+ return (
79
+ <View key={index} style={{ width: slot, height, overflow: "hidden" }}>
80
+ <View
81
+ style={{
82
+ position: "absolute",
83
+ left: 0,
84
+ width: slot,
85
+ // Place the sheared top edge on the two hour values, then lift
86
+ // it by the band so a zero segment still paints its baseline.
87
+ top: height - left + (slot / 2) * tan - band,
88
+ height: height * 2 + slot * Math.abs(tan) + band,
89
+ backgroundColor: fill,
90
+ borderTopWidth: band,
91
+ borderTopColor: stroke,
92
+ transform: [{ skewY: `${angle}deg` }],
93
+ }}
94
+ />
95
+ </View>
96
+ );
97
+ })}
98
+ </View>
99
+ );
100
+ }
101
+
102
+ export function HourlyActivityTimeline({
103
+ hours,
104
+ colors,
105
+ compact,
106
+ locale,
107
+ resetKey,
108
+ }: {
109
+ hours: readonly ActivityHour[];
110
+ colors: ThemeColors;
111
+ compact?: boolean;
112
+ locale: string;
113
+ /** Provider change re-anchors the timeline to Now. */
114
+ resetKey: string;
115
+ }) {
116
+ const scrollRef = useRef<ScrollView>(null);
117
+ /** Scroll state lives in refs so panning never triggers a re-render. */
118
+ const offsetRef = useRef(0);
119
+ const maxOffsetRef = useRef(0);
120
+ const dragOriginRef = useRef(0);
121
+ const pinnedRight = useRef(true);
122
+ const [width, widthRef, onWidthLayout] = useMeasuredWidth("global:timeline");
123
+ const [hovered, setHovered] = useState<string | null>(null);
124
+
125
+ const topHeight = compact ? 44 : 58;
126
+ const bottomHeight = compact ? 22 : 30;
127
+ const plotHeight = topHeight + 1 + bottomHeight;
128
+ const gaps = Math.max(1, hours.length - 1);
129
+ const slot = width > 0 ? width / VISIBLE_HOURS : 0;
130
+ const contentWidth = slot > 0 ? gaps * slot : 0;
131
+ const maxOffset = Math.max(0, contentWidth - width);
132
+ maxOffsetRef.current = maxOffset;
133
+
134
+ /**
135
+ * Press-and-drag panning: the host's mouse users have no horizontal wheel and
136
+ * the scrollbar is hidden. Claimed only once the gesture is clearly
137
+ * horizontal, so hover and click on an hour still reach the hotspots.
138
+ */
139
+ const pan = useMemo(
140
+ () =>
141
+ PanResponder.create({
142
+ onMoveShouldSetPanResponder: (_event, gesture) =>
143
+ Math.abs(gesture.dx) > 3 && Math.abs(gesture.dx) > Math.abs(gesture.dy),
144
+ onPanResponderGrant: () => {
145
+ dragOriginRef.current = offsetRef.current;
146
+ // A drag steals the pointer from the hotspots; drop the stale cursor.
147
+ setHovered(null);
148
+ },
149
+ onPanResponderMove: (_event, gesture) => {
150
+ const target = Math.max(
151
+ 0,
152
+ Math.min(maxOffsetRef.current, dragOriginRef.current - gesture.dx),
153
+ );
154
+ offsetRef.current = target;
155
+ scrollRef.current?.scrollTo({ x: target, animated: false });
156
+ },
157
+ onPanResponderRelease: () => {
158
+ pinnedRight.current = offsetRef.current >= maxOffsetRef.current - 2;
159
+ },
160
+ }),
161
+ [],
162
+ );
163
+
164
+ useEffect(() => {
165
+ pinnedRight.current = true;
166
+ setHovered(null);
167
+ scrollRef.current?.scrollToEnd({ animated: false });
168
+ }, [resetKey]);
169
+
170
+ const { messages, agents, messagePeak, agentPeak, total } = useMemo(() => {
171
+ const messages = hours.map((hour) => hour.messages);
172
+ const agents = hours.map((hour) => hour.agents);
173
+ return {
174
+ messages,
175
+ agents,
176
+ messagePeak: messages.reduce((peak, value) => Math.max(peak, value), 0),
177
+ agentPeak: agents.reduce((peak, value) => Math.max(peak, value), 0),
178
+ total: hours.reduce((sum, hour) => sum + hour.total, 0),
179
+ };
180
+ }, [hours]);
181
+
182
+ /** Local midnights become axis ticks. */
183
+ const dayTicks = useMemo(
184
+ () =>
185
+ hours.flatMap((hour, index) => {
186
+ const date = new Date(hour.start);
187
+ if (date.getHours() !== 0) return [];
188
+ return [
189
+ {
190
+ index,
191
+ label: date.toLocaleDateString(locale, { month: "short", day: "numeric" }),
192
+ },
193
+ ];
194
+ }),
195
+ [hours, locale],
196
+ );
197
+
198
+ const activeIndex = hours.findIndex((hour) => hour.key === hovered);
199
+ const active = activeIndex >= 0 ? hours[activeIndex] : undefined;
200
+ const readout = active
201
+ ? `${hourRangeLabel(active.start, locale)} — ${active.agents} agents · ${active.messages} messages · ${active.skills} skills · ${active.mcp} MCP`
202
+ : `Last ${hours.length} hours · ${total.toLocaleString(locale)} events · peak ${agentPeak} agents/h, ${messagePeak} messages/h`;
203
+
204
+ const fill = mixColor(colors.surface2, colors.accent, 0.22);
205
+ const agentStroke = mixColor(colors.surface2, colors.accent, 0.68);
206
+ // Softened toward the surface so the hover cursor reads grey, not near-black.
207
+ const cursorColor = mixColor(colors.surface2, colors.foregroundMuted, 0.55);
208
+
209
+ // Stable element identity: hovering must not rebuild ~330 skewed segments.
210
+ const series = useMemo(
211
+ () => (
212
+ <>
213
+ <AreaSeries
214
+ values={messages}
215
+ max={messagePeak}
216
+ height={topHeight}
217
+ slot={slot}
218
+ stroke={colors.accent}
219
+ fill={fill}
220
+ />
221
+ <View style={{ height: 1, backgroundColor: colors.border }} />
222
+ <AreaSeries
223
+ values={agents}
224
+ max={agentPeak}
225
+ height={bottomHeight}
226
+ slot={slot}
227
+ stroke={agentStroke}
228
+ fill={fill}
229
+ flip
230
+ />
231
+ </>
232
+ ),
233
+ [
234
+ messages,
235
+ agents,
236
+ messagePeak,
237
+ agentPeak,
238
+ topHeight,
239
+ bottomHeight,
240
+ slot,
241
+ colors.accent,
242
+ colors.border,
243
+ fill,
244
+ agentStroke,
245
+ ],
246
+ );
247
+
248
+ const hotspots = useMemo(
249
+ () => (
250
+ <View
251
+ // Clipped: the edge hotspots overhang by half a slot, and that overhang
252
+ // would otherwise widen the scroll content past the last hour.
253
+ style={{
254
+ position: "absolute",
255
+ left: 0,
256
+ top: 0,
257
+ width: contentWidth,
258
+ height: plotHeight,
259
+ overflow: "hidden",
260
+ }}
261
+ >
262
+ {hours.map((hour, index) => (
263
+ <Pressable
264
+ key={hour.key}
265
+ focusable
266
+ accessibilityLabel={`${hourRangeLabel(hour.start, locale)}: ${hour.agents} agents, ${hour.messages} messages, ${hour.skills} skills, ${hour.mcp} MCP`}
267
+ onHoverIn={() => setHovered(hour.key)}
268
+ onHoverOut={() => setHovered(null)}
269
+ onFocus={() => setHovered(hour.key)}
270
+ onBlur={() => setHovered(null)}
271
+ style={{
272
+ position: "absolute",
273
+ left: Math.max(0, index * slot - slot / 2),
274
+ top: 0,
275
+ width: slot,
276
+ height: plotHeight,
277
+ }}
278
+ />
279
+ ))}
280
+ </View>
281
+ ),
282
+ [hours, slot, contentWidth, plotHeight, locale],
283
+ );
284
+
285
+ return (
286
+ <View
287
+ ref={widthRef}
288
+ style={{ gap: compact ? 10 : 12 }}
289
+ onLayout={onWidthLayout}
290
+ >
291
+ <View
292
+ style={{
293
+ flexDirection: "row",
294
+ flexWrap: "wrap",
295
+ alignItems: "center",
296
+ justifyContent: "space-between",
297
+ gap: 12,
298
+ }}
299
+ >
300
+ <Text style={{ color: colors.foreground, fontSize: compact ? 13 : 15, fontWeight: "500" }}>
301
+ Timeline
302
+ </Text>
303
+ <View style={{ flexDirection: "row", alignItems: "center", gap: 14 }}>
304
+ <Text style={{ color: colors.accent, fontSize: 12 }}>▲ messages</Text>
305
+ <Text style={{ color: agentStroke, fontSize: 12 }}>▼ agents</Text>
306
+ </View>
307
+ </View>
308
+
309
+ {hours.length === 0 || slot === 0 ? (
310
+ <View style={{ height: plotHeight, justifyContent: "center" }}>
311
+ <Text style={{ color: colors.foregroundMuted, fontSize: 14 }}>
312
+ {hours.length === 0 ? "No activity yet" : ""}
313
+ </Text>
314
+ </View>
315
+ ) : (
316
+ <ScrollView
317
+ ref={scrollRef}
318
+ horizontal
319
+ nestedScrollEnabled
320
+ showsHorizontalScrollIndicator={false}
321
+ scrollEventThrottle={16}
322
+ {...pan.panHandlers}
323
+ onScroll={(event) => {
324
+ offsetRef.current = event.nativeEvent.contentOffset.x;
325
+ pinnedRight.current = offsetRef.current >= maxOffset - 2;
326
+ }}
327
+ // Fires on mount and on every resize; keeps Now on screen unless the
328
+ // user has scrolled into history.
329
+ onContentSizeChange={() => {
330
+ if (pinnedRight.current) scrollRef.current?.scrollToEnd({ animated: false });
331
+ }}
332
+ >
333
+ <View style={{ width: contentWidth, paddingBottom: 2 }}>
334
+ {series}
335
+
336
+ {active ? (
337
+ <View
338
+ pointerEvents="none"
339
+ style={{
340
+ position: "absolute",
341
+ left: Math.min(contentWidth - 1, activeIndex * slot),
342
+ top: 0,
343
+ width: 1,
344
+ height: plotHeight,
345
+ backgroundColor: cursorColor,
346
+ }}
347
+ />
348
+ ) : null}
349
+
350
+ {hotspots}
351
+
352
+ <View style={{ height: 16, marginTop: 4 }}>
353
+ {dayTicks.map((tick) => (
354
+ <View
355
+ key={tick.index}
356
+ style={{ position: "absolute", left: tick.index * slot, top: -4 }}
357
+ >
358
+ <View style={{ width: 1, height: 3, backgroundColor: colors.border }} />
359
+ <Text
360
+ numberOfLines={1}
361
+ style={{ color: colors.foregroundMuted, fontSize: 11, marginTop: 2 }}
362
+ >
363
+ {tick.label}
364
+ </Text>
365
+ </View>
366
+ ))}
367
+ <Text
368
+ style={{
369
+ position: "absolute",
370
+ right: 0,
371
+ top: 1,
372
+ color: colors.foregroundMuted,
373
+ fontSize: 11,
374
+ }}
375
+ >
376
+ Now
377
+ </Text>
378
+ </View>
379
+ </View>
380
+ </ScrollView>
381
+ )}
382
+
383
+ <Text
384
+ accessibilityLiveRegion="polite"
385
+ numberOfLines={1}
386
+ style={{ color: colors.foregroundMuted, fontSize: 12 }}
387
+ >
388
+ {readout}
389
+ </Text>
390
+ </View>
391
+ );
392
+ }
@@ -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
+ }