@sixb/client 0.1.23 → 0.2.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 (63) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-streams.d.ts +9 -2
  3. package/dist/agent-streams.d.ts.map +1 -1
  4. package/dist/browser.js +2 -2
  5. package/dist/browser.js.map +1 -1
  6. package/dist/{chunk-263m4e9p.js → chunk-1wdszw1c.js} +19 -13
  7. package/dist/{chunk-263m4e9p.js.map → chunk-1wdszw1c.js.map} +5 -5
  8. package/dist/{chunk-59f4fbnk.js → chunk-2qsekqcn.js} +108 -51
  9. package/dist/chunk-2qsekqcn.js.map +19 -0
  10. package/dist/{chunk-k2j71x7a.js → chunk-fnd56xxz.js} +2 -2
  11. package/dist/{chunk-k2j71x7a.js.map → chunk-fnd56xxz.js.map} +1 -1
  12. package/dist/chunk-j9t5h44d.js.map +1 -1
  13. package/dist/{chunk-9gz30dxy.js → chunk-mk0w4zr1.js} +1 -1
  14. package/dist/{chunk-9gz30dxy.js.map → chunk-mk0w4zr1.js.map} +1 -1
  15. package/dist/{chunk-tttfv49k.js → chunk-s2pagg09.js} +52 -4
  16. package/dist/chunk-s2pagg09.js.map +11 -0
  17. package/dist/{chunk-1v736aje.js → chunk-sh0f609h.js} +1 -1
  18. package/dist/connectors/queries.d.ts.map +1 -1
  19. package/dist/generated/@tanstack/react-query.gen.d.ts +2443 -96
  20. package/dist/generated/@tanstack/react-query.gen.d.ts.map +1 -1
  21. package/dist/generated/index.d.ts +2 -2
  22. package/dist/generated/index.d.ts.map +1 -1
  23. package/dist/generated/sdk.gen.d.ts +48 -16
  24. package/dist/generated/sdk.gen.d.ts.map +1 -1
  25. package/dist/generated/types.gen.d.ts +1233 -268
  26. package/dist/generated/types.gen.d.ts.map +1 -1
  27. package/dist/hooks.d.ts +3 -1
  28. package/dist/hooks.d.ts.map +1 -1
  29. package/dist/hooks.js +359 -77
  30. package/dist/hooks.js.map +9 -7
  31. package/dist/index.js +23 -15
  32. package/dist/index.js.map +1 -1
  33. package/dist/logs.js +3 -3
  34. package/dist/models.js +19 -11
  35. package/dist/models.js.map +1 -1
  36. package/dist/object-query-live-updates.d.ts +34 -0
  37. package/dist/object-query-live-updates.d.ts.map +1 -0
  38. package/dist/object-query-reads.d.ts +8 -0
  39. package/dist/object-query-reads.d.ts.map +1 -0
  40. package/dist/query.d.ts.map +1 -1
  41. package/dist/query.js +3 -3
  42. package/dist/useAgentActivityStream.d.ts +4 -1
  43. package/dist/useAgentActivityStream.d.ts.map +1 -1
  44. package/dist/useDesktop.d.ts +22 -0
  45. package/dist/useDesktop.d.ts.map +1 -0
  46. package/dist/users-hooks.d.ts +9 -5
  47. package/dist/users-hooks.d.ts.map +1 -1
  48. package/package.json +2 -2
  49. package/src/agent-streams.ts +16 -2
  50. package/src/generated/@tanstack/react-query.gen.ts +241 -106
  51. package/src/generated/index.ts +47 -24
  52. package/src/generated/sdk.gen.ts +222 -85
  53. package/src/generated/types.gen.ts +1394 -245
  54. package/src/hooks.ts +6 -0
  55. package/src/object-query-live-updates.ts +276 -0
  56. package/src/object-query-reads.ts +72 -0
  57. package/src/query.ts +5 -0
  58. package/src/useAgentActivityStream.ts +11 -0
  59. package/src/useDesktop.ts +50 -0
  60. package/src/users-hooks.ts +36 -5
  61. package/dist/chunk-59f4fbnk.js.map +0 -19
  62. package/dist/chunk-tttfv49k.js.map +0 -10
  63. /package/dist/{chunk-1v736aje.js.map → chunk-sh0f609h.js.map} +0 -0
