@notis_ai/cli 0.2.25 → 0.2.26

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 (157) hide show
  1. package/README.md +186 -5
  2. package/config/notis_app_design_rules.json +36 -14
  3. package/config/portal-route-roots.json +1 -0
  4. package/dist/agent-hooks/notis-agent-hook.mjs +2784 -541
  5. package/dist/base-skills/notis-cli/.notis-base-skill.json +1 -1
  6. package/dist/base-skills/notis-cli/references/intelligence.md +1 -1
  7. package/dist/base-skills/notis-query/.notis-base-skill.json +1 -1
  8. package/dist/base-skills/notis-query/SKILL.md +0 -1
  9. package/dist/base-skills/notis-query/references/documents.md +7 -0
  10. package/dist/base-skills/notis-query/references/query.md +1 -0
  11. package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
  12. package/dist/base-skills/notis-spaces/SKILL.md +96 -24
  13. package/dist/base-skills/notis-spaces/references/architecture.md +4 -3
  14. package/dist/base-skills/notis-spaces/references/design.md +37 -18
  15. package/dist/base-skills/notis-spaces/references/reading.md +8 -1
  16. package/dist/base-skills/notis-spaces/references/reports.md +6 -6
  17. package/dist/base-skills/notis-spaces/references/sdk.md +71 -7
  18. package/dist/base-skills/notis-spaces/references/store.md +22 -13
  19. package/dist/base-skills/notis-spaces/references/views.md +99 -6
  20. package/dist/sdk/package.json +3 -0
  21. package/dist/sdk/src/cloudComputerWords.ts +53 -0
  22. package/dist/sdk/src/components/Audience.tsx +76 -0
  23. package/dist/sdk/src/components/DocumentPage.tsx +15 -4
  24. package/dist/sdk/src/components/MarkdownEditor.tsx +44 -14
  25. package/dist/sdk/src/components/MultiSelectActionBar.tsx +16 -5
  26. package/dist/sdk/src/components/Skeleton.tsx +162 -6
  27. package/dist/sdk/src/hooks/useAction.ts +12 -2
  28. package/dist/sdk/src/hooks/useAgentQueue.ts +125 -0
  29. package/dist/sdk/src/hooks/useCloudComputerJob.ts +142 -0
  30. package/dist/sdk/src/hooks/useCloudComputerService.ts +388 -0
  31. package/dist/sdk/src/hooks/useCloudComputerShell.ts +95 -7
  32. package/dist/sdk/src/hooks/useCollectionInteractions.ts +40 -2
  33. package/dist/sdk/src/hooks/useItemThread.ts +58 -0
  34. package/dist/sdk/src/hooks/useMarqueeSelection.ts +6 -1
  35. package/dist/sdk/src/hooks/useNativeDocuments.ts +61 -8
  36. package/dist/sdk/src/hooks/useNotisNavigation.ts +31 -8
  37. package/dist/sdk/src/hooks/useQuery.ts +67 -10
  38. package/dist/sdk/src/hooks/useViewParams.ts +47 -11
  39. package/dist/sdk/src/index.ts +31 -4
  40. package/dist/sdk/src/interactions.ts +2 -0
  41. package/dist/sdk/src/nativeData.ts +2 -0
  42. package/dist/sdk/src/optimisticRows.ts +329 -0
  43. package/dist/sdk/src/perf.ts +188 -0
  44. package/dist/sdk/src/provider.tsx +2 -1
  45. package/dist/sdk/src/queryCache.ts +366 -17
  46. package/dist/sdk/src/runtime.ts +55 -4
  47. package/dist/sdk/src/skeleton.ts +103 -0
  48. package/dist/sdk/src/space.ts +662 -28
  49. package/dist/sdk/src/spacePublicUI.ts +36 -0
  50. package/dist/sdk/src/ui/engine/step.ts +54 -0
  51. package/dist/sdk/src/ui/icons.tsx +3 -1
  52. package/dist/sdk/src/words/shell.ts +1 -0
  53. package/dist/skill-sync/index.js +7 -2
  54. package/dist/skill-sync-worker.mjs +40 -26
  55. package/dist/space-harness/host.js +272 -105
  56. package/dist/space-sdk/dist/chunk-BWHAORT4.js +5 -0
  57. package/dist/space-sdk/dist/index.js +9 -4
  58. package/dist/space-sdk/dist/ui.js +12 -12
  59. package/dist/space-sdk/package.json +3 -0
  60. package/dist/space-sdk/src/cloudComputerWords.d.ts +34 -0
  61. package/dist/space-sdk/src/components/Audience.d.ts +46 -0
  62. package/dist/space-sdk/src/components/DocumentPage.d.ts +3 -1
  63. package/dist/space-sdk/src/components/MarkdownEditor.d.ts +21 -0
  64. package/dist/space-sdk/src/components/MultiSelectActionBar.d.ts +5 -1
  65. package/dist/space-sdk/src/components/Skeleton.d.ts +7 -2
  66. package/dist/space-sdk/src/hooks/useAction.d.ts +8 -1
  67. package/dist/space-sdk/src/hooks/useAgentQueue.d.ts +61 -0
  68. package/dist/space-sdk/src/hooks/useCloudComputerJob.d.ts +35 -0
  69. package/dist/space-sdk/src/hooks/useCloudComputerService.d.ts +75 -0
  70. package/dist/space-sdk/src/hooks/useCloudComputerShell.d.ts +36 -3
  71. package/dist/space-sdk/src/hooks/useCollectionInteractions.d.ts +6 -0
  72. package/dist/space-sdk/src/hooks/useItemThread.d.ts +32 -0
  73. package/dist/space-sdk/src/hooks/useMarqueeSelection.d.ts +2 -1
  74. package/dist/space-sdk/src/hooks/useNativeDocumentBody.d.ts +1 -0
  75. package/dist/space-sdk/src/hooks/useNativeDocuments.d.ts +20 -5
  76. package/dist/space-sdk/src/hooks/useNotisNavigation.d.ts +11 -2
  77. package/dist/space-sdk/src/hooks/useQuery.d.ts +24 -2
  78. package/dist/space-sdk/src/hooks/useViewParams.d.ts +2 -0
  79. package/dist/space-sdk/src/index.d.ts +24 -4
  80. package/dist/space-sdk/src/nativeData.d.ts +6 -0
  81. package/dist/space-sdk/src/queryCache.d.ts +97 -2
  82. package/dist/space-sdk/src/runtime.d.ts +53 -4
  83. package/dist/space-sdk/src/skeleton.d.ts +42 -0
  84. package/dist/space-sdk/src/space.ts +662 -28
  85. package/dist/space-sdk/src/tailwind-candidates.d.ts +754 -5
  86. package/dist/space-sdk/src/ui/cloud/CloudComputerFrame.d.ts +29 -0
  87. package/dist/space-sdk/src/ui/cloud/CloudComputerWaking.d.ts +20 -0
  88. package/dist/space-sdk/src/ui/comments/CommentPane.d.ts +15 -2
  89. package/dist/space-sdk/src/ui/comments/PassageComments.d.ts +50 -0
  90. package/dist/space-sdk/src/ui/comments/commentFiles.d.ts +64 -0
  91. package/dist/space-sdk/src/ui/comments/commentModel.d.ts +49 -1
  92. package/dist/space-sdk/src/ui/comments/commentWords.d.ts +26 -0
  93. package/dist/space-sdk/src/ui/comments/index.d.ts +4 -0
  94. package/dist/space-sdk/src/ui/comments/passageModel.d.ts +82 -0
  95. package/dist/space-sdk/src/ui/comments/useComments.d.ts +34 -4
  96. package/dist/space-sdk/src/ui/comments/usePassageComments.d.ts +67 -0
  97. package/dist/space-sdk/src/ui/engine/index.d.ts +2 -2
  98. package/dist/space-sdk/src/ui/engine/step.d.ts +9 -0
  99. package/dist/space-sdk/src/ui/fields/fields.d.ts +2 -1
  100. package/dist/space-sdk/src/ui/index.d.ts +4 -0
  101. package/dist/space-sdk/src/ui/layout/Panels.d.ts +9 -2
  102. package/dist/space-sdk/src/ui/layout/SidePane.d.ts +42 -0
  103. package/dist/space-sdk/src/ui/layout/index.d.ts +2 -1
  104. package/dist/space-sdk/src/ui/layout/panelMath.d.ts +11 -2
  105. package/dist/space-sdk/src/ui/list/ListReader.d.ts +38 -7
  106. package/dist/space-sdk/src/ui/list/Row.d.ts +4 -0
  107. package/dist/space-sdk/src/ui/list/SelectionBar.d.ts +9 -4
  108. package/dist/space-sdk/src/ui/list/useListKeys.d.ts +4 -0
  109. package/dist/space-sdk/src/words/shell.ts +1 -0
  110. package/dist/view-renderer/dist/host.js +355 -188
  111. package/dist/view-renderer/dist/theme.css +1 -1
  112. package/dist/view-renderer/src/host.tsx +4 -1
  113. package/dist/view-renderer/src/index.js +3 -0
  114. package/dist/view-renderer/src/pool.js +8 -4
  115. package/dist/view-renderer/src/renderer.js +92 -23
  116. package/dist/view-renderer/src/skeleton.js +450 -0
  117. package/package.json +4 -4
  118. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +8 -4
  119. package/skills/notis-onboarding/BRIEF.md +15 -9
  120. package/skills/notis-spaces/cli.md +43 -4
  121. package/src/command-specs/auth.js +5 -3
  122. package/src/command-specs/cc.js +410 -0
  123. package/src/command-specs/computer.js +320 -0
  124. package/src/command-specs/diagnostics.js +2 -13
  125. package/src/command-specs/documents.js +22 -4
  126. package/src/command-specs/index.js +7 -0
  127. package/src/command-specs/onboarding.js +127 -7
  128. package/src/command-specs/skills.js +2 -2
  129. package/src/command-specs/spaces.js +162 -30
  130. package/src/command-specs/tools.js +26 -8
  131. package/src/command-specs/views.js +4 -1
  132. package/src/runtime/agent-setup.js +20 -2
  133. package/src/runtime/app-boundary-validator.js +2 -1
  134. package/src/runtime/app-platform.js +13 -0
  135. package/src/runtime/auth-recovery.js +5 -0
  136. package/src/runtime/channel.js +16 -2
  137. package/src/runtime/cloud-transfer.js +587 -0
  138. package/src/runtime/computer-ssh.js +127 -0
  139. package/src/runtime/oauth.js +50 -4
  140. package/src/runtime/skill-sync/index.ts +20 -1
  141. package/src/runtime/skill-sync/local-scanner.ts +1 -0
  142. package/src/runtime/skill-sync/types.ts +2 -0
  143. package/src/runtime/space-audience.js +94 -0
  144. package/src/runtime/space-collection-scaffold.js +2 -1
  145. package/src/runtime/space-fixture-broker.js +2 -1
  146. package/src/runtime/space-lock.js +1 -4
  147. package/src/runtime/space-platform.js +18 -2
  148. package/src/runtime/space-source.js +105 -7
  149. package/src/runtime/space-test-server.js +13 -2
  150. package/src/runtime/space-verification.js +99 -6
  151. package/src/runtime/space-view-manifest.js +22 -4
  152. package/src/runtime/sync-skills.js +24 -20
  153. package/src/runtime/transport.js +19 -0
  154. package/src/runtime/view-render.js +2 -2
  155. package/template/.harness/index.html.tmpl +1 -1
  156. package/dist/skill-sync/index.js.map +0 -7
  157. package/dist/space-sdk/dist/chunk-SVZATGZB.js +0 -5
