@sixb/app 0.2.5 → 0.2.7

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 (136) hide show
  1. package/dist/agent/components/agent-threads.d.ts.map +1 -1
  2. package/dist/agent/components/composer-place.d.ts.map +1 -1
  3. package/dist/agent/components/computer-place.d.ts +24 -6
  4. package/dist/agent/components/computer-place.d.ts.map +1 -1
  5. package/dist/agent/components/conversation-panel.d.ts.map +1 -1
  6. package/dist/agent/components/message-view.d.ts +13 -3
  7. package/dist/agent/components/message-view.d.ts.map +1 -1
  8. package/dist/agent/components/pending-messages.d.ts.map +1 -1
  9. package/dist/agent/components/sandbox-recovery.d.ts +8 -2
  10. package/dist/agent/components/sandbox-recovery.d.ts.map +1 -1
  11. package/dist/agent/components/transcript.d.ts +13 -0
  12. package/dist/agent/components/transcript.d.ts.map +1 -1
  13. package/dist/agent/conversation.d.ts +4 -0
  14. package/dist/agent/conversation.d.ts.map +1 -1
  15. package/dist/agent/delegation/use-children.d.ts +5 -5
  16. package/dist/agent/delegation/use-children.d.ts.map +1 -1
  17. package/dist/agent/format.d.ts +7 -0
  18. package/dist/agent/format.d.ts.map +1 -1
  19. package/dist/agent/hooks/thread-queries.d.ts +1548 -0
  20. package/dist/agent/hooks/thread-queries.d.ts.map +1 -0
  21. package/dist/agent/hooks/use-agent-conversation.d.ts +41 -2
  22. package/dist/agent/hooks/use-agent-conversation.d.ts.map +1 -1
  23. package/dist/agent/hooks/use-thread-lists.d.ts +80 -3
  24. package/dist/agent/hooks/use-thread-lists.d.ts.map +1 -1
  25. package/dist/agent/hooks/use-thread-place.d.ts +49 -0
  26. package/dist/agent/hooks/use-thread-place.d.ts.map +1 -0
  27. package/dist/agent/i18n/en.d.ts +44 -6
  28. package/dist/agent/i18n/en.d.ts.map +1 -1
  29. package/dist/agent/i18n/fr.d.ts.map +1 -1
  30. package/dist/agent/i18n/index.d.ts +76 -12
  31. package/dist/agent/i18n/index.d.ts.map +1 -1
  32. package/dist/agent/live-run.d.ts.map +1 -1
  33. package/dist/agent/model-selection.d.ts +3 -2
  34. package/dist/agent/model-selection.d.ts.map +1 -1
  35. package/dist/agent/moves.d.ts +40 -0
  36. package/dist/agent/moves.d.ts.map +1 -0
  37. package/dist/agent/thread-reader-state.d.ts +30 -0
  38. package/dist/agent/thread-reader-state.d.ts.map +1 -0
  39. package/dist/agent/types.d.ts +4 -0
  40. package/dist/agent/types.d.ts.map +1 -1
  41. package/dist/artifacts/live/session.d.ts.map +1 -1
  42. package/dist/artifacts/queries.d.ts.map +1 -1
  43. package/dist/artifacts/renderers/live-frame.d.ts.map +1 -1
  44. package/dist/{chunk-69qgh20f.js → chunk-1f4h75n3.js} +1 -1
  45. package/dist/{chunk-4fex83k2.js → chunk-7v9622qb.js} +2254 -739
  46. package/dist/{chunk-4fex83k2.js.map → chunk-7v9622qb.js.map} +29 -26
  47. package/dist/{chunk-5sgac68y.js → chunk-dntecmwb.js} +1 -1
  48. package/dist/{chunk-4wm09prf.js → chunk-qmka6aea.js} +1 -1
  49. package/dist/createCustomApp.d.ts +8 -1
  50. package/dist/createCustomApp.d.ts.map +1 -1
  51. package/dist/index.d.ts +3 -2
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +4 -2
  54. package/dist/index.js.map +3 -3
  55. package/dist/pages/console/data/accounts.d.ts +94 -0
  56. package/dist/pages/console/data/accounts.d.ts.map +1 -0
  57. package/dist/pages/console/data/connectors.d.ts.map +1 -1
  58. package/dist/pages/console/data/datasets.d.ts.map +1 -1
  59. package/dist/pages/console/data/live-updates.d.ts.map +1 -1
  60. package/dist/pages/console/data/messages.d.ts +46 -0
  61. package/dist/pages/console/data/messages.d.ts.map +1 -1
  62. package/dist/pages/console/data/pipelines.d.ts.map +1 -1
  63. package/dist/pages/console/data/projections.d.ts.map +1 -1
  64. package/dist/pages/console/data/sync-button.d.ts.map +1 -1
  65. package/dist/pages/console/data/syncs.d.ts.map +1 -1
  66. package/dist/pages/console/ontology/actions.d.ts.map +1 -1
  67. package/dist/pages/console/ontology/object-type.d.ts.map +1 -1
  68. package/dist/pages/console/ontology/object-types.d.ts.map +1 -1
  69. package/dist/pages/console/ontology/rules.d.ts.map +1 -1
  70. package/dist/pages/console/ontology/workflow.d.ts.map +1 -1
  71. package/dist/pages/console/ontology/workflows.d.ts.map +1 -1
  72. package/dist/pages/folders.d.ts +106 -0
  73. package/dist/pages/folders.d.ts.map +1 -0
  74. package/dist/pages/settings/usage/breakdown.d.ts.map +1 -1
  75. package/dist/pages/settings/usage/page.d.ts +4 -1
  76. package/dist/pages/settings/usage/page.d.ts.map +1 -1
  77. package/dist/pages/settings/usage/spend-model.d.ts +43 -19
  78. package/dist/pages/settings/usage/spend-model.d.ts.map +1 -1
  79. package/dist/pages.js +23453 -22656
  80. package/dist/pages.js.map +23 -21
  81. package/dist/server.d.ts +1 -1
  82. package/dist/server.d.ts.map +1 -1
  83. package/dist/server.js +40 -3
  84. package/dist/server.js.map +3 -3
  85. package/package.json +3 -3
  86. package/src/agent/agent-chat.tsx +2 -2
  87. package/src/agent/components/agent-threads.tsx +42 -2
  88. package/src/agent/components/composer-place.tsx +2 -7
  89. package/src/agent/components/computer-place.tsx +415 -70
  90. package/src/agent/components/conversation-panel.tsx +31 -26
  91. package/src/agent/components/message-view.tsx +418 -9
  92. package/src/agent/components/pending-messages.tsx +5 -1
  93. package/src/agent/components/sandbox-recovery.tsx +24 -6
  94. package/src/agent/components/transcript.tsx +136 -5
  95. package/src/agent/conversation.ts +16 -1
  96. package/src/agent/format.ts +52 -0
  97. package/src/agent/hooks/thread-queries.ts +75 -0
  98. package/src/agent/hooks/use-agent-conversation.ts +461 -112
  99. package/src/agent/hooks/use-thread-lists.ts +72 -7
  100. package/src/agent/hooks/use-thread-place.ts +239 -0
  101. package/src/agent/i18n/en.ts +69 -16
  102. package/src/agent/i18n/fr.ts +71 -19
  103. package/src/agent/live-run.ts +38 -0
  104. package/src/agent/model-selection.ts +3 -2
  105. package/src/agent/moves.ts +174 -0
  106. package/src/agent/thread-reader-state.ts +75 -0
  107. package/src/agent/types.ts +6 -0
  108. package/src/artifacts/live/session.ts +5 -0
  109. package/src/createCustomApp.ts +57 -3
  110. package/src/index.ts +4 -0
  111. package/src/pages/console/data/accounts.tsx +509 -0
  112. package/src/pages/console/data/connectors.tsx +67 -64
  113. package/src/pages/console/data/datasets.tsx +79 -68
  114. package/src/pages/console/data/live-updates.ts +2 -0
  115. package/src/pages/console/data/messages.ts +73 -0
  116. package/src/pages/console/data/pipelines.tsx +80 -69
  117. package/src/pages/console/data/projections.tsx +111 -82
  118. package/src/pages/console/data/sync-button.tsx +56 -16
  119. package/src/pages/console/data/syncs.tsx +121 -86
  120. package/src/pages/console/ontology/actions.tsx +51 -24
  121. package/src/pages/console/ontology/object-type.tsx +5 -1
  122. package/src/pages/console/ontology/object-types.tsx +41 -32
  123. package/src/pages/console/ontology/rules.tsx +48 -38
  124. package/src/pages/console/ontology/workflow.tsx +9 -3
  125. package/src/pages/console/ontology/workflows.tsx +55 -67
  126. package/src/pages/folders.tsx +335 -0
  127. package/src/pages/section-ui.tsx +1 -1
  128. package/src/pages/settings/usage/breakdown.tsx +5 -2
  129. package/src/pages/settings/usage/filter-menu.tsx +1 -1
  130. package/src/pages/settings/usage/page.tsx +32 -13
  131. package/src/pages/settings/usage/spend-chart.tsx +2 -2
  132. package/src/pages/settings/usage/spend-model.ts +118 -50
  133. package/src/server.ts +1 -0
  134. /package/dist/{chunk-69qgh20f.js.map → chunk-1f4h75n3.js.map} +0 -0
  135. /package/dist/{chunk-5sgac68y.js.map → chunk-dntecmwb.js.map} +0 -0
  136. /package/dist/{chunk-4wm09prf.js.map → chunk-qmka6aea.js.map} +0 -0