package/src/hooks.ts CHANGED
@@ -25,6 +25,10 @@ export * from "./events-hooks"
25
25
  export * from "./events-provider"
26
26
  export * from "./generated/@tanstack/react-query.gen"
27
27
  export * from "./logs-hooks"
28
+ export {
29
+ type UseObjectQueryLiveUpdatesOptions,
30
+ useObjectQueryLiveUpdates,
31
+ } from "./object-query-live-updates"
28
32
  export * from "./query-hooks"
29
33
  export {
30
34
  type UseAgentActivityStreamOptions,
@@ -36,7 +40,9 @@ export {
36
40
  type UseAgentRunStreamResult,
37
41
  useAgentRunStream,
38
42
  } from "./useAgentRunStream"
43
+ export { type DesktopPlatform, type SixbDesktop, useDesktop } from "./useDesktop"
39
44
  export {
45
+ type UserLookupInput,
40
46
  type UseUserOptions,
41
47
  type UseUsersOptions,
42
48
  userQueryOptions,
@@ -0,0 +1,276 @@
1
+ import { type Query, type QueryClient, useQueryClient } from "@tanstack/react-query"
2
+ import { startTransition, useEffect, useRef } from "react"
3
+ import { useSixbProviderClient } from "./client-provider"
4
+ import { events } from "./events"
5
+ import { useEvents } from "./events-hooks"
6
+ import { objectQueryReadsAny } from "./object-query-reads"
7
+ import { objectQueryKeys } from "./query-hooks"
8
+
9
+ const DEFAULT_WINDOW_MS = 1_000
10
+ const MINIMUM_WINDOW_MS = 100
11
+
12
+ /** Every view hears the same events, so what they gather is kept per cache. */
13
+ interface LiveUpdates {
14
+ /** The mounted, enabled hooks. With none left, nothing should refresh. */
15
+ listeners: number
16
+ /** The API client whose answers say what each query reads. */
17
+ client: object | undefined
18
+ /** Events may have been missed, so any query could have changed. */
19
+ everything: boolean
20
+ /** Types changed since the last refresh. */
21
+ readonly changed: Set<string>
22
+ /**
23
+ * Queries a change reached while they were fetching, by hash, with the types that changed: what
24
+ * they are reading may predate it. A query with no answer yet can then turn out not to read them.
25
+ */
26
+ readonly rereads: Map<string, ReadonlySet<string> | "everything">
27
+ windowMs: number
28
+ cancel?: () => void
29
+ }
30
+
31
+ const liveUpdates = new WeakMap<QueryClient, LiveUpdates>()
32
+
33
+ function liveUpdatesOf(queryClient: QueryClient): LiveUpdates {
34
+ let state = liveUpdates.get(queryClient)
35
+ if (!state) {
36
+ state = {
37
+ listeners: 0,
38
+ client: undefined,
39
+ everything: false,
40
+ changed: new Set(),
41
+ rereads: new Map(),
42
+ windowMs: DEFAULT_WINDOW_MS,
43
+ }
44
+ liveUpdates.set(queryClient, state)
45
+ }
46
+ return state
47
+ }
48
+
49
+ export interface UseObjectQueryLiveUpdatesOptions {
50
+ /** Stop listening, for a view that must not refresh. Defaults to true. */
51
+ readonly enabled?: boolean
52
+ /** Refresh at most once per this long while changes arrive. Defaults to one second. */
53
+ readonly windowMs?: number
54
+ /** Told when the event stream fails, such as when a session ends: queries then stop refreshing. */
55
+ readonly onError?: (error: unknown) => void
56
+ }
57
+
58
+ /**
59
+ * Keeps cached object queries current while they are shown: mount it once, near the root.
60
+ *
61
+ * Object events name their type, link events their source's and target's. A query refreshes when
62
+ * it reads one of them, through its filters, traversals or expansions. Changes gather for the
63
+ * window, and for as long as the page is hidden, so a burst of writes refreshes each query at most
64
+ * once per window. A query already fetching finishes first, then reads again.
65
+ *
66
+ * In a standalone browser app, wrap this in `SixbEventsProvider` so its two subscriptions share one
67
+ * connection.
68
+ */
69
+ export function useObjectQueryLiveUpdates(options: UseObjectQueryLiveUpdatesOptions = {}): void {
70
+ const queryClient = useQueryClient()
71
+ const client = useSixbProviderClient()
72
+ const { enabled = true, windowMs = DEFAULT_WINDOW_MS, onError } = options
73
+ const subscription = client ? { client } : undefined
74
+
75
+ useEffect(() => {
76
+ if (!enabled) return
77
+ return listenToObjectQueryChanges(queryClient, client)
78
+ }, [enabled, queryClient, client])
79
+
80
+ const objectStream = useEvents(
81
+ events.objects(subscription),
82
+ (event) => noteObjectTypesChanged(queryClient, [event.payload.objectTypeId], windowMs),
83
+ { enabled, onError }
84
+ )
85
+ const linkStream = useEvents(
86
+ events.links(subscription),
87
+ (event) =>
88
+ noteObjectTypesChanged(
89
+ queryClient,
90
+ [event.payload.sourceTypeId, event.payload.targetTypeId],
91
+ windowMs
92
+ ),
93
+ { enabled, onError }
94
+ )
95
+
96
+ // Per hook: another view mounting starts disconnected, which says nothing about this stream.
97
+ const streams = useRef<Record<string, EventStreamHistory>>({})
98
+ useEffect(() => {
99
+ for (const [name, connected] of [
100
+ ["objects", objectStream.connected],
101
+ ["links", linkStream.connected],
102
+ ] as const) {
103
+ streams.current[name] = noteEventStreamConnected(
104
+ queryClient,
105
+ streams.current[name],
106
+ connected,
107
+ windowMs
108
+ )
109
+ }
110
+ }, [queryClient, objectStream.connected, linkStream.connected, windowMs])
111
+ }
112
+
113
+ export interface EventStreamHistory {
114
+ readonly connected: boolean
115
+ readonly everConnected: boolean
116
+ }
117
+
118
+ /** Events sent during a dropped connection may never arrive, so anything could have changed. */
119
+ export function noteEventStreamConnected(
120
+ queryClient: QueryClient,
121
+ history: EventStreamHistory | undefined,
122
+ connected: boolean,
123
+ windowMs: number = DEFAULT_WINDOW_MS
124
+ ): EventStreamHistory {
125
+ if (connected && history?.everConnected && !history.connected) {
126
+ const state = liveUpdatesOf(queryClient)
127
+ if (state.listeners > 0) {
128
+ state.everything = true
129
+ state.windowMs = Math.max(windowMs, MINIMUM_WINDOW_MS)
130
+ schedule(queryClient, state)
131
+ }
132
+ }
133
+ return { connected, everConnected: connected || (history?.everConnected ?? false) }
134
+ }
135
+
136
+ /**
137
+ * Returns the way to stop. The last listener to leave cancels the pending refresh, and marks what
138
+ * it would have refreshed as stale: those events are gone, so the next mount must read again.
139
+ */
140
+ export function listenToObjectQueryChanges(queryClient: QueryClient, client?: object): () => void {
141
+ const state = liveUpdatesOf(queryClient)
142
+ state.listeners += 1
143
+ state.client = client
144
+
145
+ if (state.rereads.size > 0) schedule(queryClient, state)
146
+
147
+ return () => {
148
+ state.listeners -= 1
149
+ if (state.listeners > 0) return
150
+
151
+ state.cancel?.()
152
+ const stale = staleQueries(queryClient, state)
153
+ const everything = state.everything
154
+ const changed = new Set(state.changed)
155
+ state.changed.clear()
156
+ state.everything = false
157
+ state.rereads.clear()
158
+ if (stale.length === 0) return
159
+
160
+ // Those events are gone, so these stay due for the next listener. A mark alone would not do: it
161
+ // does not read an active query again, and a read in flight would clear it when it lands.
162
+ for (const query of stale) {
163
+ state.rereads.set(query.queryHash, everything ? "everything" : changed)
164
+ }
165
+ const hashes = new Set(stale.map((query) => query.queryHash))
166
+ void queryClient.invalidateQueries({
167
+ queryKey: objectQueryKeys.all(),
168
+ refetchType: "none",
169
+ predicate: (query) => hashes.has(query.queryHash),
170
+ })
171
+ }
172
+ }
173
+
174
+ function isFetching(query: Query): boolean {
175
+ return query.state.fetchStatus === "fetching"
176
+ }
177
+
178
+ function staleQueries(queryClient: QueryClient, state: LiveUpdates): Query[] {
179
+ return queryClient
180
+ .getQueryCache()
181
+ .findAll({ queryKey: objectQueryKeys.all() })
182
+ .filter((query) => {
183
+ if (state.everything) return true
184
+ if (
185
+ state.changed.size > 0 &&
186
+ objectQueryReadsAny(state.client, query.queryKey[3], state.changed)
187
+ ) {
188
+ return true
189
+ }
190
+ const reread = state.rereads.get(query.queryHash)
191
+ return (
192
+ reread === "everything" ||
193
+ (reread !== undefined && objectQueryReadsAny(state.client, query.queryKey[3], reread))
194
+ )
195
+ })
196
+ }
197
+
198
+ export function noteObjectTypesChanged(
199
+ queryClient: QueryClient,
200
+ objectTypeIds: readonly string[],
201
+ windowMs: number = DEFAULT_WINDOW_MS
202
+ ): void {
203
+ const state = liveUpdatesOf(queryClient)
204
+ if (state.listeners === 0) return
205
+
206
+ state.windowMs = Math.max(windowMs, MINIMUM_WINDOW_MS)
207
+ for (const objectTypeId of objectTypeIds) state.changed.add(objectTypeId)
208
+ schedule(queryClient, state)
209
+ }
210
+
211
+ function schedule(queryClient: QueryClient, state: LiveUpdates): void {
212
+ if (state.cancel) return
213
+
214
+ const timer = setTimeout(() => {
215
+ state.cancel = undefined
216
+ refreshWhenVisible(queryClient, state)
217
+ }, state.windowMs)
218
+ state.cancel = () => {
219
+ clearTimeout(timer)
220
+ state.cancel = undefined
221
+ }
222
+ }
223
+
224
+ function refreshWhenVisible(queryClient: QueryClient, state: LiveUpdates): void {
225
+ if (globalThis.document?.visibilityState !== "hidden") {
226
+ refresh(queryClient, state)
227
+ return
228
+ }
229
+
230
+ const showAgain = () => {
231
+ state.cancel = undefined
232
+ refreshWhenVisible(queryClient, state)
233
+ }
234
+ document.addEventListener("visibilitychange", showAgain, { once: true })
235
+ state.cancel = () => {
236
+ document.removeEventListener("visibilitychange", showAgain)
237
+ state.cancel = undefined
238
+ }
239
+ }
240
+
241
+ function refresh(queryClient: QueryClient, state: LiveUpdates): void {
242
+ const stale = staleQueries(queryClient, state)
243
+ const everything = state.everything
244
+ const changed = new Set(state.changed)
245
+ const earlier = new Map(state.rereads)
246
+ state.changed.clear()
247
+ state.everything = false
248
+ state.rereads.clear()
249
+
250
+ // Restarting a slow read for each window would mean it never finishes during a burst, and the
251
+ // server would keep running every read it abandoned. It finishes, then reads again if what it
252
+ // turns out to read changed.
253
+ const ready = new Set<string>()
254
+ for (const query of stale) {
255
+ if (!isFetching(query)) {
256
+ ready.add(query.queryHash)
257
+ continue
258
+ }
259
+ const before = earlier.get(query.queryHash)
260
+ state.rereads.set(
261
+ query.queryHash,
262
+ everything || before === "everything"
263
+ ? "everything"
264
+ : new Set([...(before ?? []), ...changed])
265
+ )
266
+ }
267
+ if (state.rereads.size > 0) schedule(queryClient, state)
268
+ if (ready.size === 0) return
269
+
270
+ startTransition(() => {
271
+ void queryClient.invalidateQueries({
272
+ queryKey: objectQueryKeys.all(),
273
+ predicate: (query) => ready.has(query.queryHash),
274
+ })
275
+ })
276
+ }
@@ -0,0 +1,72 @@
1
+ import type { ObjectQuery } from "@sixb/core"
2
+
3
+ const MAX_REMEMBERED_QUERIES = 1_000
4
+
5
+ /** Reads are per API client: the same query can read different types in another project. */
6
+ const readsByClient = new WeakMap<object, Map<string, readonly string[]>>()
7
+ const DEFAULT_CLIENT = {}
8
+
9
+ /** Two queries that differ only in property order share one cache entry, and so one key here. */
10
+ const keys = new WeakMap<object, string>()
11
+
12
+ function queryKey(query: object): string {
13
+ let key = keys.get(query)
14
+ if (key === undefined) {
15
+ key = JSON.stringify(query, (_name, value: unknown) =>
16
+ value && typeof value === "object" && !Array.isArray(value)
17
+ ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : 1)))
18
+ : value
19
+ )
20
+ keys.set(query, key)
21
+ }
22
+ return key
23
+ }
24
+
25
+ /** Any page of a query reads the same types as the query it pages through. */
26
+ function withoutPage<TQuery extends object>(query: TQuery): object {
27
+ return (query as { kind?: unknown }).kind === "page"
28
+ ? (query as unknown as { input: object }).input
29
+ : query
30
+ }
31
+
32
+ function readsOf(client: object | undefined): Map<string, readonly string[]> {
33
+ const owner = client ?? DEFAULT_CLIENT
34
+ let reads = readsByClient.get(owner)
35
+ if (!reads) {
36
+ reads = new Map()
37
+ readsByClient.set(owner, reads)
38
+ }
39
+ return reads
40
+ }
41
+
42
+ export function rememberObjectQueryReads(
43
+ client: object | undefined,
44
+ query: ObjectQuery,
45
+ objectTypeIds: readonly string[] | undefined
46
+ ): void {
47
+ const reads = readsOf(client)
48
+ const key = queryKey(withoutPage(query))
49
+
50
+ // Oldest first, so the most recently answered queries are the ones kept.
51
+ reads.delete(key)
52
+ if (objectTypeIds) reads.set(key, objectTypeIds)
53
+ if (reads.size > MAX_REMEMBERED_QUERIES) {
54
+ const oldest = reads.keys().next().value
55
+ if (oldest !== undefined) reads.delete(oldest)
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Whether a change to these object types can change this cached query's result. A query not known
61
+ * here has not answered yet, or has been forgotten, so it counts as reading everything.
62
+ */
63
+ export function objectQueryReadsAny(
64
+ client: object | undefined,
65
+ query: unknown,
66
+ changed: ReadonlySet<string>
67
+ ): boolean {
68
+ if (!query || typeof query !== "object") return true
69
+
70
+ const reads = readsOf(client).get(queryKey(withoutPage(query)))
71
+ return reads === undefined || reads.some((objectTypeId) => changed.has(objectTypeId))
72
+ }
package/src/query.ts CHANGED
@@ -35,6 +35,7 @@ import type {
35
35
  ObjectQueryObject,
36
36
  ObjectQuery as WireObjectQuery,
37
37
  } from "./generated/types.gen"
38
+ import { rememberObjectQueryReads } from "./object-query-reads"
38
39
 
39
40
  export type { ObjectQueryIssue }
40
41
  export type { CurrentUserRef } from "@sixb/core/ontology"
@@ -155,6 +156,7 @@ export function createHttpQueryExecutor(client?: Client): ObjectQueryExecutor {
155
156
  signal: options?.signal,
156
157
  })
157
158
  if (error || !data) throw toSixbQueryError(error)
159
+ rememberObjectQueryReads(client, query, data.plan?.readObjectTypeIds)
158
160
  return {
159
161
  objects: data.objects.map(reviveQueryRow),
160
162
  hasMore: data.hasMore,
@@ -169,6 +171,7 @@ export function createHttpQueryExecutor(client?: Client): ObjectQueryExecutor {
169
171
  body: { query: toWireQuery(query) },
170
172
  })
171
173
  if (error || !data) throw toSixbQueryError(error)
174
+ rememberObjectQueryReads(client, query, data.plan?.readObjectTypeIds)
172
175
  return data.count
173
176
  },