@@ -0,0 +1,329 @@
1
+ /**
2
+ * What a native insert or update looks like in the rows a view already holds, before the server answers.
3
+ *
4
+ * Writes and reads use different shapes: a write keys properties by id or name and sends plain values (a select as
5
+ * an option id or label), a native read keys them by name in typed envelopes (`{type: 'select', select: {id, name,
6
+ * color}}`), and `useNativeDocuments` flattens those envelopes. Property types and options are learned from every
7
+ * row of the database the cache holds. A value is shown only when it can be put in the read's shape for certain;
8
+ * anything else (a property named by id, an unseen option, a relation) keeps its old value until the server's rows
9
+ * arrive, which never takes long: the host reads every list again after each write.
10
+ *
11
+ * A row leaves or joins a read only by the read's own filter, evaluated here when the page sent it and every field it
12
+ * reads is understood; a Space's `shows` filter stays on the server, so there a row changes in place and a new row
13
+ * shows only in the list it was created from. Rows move to their sorted place when the read's sorts are understood.
14
+ */
15
+
16
+ import type { NativeField, NativeFilter, NativeInsert, NativeQuery, NativeUpdate } from './nativeData';
17
+ import { recordKeyOf, type RowChange, type RowsRead } from './queryCache';
18
+
19
+ type Row = Record<string, unknown>;
20
+
21
+ const isObject = (value: unknown): value is Row => !!value && typeof value === 'object' && !Array.isArray(value);
22
+ const text = (value: string) => (value ? [{ type: 'text', text: { content: value } }] : []);
23
+
24
+ /** What the cached rows of a database say about its properties: names, native types and select options. */
25
+ type Learned = { names: Set<string>; types: Map<string, string>; options: Map<string, Map<string, Row>> };
26
+ const learnedFor = new WeakMap<readonly Row[], Learned>();
27
+ function learn(rows: readonly Row[]): Learned {
28
+ const cached = learnedFor.get(rows);
29
+ if (cached) return cached;
30
+ const names = new Set<string>();
31
+ const types = new Map<string, string>();
32
+ const options = new Map<string, Map<string, Row>>();
33
+ for (const row of rows) {
34
+ const properties = isObject(row.properties) ? row.properties : {};
35
+ for (const [name, value] of Object.entries(properties)) {
36
+ names.add(name);
37
+ if (!isObject(value) || typeof value.type !== 'string') continue;
38
+ types.set(name, value.type);
39
+ const picked = value[value.type];
40
+ for (const option of Array.isArray(picked) ? picked : [picked]) {
41
+ if (!isObject(option) || typeof option.id !== 'string' || typeof option.name !== 'string') continue;
42
+ let known = options.get(name);
43
+ if (!known) options.set(name, known = new Map());
44
+ known.set(`id:${option.id}`, option);
45
+ known.set(`name:${option.name.toLowerCase()}`, option);
46
+ }
47
+ }
48
+ }
49
+ const learned = { names, types, options };
50
+ learnedFor.set(rows, learned);
51
+ return learned;
52
+ }
53
+
54
+ function findOption(options: Map<string, Row> | undefined, raw: unknown): Row | undefined {
55
+ if (typeof raw !== 'string') return undefined;
56
+ return options?.get(`id:${raw}`) ?? options?.get(`name:${raw.toLowerCase()}`);
57
+ }
58
+
59
+ const SKIP = Symbol('skip');
60
+
61
+ /** A written value in the native read envelope, or SKIP when it cannot be shown for certain. */
62
+ function nativeValue(type: string, value: unknown, options: Map<string, Row> | undefined): unknown {
63
+ if (value === null) {
64
+ if (['multi_select', 'relation', 'people', 'files', 'title', 'rich_text'].includes(type)) {
65
+ return type === 'title' ? { type, title: [], rich_text: [] } : { type, [type]: [] };
66
+ }
67
+ if (type === 'checkbox') return { type, checkbox: false };
68
+ return type ? { type, [type]: null } : SKIP;
69
+ }
70
+ switch (type) {
71
+ case 'title': return typeof value === 'string' ? { type, title: text(value), rich_text: text(value) } : SKIP;
72
+ case 'rich_text': return typeof value === 'string' ? { type, rich_text: text(value) } : SKIP;
73
+ case 'url': case 'email': return typeof value === 'string' ? { type, [type]: value } : SKIP;
74
+ case 'number': return typeof value === 'number' && Number.isFinite(value) ? { type, number: value } : SKIP;
75
+ case 'checkbox': return typeof value === 'boolean' ? { type, checkbox: value } : SKIP;
76
+ case 'select': case 'status': {
77
+ const found = findOption(options, value);
78
+ return found ? { type, [type]: { ...found } } : SKIP;
79
+ }
80
+ case 'multi_select': {
81
+ if (!Array.isArray(value)) return SKIP;
82
+ const found = value.map((item) => findOption(options, item));
83
+ return found.every(Boolean) ? { type, multi_select: found.map((item) => ({ ...item })) } : SKIP;
84
+ }
85
+ case 'date': {
86
+ if (typeof value === 'string') return { type, date: { start: value, end: null, timezone: null } };
87
+ if (isObject(value) && typeof value.start === 'string') {
88
+ return { type, date: { start: value.start, end: value.end ?? null, timezone: value.timezone ?? null } };
89
+ }
90
+ return SKIP;
91
+ }
92
+ default: return SKIP;
93
+ }
94
+ }
95
+
96
+ /** A written value as `useNativeDocuments` flattens it, or SKIP when it cannot be shown for certain. */
97
+ function documentValue(type: string | undefined, current: unknown, value: unknown, options: Map<string, Row> | undefined): unknown {
98
+ if (type) {
99
+ const envelope = nativeValue(type, value, options);
100
+ if (envelope === SKIP) return SKIP;
101
+ const record = envelope as Row;
102
+ if (type === 'title' || type === 'rich_text') return typeof value === 'string' ? value : '';
103
+ if (type === 'select' || type === 'status') return isObject(record[type]) ? (record[type] as Row).name : null;
104
+ if (type === 'multi_select') return (record.multi_select as Row[]).map((item) => item.name);
105
+ if (type === 'date') return isObject(record.date) ? (record.date as Row).start : null;
106
+ return record[type];
107
+ }
108
+ // Without the native type the flattened value is ambiguous (an option id and its label are both strings).
109
+ return value === null && current === null ? null : SKIP;
110
+ }
111
+
112
+ /** The property a write names, by its name as the rows key it (exact, else case-insensitive); never by id. */
113
+ function propertyName(names: Iterable<string>, written: string): string | null {
114
+ const list = [...names];
115
+ if (list.includes(written)) return written;
116
+ const lower = written.toLowerCase();
117
+ return list.find((name) => name.toLowerCase() === lower) ?? null;
118
+ }
119
+
120
+ /** `row` with `fields` written into it, in the read's shape. */
121
+ function written(row: Row, fields: NativeInsert, read: RowsRead, learned: Learned): Row {
122
+ const next: Row = { ...row };
123
+ const document = read.shape === 'document';
124
+ const properties: Row = { ...(isObject(row.properties) ? row.properties : {}) };
125
+ const names = new Set([...learned.names, ...Object.keys(properties)]);
126
+ let skipped = false;
127
+ for (const [key, value] of Object.entries(fields.properties ?? {})) {
128
+ const name = propertyName(names, key);
129
+ if (!name) { skipped = true; continue; }
130
+ const type = learned.types.get(name) ?? (isObject(properties[name]) ? String((properties[name] as Row).type ?? '') : '');
131
+ const shown = document ? documentValue(type || undefined, properties[name], value, learned.options.get(name))
132
+ : nativeValue(type, value, learned.options.get(name));
133
+ if (shown === SKIP) { skipped = true; continue; }
134
+ properties[name] = shown;
135
+ if (type === 'title') next.title = typeof value === 'string' ? value : '';
136
+ }
137
+ const title = fields.columns?.title;
138
+ if (title !== undefined) {
139
+ next.title = title ?? '';
140
+ for (const [name, type] of learned.types) {
141
+ if (type === 'title') properties[name] = document ? title ?? '' : nativeValue('title', title, undefined);
142
+ }
143
+ }
144
+ if (fields.columns?.icon !== undefined) next.icon = fields.columns.icon;
145
+ if (fields.columns?.cover !== undefined) next.cover = fields.columns.cover;
146
+ next.properties = properties;
147
+ if (skipped) partial.add(next);
148
+ return next;
149
+ }
150
+
151
+ /** Rows that could not show every written value: they wait for the server's rows before taking its revision. */
152
+ const partial = new WeakSet<Row>();
153
+
154
+ // ---- the read's own filter and sorts ----
155
+
156
+ const UNKNOWN = Symbol('unknown');
157
+
158
+ /** The comparable value of one field of a row (a list for options and multi-selects), or UNKNOWN. */
159
+ function fieldValue(row: Row, field: NativeField, read: RowsRead, learned: Learned): unknown {
160
+ if ('column' in field) {
161
+ if (field.column === 'record_key') return recordKeyOf(row) ?? UNKNOWN;
162
+ // A flattened document titles an empty title "Untitled" in the reader's language: not the stored value.
163
+ if (field.column === 'title') return typeof row.title === 'string' && read.shape !== 'document' ? row.title : UNKNOWN;
164
+ if (field.column === 'created_at') return row.created_at ?? row.createdAt ?? UNKNOWN;
165
+ if (field.column === 'updated_at' || field.column === 'last_edited_time') {
166
+ return row.updated_at ?? row.last_edited_time ?? row.lastEditedTime ?? UNKNOWN;
167
+ }
168
+ return UNKNOWN;
169
+ }
170
+ if (!('property' in field)) return UNKNOWN;
171
+ const properties = isObject(row.properties) ? row.properties : {};
172
+ const name = propertyName(Object.keys(properties), field.property);
173
+ if (!name) return UNKNOWN;
174
+ const value = properties[name];
175
+ if (read.shape === 'document') {
176
+ const type = learned.types.get(name);
177
+ if (!type) return UNKNOWN;
178
+ if (type === 'select' || type === 'status' || type === 'multi_select') {
179
+ // Flattened rows keep option names only; a filter may name the option by id.
180
+ const labels = Array.isArray(value) ? value : value === null || value === undefined ? [] : [value];
181
+ return labels.flatMap((label) => {
182
+ const option = findOption(learned.options.get(name), label);
183
+ return option ? [option.id, option.name] : [label];
184
+ });
185
+ }
186
+ return value ?? null;
187
+ }
188
+ if (!isObject(value) || typeof value.type !== 'string') return UNKNOWN;
189
+ const inner = value[value.type];
190
+ switch (value.type) {
191
+ case 'title': case 'rich_text':
192
+ return Array.isArray(inner) ? inner.map((chunk) => (isObject(chunk) && isObject(chunk.text) ? String(chunk.text.content ?? '') : '')).join('') : '';
193
+ case 'select': case 'status': return isObject(inner) ? [inner.id, inner.name] : [];
194
+ case 'multi_select': return Array.isArray(inner) ? inner.flatMap((item) => (isObject(item) ? [item.id, item.name] : [])) : [];
195
+ case 'date': return isObject(inner) ? inner.start ?? null : null;
196
+ case 'number': case 'checkbox': case 'url': case 'email': return inner ?? null;
197
+ default: return UNKNOWN;
198
+ }
199
+ }
200
+
201
+ const isEmpty = (value: unknown) => value === null || value === undefined || value === '' || (Array.isArray(value) && !value.length);
202
+ const same = (a: unknown, b: unknown) => (typeof a === 'string' && typeof b === 'string' ? a.toLowerCase() === b.toLowerCase() : a === b);
203
+
204
+ function compare(a: unknown, b: unknown): number {
205
+ if (typeof a === 'number' && typeof b === 'number') return a - b;
206
+ if (typeof a === 'string' && typeof b === 'string') return a < b ? -1 : a > b ? 1 : 0;
207
+ if (typeof a === 'boolean' && typeof b === 'boolean') return Number(a) - Number(b);
208
+ return Number.NaN;
209
+ }
210
+
211
+ /** Whether `row` passes `filter`: true, false, or UNKNOWN when a field or operator is not understood here. */
212
+ function matches(row: Row, filter: NativeFilter | undefined, read: RowsRead, learned: Learned): boolean | typeof UNKNOWN {
213
+ if (!filter) return true;
214
+ if ('and' in filter || 'or' in filter) {
215
+ const all = 'and' in filter;
216
+ const results = (all ? (filter as { and: NativeFilter[] }).and : (filter as { or: NativeFilter[] }).or)
217
+ .map((part) => matches(row, part, read, learned));
218
+ if (all) return results.includes(false) ? false : results.includes(UNKNOWN) ? UNKNOWN : true;
219
+ return results.includes(true) ? true : results.includes(UNKNOWN) ? UNKNOWN : false;
220
+ }
221
+ const value = fieldValue(row, filter.field, read, learned);
222
+ if (value === UNKNOWN) return UNKNOWN;
223
+ const values = Array.isArray(value) ? value : [value];
224
+ const wanted = filter.value;
225
+ const ordered = (test: (result: number) => boolean) => {
226
+ const result = compare(value, wanted);
227
+ return Number.isNaN(result) ? (isEmpty(value) ? false : UNKNOWN) : test(result);
228
+ };
229
+ switch (filter.op) {
230
+ case 'is_empty': return values.every(isEmpty);
231
+ case 'is_not_empty': return !values.every(isEmpty);
232
+ case 'equals': return values.some((item) => same(item, wanted));
233
+ case 'not_equals': return !values.some((item) => same(item, wanted));
234
+ case 'in': return Array.isArray(wanted) ? values.some((item) => wanted.some((one) => same(item, one))) : UNKNOWN;
235
+ case 'contains': case 'not_contains': case 'does_not_contain': {
236
+ if (typeof wanted !== 'string') return UNKNOWN;
237
+ const found = Array.isArray(value) ? values.some((item) => same(item, wanted))
238
+ : typeof value === 'string' && value.toLowerCase().includes(wanted.toLowerCase());
239
+ return filter.op === 'contains' ? found : !found;
240
+ }
241
+ case 'greater_than': case 'after': return ordered((result) => result > 0);
242
+ case 'less_than': case 'before': return ordered((result) => result < 0);
243
+ case 'greater_than_or_equal_to': case 'on_or_after': return ordered((result) => result >= 0);
244
+ case 'less_than_or_equal_to': case 'on_or_before': return ordered((result) => result <= 0);
245
+ default: return UNKNOWN;
246
+ }
247
+ }
248
+
249
+ /** Where `row` goes among `rows` by the read's sorts, or -1 when they are not understood here. */
250
+ function sortedPlace(rows: readonly Row[], row: Row, read: RowsRead, learned: Learned): number {
251
+ const sorts = (read.query as NativeQuery | undefined)?.sorts;
252
+ if (!sorts?.length) return -1;
253
+ // An option sorts by its name; empty values sort last either way.
254
+ const keyOf = (item: Row) => sorts.map((sort) => {
255
+ const value = fieldValue(item, sort.field, read, learned);
256
+ return Array.isArray(value) ? value[1] ?? value[0] ?? null : value;
257
+ });
258
+ const mine = keyOf(row);
259
+ if (mine.includes(UNKNOWN)) return -1;
260
+ for (let index = 0; index < rows.length; index += 1) {
261
+ const theirs = keyOf(rows[index]!);
262
+ let result = 0;
263
+ for (let at = 0; at < sorts.length && !result; at += 1) {
264
+ const a = mine[at], b = theirs[at];
265
+ if (b === UNKNOWN) return -1;
266
+ if (isEmpty(a) !== isEmpty(b)) { result = isEmpty(a) ? 1 : -1; break; }
267
+ if (isEmpty(a)) continue;
268
+ const order = compare(a, b);
269
+ if (Number.isNaN(order)) return -1;
270
+ result = sorts[at]!.direction === 'desc' ? -order : order;
271
+ }
272
+ if (result < 0) return index;
273
+ }
274
+ return rows.length;
275
+ }
276
+
277
+ // ---- the changes ----
278
+
279
+ /**
280
+ * The change a native update makes: the row is rewritten where it is, leaves a read whose own filter it no longer
281
+ * passes, and moves to its sorted place.
282
+ */
283
+ export function updateChange(binding: string, input: NativeUpdate): RowChange {
284
+ return {
285
+ binding,
286
+ recordKey: input.record_key,
287
+ project: (row, read, related) => (row ? written(row, input, read, learn(related())) : undefined),
288
+ keeps: (row, read, related) => matches(row, (read.query as NativeQuery | undefined)?.filter, read, learn(related())) !== false,
289
+ exact: (row) => !partial.has(row),
290
+ position: (rows, row, read, related) => sortedPlace(rows, row, read, learn(related())),
291
+ };
292
+ }
293
+
294
+ /**
295
+ * The change a native insert makes: a new row with the temporary key `tempKey`, at its sorted place or the top, in
296
+ * every read of the database whose own filter it passes for certain. A Space `shows` list's filter stays on the
297
+ * server, so a new row shows there only in the lists `showIn` names (the lists it was created from).
298
+ */
299
+ export function insertChange(binding: string, input: NativeInsert, tempKey: string, showIn: readonly string[] = []): RowChange {
300
+ return {
301
+ binding,
302
+ recordKey: tempKey,
303
+ insert: true,
304
+ project: (row, read, related) => {
305
+ if (row) return undefined;
306
+ const query = read.query as NativeQuery | undefined;
307
+ if (read.list ? !showIn.includes(read.list) : !query || query.search || query.mode === 'search' || (query.offset ?? 0) > 0) {
308
+ return undefined;
309
+ }
310
+ const learned = learn(related());
311
+ const blank: Row = read.shape === 'document'
312
+ ? { id: tempKey, recordKey: tempKey, title: '', properties: {} }
313
+ : { id: tempKey, record_key: tempKey, title: '', properties: {} };
314
+ const next = written(blank, input, read, learned);
315
+ if (read.list) return next;
316
+ return matches(next, query!.filter, read, learned) === true ? next : undefined;
317
+ },
318
+ position: (rows, row, read, related) => Math.max(0, sortedPlace(rows, row, read, learn(related()))),
319
+ };
320
+ }
321
+
322
+ /** A temporary key for a row being created. */
323
+ export function tempRecordKey(): string {
324
+ const random = typeof crypto !== 'undefined' && 'randomUUID' in crypto ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`;
325
+ return `pending:${random}`;
326
+ }
327
+ export function isTempRecordKey(key: unknown): boolean {
328
+ return typeof key === 'string' && key.startsWith('pending:');
329
+ }
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Always-on timing of the moments a person waits for in a Space, from their key press or click to the first frame
3
+ * that shows real content (no skeleton). Each finished wait is one `performance.measure` entry:
4
+ *
5
+ * - `notis:space-open`: another Space (or record context) shows.
6
+ * - `notis:view-switch`: another view of the same Space shows.
7
+ * - `notis:record-open`: an item of a list opens in its reader, or a DocumentPage opens another record.
8
+ * - `notis:query-change`: a read whose key changed (a filter, a search, a server tab) shows its new answer.
9
+ *
10
+ * Read them with `performance.getEntriesByType('measure').filter((entry) => entry.name.startsWith('notis:'))`.
11
+ * The cost is a timestamp per key press or click and, while a wait is open, one animation frame (and a mutation
12
+ * observer when a skeleton still shows). One copy serves the host and every Space bundle (kept on `globalThis`).
13
+ */
14
+
15
+ export type WaitName = 'notis:space-open' | 'notis:view-switch' | 'notis:record-open' | 'notis:query-change';
16
+
17
+ /** A key press or click older than this did not cause the wait: it starts when it is noticed. */
18
+ export const INTENT_WINDOW_MS = 3_000;
19
+ /** A wait whose content never shows within this is dropped, not measured. */
20
+ export const WAIT_TIMEOUT_MS = 10_000;
21
+ /** What a loading placeholder carries: the SDK skeletons and the list's skeleton rows. */
22
+ export const SKELETON_SELECTOR = '[data-notis-skeleton], [data-notis-content-skeleton], .nui-skel';
23
+
24
+ interface Pending {
25
+ start: number;
26
+ /** Parts still loading (one per read of a query change); the wait ends when none is left. */
27
+ parts: Set<unknown>;
28
+ ended: boolean;
29
+ stop?: () => void;
30
+ }
31
+ interface PerfState {
32
+ intent: number | null;
33
+ watching: boolean;
34
+ pending: Map<WaitName, Pending>;
35
+ }
36
+
37
+ const STATE = Symbol.for('notis.perf');
38
+ function state(): PerfState {
39
+ const holder = globalThis as unknown as Record<symbol, PerfState | undefined>;
40
+ return (holder[STATE] ??= { intent: null, watching: false, pending: new Map() });
41
+ }
42
+
43
+ function clock(): Performance | null {
44
+ return typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance : null;
45
+ }
46
+
47
+ /** Notes a key press or click now (the host's listeners call it; tests may too). */
48
+ export function noteIntent(at?: number): void {
49
+ const perf = clock();
50
+ if (perf) state().intent = at ?? perf.now();
51
+ }
52
+
53
+ /** Listens for key presses and clicks on `target` (capture, passive), once per target. Returns a stop function. */
54
+ export function watchUserIntent(target: Pick<Window, 'addEventListener' | 'removeEventListener'> | null =
55
+ typeof window === 'undefined' ? null : window): () => void {
56
+ const current = state();
57
+ if (!target || current.watching) return () => {};
58
+ current.watching = true;
59
+ const note = (event: Event) => {
60
+ // A modifier pressed alone is not the intent: the key it modifies is.
61
+ if (event instanceof KeyboardEvent && ['Shift', 'Control', 'Alt', 'Meta'].includes(event.key)) return;
62
+ noteIntent(typeof event.timeStamp === 'number' && event.timeStamp > 0 ? event.timeStamp : undefined);
63
+ };
64
+ const options = { capture: true, passive: true } as const;
65
+ target.addEventListener('keydown', note, options);
66
+ target.addEventListener('pointerdown', note, options);
67
+ return () => {
68
+ target.removeEventListener('keydown', note, options);
69
+ target.removeEventListener('pointerdown', note, options);
70
+ current.watching = false;
71
+ };
72
+ }
73
+
74
+ /**
75
+ * Starts `name` at the last key press or click (when recent), else now. `part` names one thing the wait needs (a
76
+ * read): the wait ends once every part began for it ended. A newer key press or click starts a new wait.
77
+ */
78
+ export function beginWait(name: WaitName, part: unknown = name): void {
79
+ const perf = clock();
80
+ if (!perf) return;
81
+ const now = perf.now();
82
+ const current = state();
83
+ const intent = current.intent !== null && now - current.intent < INTENT_WINDOW_MS ? current.intent : null;
84
+ const open = current.pending.get(name);
85
+ // A wait no paint ended for this long is stale: it never joins a new one.
86
+ if (open && !open.ended && now - open.start < WAIT_TIMEOUT_MS && (intent === null || intent <= open.start)) {
87
+ open.parts.add(part);
88
+ return;
89
+ }
90
+ open?.stop?.();
91
+ current.pending.set(name, { start: intent ?? now, parts: new Set([part]), ended: false });
92
+ }
93
+
94
+ /** Drops `name` unmeasured (the move it timed did not happen). */
95
+ export function cancelWait(name: WaitName): void {
96
+ const current = state();
97
+ const open = current.pending.get(name);
98
+ if (!open) return;
99
+ open.stop?.();
100
+ open.ended = true;
101
+ current.pending.delete(name);
102
+ }
103
+
104
+ /** Whether `name` waits now. */
105
+ export function isWaiting(name: WaitName): boolean {
106
+ const open = state().pending.get(name);
107
+ return !!open && !open.ended;
108
+ }
109
+
110
+ function finish(name: WaitName, open: Pending, detail?: Record<string, unknown>) {
111
+ const perf = clock();
112
+ const current = state();
113
+ if (!perf || open.ended || current.pending.get(name) !== open) return;
114
+ open.ended = true;
115
+ open.stop?.();
116
+ current.pending.delete(name);
117
+ try {
118
+ perf.measure(name, { start: open.start, end: perf.now(), ...(detail ? { detail } : {}) });
119
+ } catch {
120
+ // An old engine without measure options: the wait goes unmeasured.
121
+ }
122
+ }
123
+
124
+ function nextFrame(run: () => void): () => void {
125
+ if (typeof requestAnimationFrame === 'function') {
126
+ const frame = requestAnimationFrame(() => run());
127
+ return () => cancelAnimationFrame(frame);
128
+ }
129
+ const timer = setTimeout(run, 0);
130
+ return () => clearTimeout(timer);
131
+ }
132
+
133
+ /**
134
+ * `part` of `name` has painted: once every part has, the wait is measured on the next animation frame (the frame
135
+ * that shows what was just committed). Does nothing when `name` does not wait.
136
+ */
137
+ export function endWait(name: WaitName, part: unknown = name, detail?: Record<string, unknown>): void {
138
+ const open = state().pending.get(name);
139
+ if (!open || open.ended) return;
140
+ open.parts.delete(part);
141
+ if (open.parts.size) return;
142
+ open.stop?.();
143
+ open.stop = nextFrame(() => finish(name, open, detail));
144
+ }
145
+
146
+ /**
147
+ * Ends `name` on the first frame where `root` shows no skeleton: at once when it already shows content, else when a
148
+ * change takes the last skeleton out (dropped after `WAIT_TIMEOUT_MS`). Does nothing when `name` does not wait.
149
+ */
150
+ export function endWaitWhenContent(name: WaitName, root: ParentNode | null | undefined, detail?: Record<string, unknown>): void {
151
+ const open = state().pending.get(name);
152
+ if (!open || open.ended || !root) return;
153
+ open.parts.clear();
154
+ open.stop?.();
155
+ const shows = () => !root.querySelector(SKELETON_SELECTOR);
156
+ let observer: MutationObserver | null = null;
157
+ let timer: ReturnType<typeof setTimeout> | null = null;
158
+ let cancelFrame: (() => void) | null = null;
159
+ const stop = () => {
160
+ observer?.disconnect(); observer = null;
161
+ if (timer) clearTimeout(timer); timer = null;
162
+ cancelFrame?.(); cancelFrame = null;
163
+ };
164
+ open.stop = stop;
165
+ cancelFrame = nextFrame(() => {
166
+ cancelFrame = null;
167
+ if (shows()) { finish(name, open, detail); return; }
168
+ if (typeof MutationObserver === 'undefined') return;
169
+ observer = new MutationObserver(() => {
170
+ if (!shows() || cancelFrame) return;
171
+ cancelFrame = nextFrame(() => { cancelFrame = null; if (shows()) finish(name, open, detail); });
172
+ });
173
+ observer.observe(root as Node, { childList: true, subtree: true, attributes: true, attributeFilter: ['class', 'data-notis-skeleton'] });
174
+ timer = setTimeout(() => {
175
+ stop();
176
+ const current = state();
177
+ if (current.pending.get(name) === open) { open.ended = true; current.pending.delete(name); }
178
+ }, WAIT_TIMEOUT_MS);
179
+ });
180
+ }
181
+
182
+ /** Forgets every open wait (tests). */
183
+ export function resetWaits(): void {
184
+ const current = state();
185
+ for (const open of current.pending.values()) open.stop?.();
186
+ current.pending.clear();
187
+ current.intent = null;
188
+ }
@@ -4,6 +4,7 @@ import React, { createContext, useContext, useMemo, type Context, type ReactNode
4
4
  import type { NotisRuntime } from './runtime';
5
5
  import { ShortcutProvider } from './interactions/shortcuts';
6
6
  import { guardSpaceRuntime } from './space';
7
+ import { publicRecordUI } from './spacePublicUI';
7
8
 
8
9
  const NOTIS_CONTEXT_SYMBOL = Symbol.for('notis.sdk.runtime_context');
9
10
 
@@ -29,7 +30,7 @@ export function NotisProvider({ children, runtime, onProtocolError, shortcutsAva
29
30
  children: ReactNode; runtime: NotisRuntime | null; onProtocolError?: (error: Error) => void;
30
31
  shortcutsAvailable?: () => boolean;
31
32
  }) {
32
- const scopedRuntime = useMemo(() => guardSpaceRuntime(runtime, onProtocolError), [runtime, onProtocolError]);
33
+ const scopedRuntime = useMemo(() => guardSpaceRuntime(runtime, onProtocolError, { publicRecordUI }), [runtime, onProtocolError]);
33
34
  if (runtime === undefined) {
34
35
  throw new Error('NotisProvider requires an explicit runtime prop.');
35
36
  }