@@ -6,7 +6,16 @@ import {
6
6
  MessageScrollerProvider,
7
7
  MessageScrollerViewport,
8
8
  } from "@sixb/ui/components"
9
- import { Fragment, memo, type ReactNode, useCallback, useMemo, useRef } from "react"
9
+ import {
10
+ Fragment,
11
+ memo,
12
+ type ReactNode,
13
+ useCallback,
14
+ useEffect,
15
+ useMemo,
16
+ useRef,
17
+ useState,
18
+ } from "react"
10
19
  import {
11
20
  ApprovalCardsContext,
12
21
  type HeldCall,
@@ -26,11 +35,14 @@ import {
26
35
  type ThreadDelegation,
27
36
  } from "../delegation/interpret"
28
37
  import { heldInCard } from "../delegation/model"
38
+ import type { AgentMessageEditDraft } from "../hooks/use-agent-conversation"
29
39
  import { useAgentMessages } from "../i18n"
30
40
  import { principalKey } from "../message-authors"
41
+ import type { TranscriptMove } from "../moves"
31
42
  import { openQuestion } from "../questions/interpret"
32
43
  import { type QuestionTurn, QuestionTurnContext } from "../questions/question-card"
33
44
  import { CONTEXT_LIMIT_EXCEEDED } from "../run-presentation"
45
+ import type { AgentContextEntryInput, AgentFileRef } from "../types"
34
46
  import { ApprovalCards } from "./approval-card"
35
47
  import {
36
48
  CompactionMarker,
@@ -55,6 +67,18 @@ export interface TranscriptProps {
55
67
  readonly anchorCurrentTurn?: boolean
56
68
  readonly onRetry?: () => void
57
69
  readonly onContinue?: () => void
70
+ /** Saved user message ids the reader may edit in place. */
71
+ readonly editableMessageIds?: ReadonlySet<string>
72
+ /** Controlled inline-edit draft, when managed by `useAgentConversation`. */
73
+ readonly editingMessage?: AgentMessageEditDraft | null
74
+ readonly onStartEditMessage?: (messageId: string) => void
75
+ readonly onCancelEditMessage?: () => void
76
+ readonly onSubmitEditMessage?: (
77
+ messageId: string,
78
+ text: string,
79
+ attachments: readonly AgentFileRef[],
80
+ context: readonly AgentContextEntryInput[]
81
+ ) => void
58
82
  /** Start a new thread: the way on from a conversation too long for its model. */
59
83
  readonly onNewThread?: () => void
60
84
  /**
@@ -71,7 +95,13 @@ export interface TranscriptProps {
71
95
  */
72
96
  readonly delegation?: TranscriptDelegation
73
97
  /** Where the conversation moved, after which saved message: the files from before stayed. */
74
- readonly moved?: { readonly afterMessageId: string; readonly label: string } | null
98
+ readonly moved?: {
99
+ readonly afterMessageId: string
100
+ readonly label: string
101
+ readonly place?: "cloud" | "computer"
102
+ } | null
103
+ /** Every workspace transition across the conversation, keyed by the message before the move. */
104
+ readonly moves?: ReadonlyMap<string, TranscriptMove>
75
105
  /**
76
106
  * Where its background commands run and what is known of them now, each a card under the work
77
107
  * that started it. Without it, a command its turn no longer runs reads as last seen running.
@@ -167,11 +197,71 @@ function TranscriptView({
167
197
  anchorCurrentTurn,
168
198
  onRetry,
169
199
  onContinue,
200
+ editableMessageIds,
201
+ editingMessage,
202
+ onStartEditMessage,
203
+ onCancelEditMessage,
204
+ onSubmitEditMessage,
170
205
  onNewThread,
171
206
  approvals,
172
207
  moved,
208
+ moves,
173
209
  onAnswer,
174
210
  }: TranscriptProps & { readonly threadDelegation: ThreadDelegation }) {
211
+ const [uncontrolledEdit, setUncontrolledEdit] = useState<AgentMessageEditDraft | null>(null)
212
+ // biome-ignore lint/correctness/useExhaustiveDependencies: reset uncontrolled inline edit when switching threads
213
+ useEffect(() => {
214
+ setUncontrolledEdit(null)
215
+ }, [threadId])
216
+
217
+ const controlledEditing = editingMessage !== undefined
218
+ const activeEdit = controlledEditing ? editingMessage : uncontrolledEdit
219
+
220
+ // Read at click time: the handler stays the same while a reply streams, so the memoized
221
+ // messages keep their props.
222
+ const messagesRef = useRef(messages)
223
+ messagesRef.current = messages
224
+
225
+ const handleStartEdit = useCallback(
226
+ (messageId: string) => {
227
+ if (onStartEditMessage) {
228
+ onStartEditMessage(messageId)
229
+ return
230
+ }
231
+ const target = messagesRef.current.find(
232
+ (entry) => entry.id === messageId && entry.role === "user"
233
+ )
234
+ if (!target) return
235
+ const text = target.parts
236
+ .map((part) => (part.type === "text" ? part.text : ""))
237
+ .join("")
238
+ .trim()
239
+ const attachments = target.parts.flatMap((part) =>
240
+ part.type === "file" ? [part.fileRef] : []
241
+ )
242
+ setUncontrolledEdit({ messageId, text, attachments, context: target.context, nonce: 1 })
243
+ },
244
+ [onStartEditMessage]
245
+ )
246
+
247
+ const handleCancelEdit = useCallback(() => {
248
+ if (onCancelEditMessage) onCancelEditMessage()
249
+ else setUncontrolledEdit(null)
250
+ }, [onCancelEditMessage])
251
+
252
+ const handleSubmitEdit = useCallback(
253
+ (
254
+ messageId: string,
255
+ text: string,
256
+ attachments: readonly AgentFileRef[],
257
+ context: readonly AgentContextEntryInput[]
258
+ ) => {
259
+ if (!controlledEditing) setUncontrolledEdit(null)
260
+ onSubmitEditMessage?.(messageId, text, attachments, context)
261
+ },
262
+ [controlledEditing, onSubmitEditMessage]
263
+ )
264
+
175
265
  // Messages one person sends in a row name them once; an answer in between names them again.
176
266
  const continuedKeys = useMemo(() => continuedUserMessages(messages), [messages])
177
267
 
@@ -269,6 +359,10 @@ function TranscriptView({
269
359
  message.runId && lastOfRun.get(message.runId) === message.key
270
360
  ? unshown.byRun.get(message.runId)
271
361
  : undefined
362
+ // Where the conversation moved after this message: the files it worked on stayed.
363
+ const move =
364
+ (message.id ? moves?.get(message.id) : undefined) ??
365
+ (moved && message.id === moved.afterMessageId ? moved : undefined)
272
366
  return (
273
367
  <Fragment key={message.key}>
274
368
  {index === trailingAt ? trailingCards : null}
@@ -279,6 +373,23 @@ function TranscriptView({
279
373
  message={message}
280
374
  continued={continuedKeys.has(message.key)}
281
375
  scrollAnchor={message.key === anchoredKey}
376
+ canEdit={
377
+ onSubmitEditMessage !== undefined &&
378
+ message.id !== null &&
379
+ (editableMessageIds === undefined || editableMessageIds.has(message.id))
380
+ }
381
+ editing={
382
+ activeEdit !== null && message.id === activeEdit.messageId
383
+ ? activeEdit
384
+ : null
385
+ }
386
+ {...(onSubmitEditMessage
387
+ ? {
388
+ onStartEdit: handleStartEdit,
389
+ onCancelEdit: handleCancelEdit,
390
+ onSubmitEdit: handleSubmitEdit,
391
+ }
392
+ : {})}
282
393
  // Only the newest answer can be continued; older ones keep their notice alone.
283
394
  {...(message.key === newestSavedKey && hasOnContinue
284
395
  ? { onContinue: stableOnContinue, continuing: turn.continuing }
@@ -302,9 +413,9 @@ function TranscriptView({
302
413
  <ApprovalCards calls={calls} />
303
414
  </MessageScrollerItem>
304
415
  ) : null}
305
- {moved && message.id === moved.afterMessageId ? (
306
- <MessageScrollerItem messageId="moved">
307
- <MovedMarker label={moved.label} />
416
+ {move ? (
417
+ <MessageScrollerItem messageId={`moved:${message.id ?? message.key}`}>
418
+ <MovedMarker label={move.label} place={move.place} />
308
419
  </MessageScrollerItem>
309
420
  ) : null}
310
421
  </Fragment>
@@ -441,6 +552,11 @@ const TranscriptMessage = memo(function TranscriptMessage({
441
552
  message,
442
553
  continued,
443
554
  scrollAnchor,
555
+ canEdit = false,
556
+ editing = null,
557
+ onStartEdit,
558
+ onCancelEdit,
559
+ onSubmitEdit,
444
560
  onContinue,
445
561
  continuing,
446
562
  after,
@@ -448,6 +564,16 @@ const TranscriptMessage = memo(function TranscriptMessage({
448
564
  readonly message: AgentConversationMessage
449
565
  readonly continued: boolean
450
566
  readonly scrollAnchor: boolean
567
+ readonly canEdit?: boolean
568
+ readonly editing?: AgentMessageEditDraft | null
569
+ readonly onStartEdit?: (messageId: string) => void
570
+ readonly onCancelEdit?: () => void
571
+ readonly onSubmitEdit?: (
572
+ messageId: string,
573
+ text: string,
574
+ attachments: readonly AgentFileRef[],
575
+ context: readonly AgentContextEntryInput[]
576
+ ) => void
451
577
  readonly onContinue?: () => void
452
578
  readonly continuing?: boolean
453
579
  readonly after?: ReactNode
@@ -466,6 +592,11 @@ const TranscriptMessage = memo(function TranscriptMessage({
466
592
  <MessageView
467
593
  message={message}
468
594
  continued={continued}
595
+ canEdit={canEdit}
596
+ editing={editing}
597
+ onStartEdit={onStartEdit}
598
+ onCancelEdit={onCancelEdit}
599
+ onSubmitEdit={onSubmitEdit}
469
600
  onContinue={onContinue}
470
601
  continuing={continuing}
471
602
  after={trailing}
@@ -96,6 +96,8 @@ export interface AgentConversationMessage {
96
96
  readonly diagnostics: readonly AgentConversationDiagnostic[]
97
97
  /** Earlier turns were condensed before this reply: the summary the agent read instead. */
98
98
  readonly compaction?: NonNullable<AgentMessage["compaction"]>
99
+ /** When the saved message was created (ISO 8601). */
100
+ readonly createdAt?: string
99
101
  /**
100
102
  * A reply whose run ended before finishing it: it failed, or someone stopped it. The turn tells
101
103
  * only of a turn that ended without any answer.
@@ -112,6 +114,8 @@ export interface PendingUserMessage {
112
114
  readonly context: readonly AgentContextEntryInput[]
113
115
  /** The saved message's id, once the API accepted it. */
114
116
  readonly messageId: string | null
117
+ /** When editing an earlier message, the id of the saved message this replaces. */
118
+ readonly replacesMessageId?: string
115
119
  }
116
120
 
117
121
  export interface ConversationMessagesInput {
@@ -163,8 +167,13 @@ export function conversationMessages(input: ConversationMessagesInput): AgentCon
163
167
  }
164
168
  }
165
169
 
170
+ const replaceId = input.pending?.replacesMessageId
171
+ const replaceAt =
172
+ replaceId === undefined ? -1 : input.messages.findIndex((message) => message.id === replaceId)
173
+ const sourceMessages = replaceAt === -1 ? input.messages : input.messages.slice(0, replaceAt)
174
+
166
175
  let lastUserMessageId: string | null = null
167
- for (const message of input.messages) {
176
+ for (const message of sourceMessages) {
168
177
  if (message.role === "system") continue
169
178
 
170
179
  savedIds.add(message.id)
@@ -300,6 +309,7 @@ function savedMessage(
300
309
  ),
301
310
  diagnostics: message.annotations,
302
311
  ...(message.compaction ? { compaction: message.compaction } : {}),
312
+ createdAt: message.createdAt,
303
313
  }
304
314
 
305
315
  const nextEntry: SavedEntry = { key, author, observed, message: converted }
@@ -447,6 +457,11 @@ function liveMessages(
447
457
  savedIds: ReadonlySet<string>,
448
458
  answeredRuns: ReadonlySet<string>
449
459
  ): AgentConversationMessage[] {
460
+ // While an in-place edit is replacing an earlier turn and its new run has not been accepted yet,
461
+ // suppress any live stream left over from the turn being rewound.
462
+ if (input.pending?.replacesMessageId !== undefined && input.pending.messageId === null) {
463
+ return []
464
+ }
450
465
  const live = input.live
451
466
  if (!live || live.runId === null) return []
452
467
  if (live.parts.length === 0 && live.inboxReads.length === 0) return []
@@ -70,6 +70,58 @@ export function relativeTime(
70
70
  return null
71
71
  }
72
72
 
73
+ /**
74
+ * Spoken relative age for a message's hover bar ("just now", "5 minutes ago", "3 days ago"),
75
+ * falling back to a short date after 30 days.
76
+ */
77
+ export function formatMessageTimeAgo(
78
+ iso: string | undefined,
79
+ locale = "en",
80
+ justNow = en.contextMeter.justNow
81
+ ): string {
82
+ if (!iso) return ""
83
+ const then = new Date(iso).getTime()
84
+ if (Number.isNaN(then)) return ""
85
+
86
+ const diffSeconds = Math.max(0, Math.round((Date.now() - then) / 1000))
87
+ if (diffSeconds < 45) return justNow
88
+
89
+ try {
90
+ const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "always", style: "long" })
91
+ const minutes = Math.round(diffSeconds / 60)
92
+ if (minutes < 60) return rtf.format(-Math.max(1, minutes), "minute")
93
+ const hours = Math.round(minutes / 60)
94
+ if (hours < 24) return rtf.format(-Math.max(1, hours), "hour")
95
+ const days = Math.round(hours / 24)
96
+ if (days < 30) return rtf.format(-Math.max(1, days), "day")
97
+ } catch {
98
+ // Fall back to a calendar date if the runtime rejects the locale tag.
99
+ }
100
+
101
+ const date = new Date(then)
102
+ const sameYear = date.getFullYear() === new Date().getFullYear()
103
+ return date.toLocaleDateString(locale, {
104
+ month: "short",
105
+ day: "numeric",
106
+ ...(sameYear ? {} : { year: "numeric" }),
107
+ })
108
+ }
109
+
110
+ /** Exact local timestamp for a message's tooltip, e.g. "Nov 14, 7:55 PM". */
111
+ export function formatMessageTimestamp(iso: string | undefined, locale = "en"): string {
112
+ if (!iso) return ""
113
+ const date = new Date(iso)
114
+ if (Number.isNaN(date.getTime())) return ""
115
+ const sameYear = date.getFullYear() === new Date().getFullYear()
116
+ return date.toLocaleString(locale, {
117
+ month: "short",
118
+ day: "numeric",
119
+ ...(sameYear ? {} : { year: "numeric" }),
120
+ hour: "numeric",
121
+ minute: "2-digit",
122
+ })
123
+ }
124
+
73
125
  /** A token count as a context meter shows it: `950`, `9.5k`, `38k`, `984k`, `1.2M`. */
74
126
  export function formatTokenCount(tokens: number, locale = "en"): string {
75
127
  const decimal = (value: number) => value.toLocaleString(locale, { maximumFractionDigits: 1 })
@@ -0,0 +1,75 @@
1
+ import {
2
+ getAgentThreadOptions,
3
+ listAgentThreadMessagesOptions,
4
+ listAgentThreadRunsOptions,
5
+ } from "@sixb/client/hooks"
6
+ import { type QueryClient, queryOptions, useQueryClient } from "@tanstack/react-query"
7
+ import { useCallback } from "react"
8
+
9
+ /**
10
+ * How long a thread's reads count as fresh. Opening a thread its prefetch just read shows them
11
+ * without reading them again; an event that changes the thread marks them stale, whatever their
12
+ * age (`markThreadReadsStale`).
13
+ */
14
+ const THREAD_READS_FRESH_MS = 30_000
15
+
16
+ /** How long a thread's messages stay cached once nothing shows them: coming back is instant. */
17
+ const THREAD_MESSAGES_CACHE_MS = 30 * 60_000
18
+
19
+ /**
20
+ * The reads opening a thread makes. Opening and prefetching both use these, so they share each
21
+ * query by its key and agree on when it is fresh.
22
+ */
23
+ export function threadQueryOptions(threadId: string) {
24
+ const path = { threadId }
25
+
26
+ return {
27
+ thread: queryOptions({ ...getAgentThreadOptions({ path }), staleTime: THREAD_READS_FRESH_MS }),
28
+ messages: queryOptions({
29
+ ...listAgentThreadMessagesOptions({ path, query: { order: "asc" } }),
30
+ staleTime: THREAD_READS_FRESH_MS,
31
+ gcTime: THREAD_MESSAGES_CACHE_MS,
32
+ }),
33
+ runs: queryOptions({
34
+ ...listAgentThreadRunsOptions({ path, query: { order: "desc" } }),
35
+ staleTime: THREAD_READS_FRESH_MS,
36
+ }),
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Load a thread before it opens, such as when the pointer rests on its link, so opening it shows
42
+ * its messages at once. Reads still fresh are left as they are.
43
+ */
44
+ export function usePrefetchAgentThread(): (threadId: string) => void {
45
+ const queryClient = useQueryClient()
46
+
47
+ return useCallback(
48
+ (threadId: string) => {
49
+ const reads = threadQueryOptions(threadId)
50
+
51
+ void queryClient.prefetchQuery(reads.thread)
52
+ void queryClient.prefetchQuery(reads.messages)
53
+ void queryClient.prefetchQuery(reads.runs)
54
+ },
55
+ [queryClient]
56
+ )
57
+ }
58
+
59
+ /** The operations a thread's reads are cached under, each keyed by the thread it reads. */
60
+ const THREAD_READS = Object.values(threadQueryOptions("")).map((read) => read.queryKey[0]._id)
61
+
62
+ /**
63
+ * Mark a thread's cached reads stale without reading them, or every thread's when no thread is
64
+ * named: whatever shows one next reads it again. A thread nobody has open learns of a change this
65
+ * way, from an activity event or the feed reconnecting, since its reads stay fresh for a while once
66
+ * read and nothing else would read them again.
67
+ */
68
+ export function markThreadReadsStale(queryClient: QueryClient, threadId?: string): void {
69
+ for (const _id of THREAD_READS) {
70
+ void queryClient.invalidateQueries({
71
+ queryKey: [threadId === undefined ? { _id } : { _id, path: { threadId } }],
72
+ refetchType: "none",
73
+ })
74
+ }
75
+ }