174
177
 
@@ -178,6 +181,7 @@ export function createHttpQueryExecutor(client?: Client): ObjectQueryExecutor {
178
181
  body: { query: toWireQuery(query) },
179
182
  })
180
183
  if (error || !data) throw toSixbQueryError(error)
184
+ rememberObjectQueryReads(client, query, data.plan?.readObjectTypeIds)
181
185
  return data.exists
182
186
  },
183
187
 
@@ -187,6 +191,7 @@ export function createHttpQueryExecutor(client?: Client): ObjectQueryExecutor {
187
191
  body: { query: toWireQuery(query), facets: [...facets] },
188
192
  })
189
193
  if (error || !data) throw toSixbQueryError(error)
194
+ rememberObjectQueryReads(client, query, data.plan?.readObjectTypeIds)
190
195
  return {
191
196
  total: data.total,
192
197
  facets: data.facets.map((facet) => ({
@@ -1,7 +1,9 @@
1
1
  import { useEffect, useRef, useState } from "react"
2
2
  import {
3
3
  type AgentApprovalActivityEvent,
4
+ type AgentComputerActivityEvent,
4
5
  type AgentRunActivityEvent,
6
+ type AgentThreadMovedEvent,
5
7
  createAgentActivitySocket,
6
8
  } from "./agent-streams"
7
9
  import type { Client } from "./generated/client"
@@ -16,6 +18,9 @@ export interface UseAgentActivityStreamOptions {
16
18
  readonly onActivity?: (event: AgentRunActivityEvent) => void
17
19
  /** One of a turn's held calls was held, decided, ran, or was set aside. */
18
20
  readonly onApprovalActivity?: (event: AgentApprovalActivityEvent) => void
21
+ /** `sixb` opened or closed on one of your computers, in a folder. */
22
+ readonly onComputerActivity?: (event: AgentComputerActivityEvent) => void
23
+ readonly onThreadMoved?: (event: AgentThreadMovedEvent) => void
19
24
  readonly onSubscribed?: () => void
20
25
  readonly onError?: (message: string) => void
21
26
  }
@@ -33,6 +38,10 @@ export function useAgentActivityStream(
33
38
  onActivityRef.current = options.onActivity
34
39
  const onApprovalActivityRef = useRef(options.onApprovalActivity)
35
40
  onApprovalActivityRef.current = options.onApprovalActivity
41
+ const onComputerActivityRef = useRef(options.onComputerActivity)
42
+ onComputerActivityRef.current = options.onComputerActivity
43
+ const onThreadMovedRef = useRef(options.onThreadMoved)
44
+ onThreadMovedRef.current = options.onThreadMoved
36
45
  const onSubscribedRef = useRef(options.onSubscribed)
37
46
  onSubscribedRef.current = options.onSubscribed
38
47
  const onErrorRef = useRef(options.onError)
@@ -50,6 +59,8 @@ export function useAgentActivityStream(
50
59
  client,
51
60
  onActivity: (event) => onActivityRef.current?.(event),
52
61
  onApprovalActivity: (event) => onApprovalActivityRef.current?.(event),
62
+ onComputerActivity: (event) => onComputerActivityRef.current?.(event),
63
+ onThreadMoved: (event) => onThreadMovedRef.current?.(event),
53
64
  onSubscribed: () => onSubscribedRef.current?.(),
54
65
  onError: (message) => onErrorRef.current?.(message),
55
66
  onStateChange: setState,
@@ -0,0 +1,50 @@
1
+ import { useSyncExternalStore } from "react"
2
+
3
+ /** The systems a desktop app runs on. */
4
+ export type DesktopPlatform = "darwin" | "win32" | "linux"
5
+
6
+ /**
7
+ * What the desktop app around this page offers it. The shell sets it before the page's first
8
+ * script, and it never changes while the page is open.
9
+ *
10
+ * A deploy reaches an installed desktop app at once, while the shell stays as it was built. So a
11
+ * page can run inside a shell older than itself: anything added here is optional, and a page checks
12
+ * for it rather than for a version.
13
+ */
14
+ export interface SixbDesktop {
15
+ readonly platform: DesktopPlatform
16
+ }
17
+
18
+ const PLATFORMS: readonly unknown[] = ["darwin", "win32", "linux"] satisfies DesktopPlatform[]
19
+
20
+ function isSixbDesktop(value: unknown): value is SixbDesktop {
21
+ return (
22
+ typeof value === "object" &&
23
+ value !== null &&
24
+ PLATFORMS.includes((value as { readonly platform?: unknown }).platform)
25
+ )
26
+ }
27
+
28
+ function readDesktop(): SixbDesktop | null {
29
+ const { sixbDesktop } = globalThis as { readonly sixbDesktop?: unknown }
30
+ return isSixbDesktop(sixbDesktop) ? sixbDesktop : null
31
+ }
32
+
33
+ function readNoDesktop(): null {
34
+ return null
35
+ }
36
+
37
+ function subscribeToNothing(): () => void {
38
+ return () => {}
39
+ }
40
+
41
+ /**
42
+ * The desktop app this page runs in, or null in a browser and in a desktop app built before this
43
+ * existed. Right from the first render, so nothing flickers.
44
+ *
45
+ * It decides what to show, and grants nothing: a page can set this value itself. The shell's main
46
+ * process checks whatever a desktop feature does.
47
+ */
48
+ export function useDesktop(): SixbDesktop | null {
49
+ return useSyncExternalStore(subscribeToNothing, readDesktop, readNoDesktop)
50
+ }
@@ -33,11 +33,18 @@ export function usersQueryOptions(options: UseUsersOptions = {}) {
33
33
  })
34
34
  }
35
35
 
36
+ /** A member by user reference, id, or email: the email matches exactly, ignoring case. */
37
+ export type UserLookupInput = UserRef | string | { readonly email: string }
38
+
36
39
  /**
37
40
  * Query options for one member, for prefetching or `useQuery`. The data is `null` when no member
38
- * has this id or the reader cannot read the directory.
41
+ * has this id or email, or the reader cannot read the directory.
39
42
  */
40
- export function userQueryOptions(user: UserRef | string, options: UseUserOptions = {}) {
43
+ export function userQueryOptions(user: UserLookupInput, options: UseUserOptions = {}) {
44
+ if (typeof user === "object" && "email" in user) {
45
+ return userByEmailQueryOptions(user.email, options)
46
+ }
47
+
41
48
  const { client, ...extras } = options
42
49
  const path = { userId: typeof user === "string" ? user : user.id }
43
50
 
@@ -63,6 +70,30 @@ export function userQueryOptions(user: UserRef | string, options: UseUserOptions
63
70
  })
64
71
  }
65
72
 
73
+ function userByEmailQueryOptions(email: string, options: UseUserOptions) {
74
+ const { client, ...extras } = options
75
+ // The server ignores case, so the cache does too.
76
+ const query = { email: email.trim().toLowerCase() }
77
+
78
+ return queryOptions<GetUserResponse | null, Error>({
79
+ ...extras,
80
+ queryKey: [{ _id: "user", query }] as const,
81
+ queryFn: async ({ signal }) => {
82
+ const { data, error, response } = await listUsers({
83
+ client,
84
+ query,
85
+ signal,
86
+ responseStyle: "fields",
87
+ throwOnError: false,
88
+ })
89
+ if (response?.status === 403) return null
90
+ if (error !== undefined) throw error
91
+
92
+ return data.users[0] ?? null
93
+ },
94
+ })
95
+ }
96
+
66
97
  /**
67
98
  * One page of the project's member directory, active members by default. Pass `status: "all"`
68
99
  * to include suspended members. Reading it requires `can.view(project.users)`.
@@ -74,11 +105,11 @@ export function useUsers(options: UseUsersOptions = {}): UseQueryResult<ListUser
74
105
  }
75
106
 
76
107
  /**
77
- * One member of the directory, from a user reference or an id: `null` when no member has it, or
78
- * without `can.view(project.users)`.
108
+ * One member of the directory, from a user reference, an id, or `{ email }`: `null` when no member
109
+ * has it, or without `can.view(project.users)`.
79
110
  */
80
111
  export function useUser(
81
- user: UserRef | string,
112
+ user: UserLookupInput,
82
113
  options: UseUserOptions = {}
83
114
  ): UseQueryResult<GetUserResponse | null, Error> {
84
115
  const providerClient = useSixbProviderClient()