@notis_ai/cli 0.2.25 → 0.2.27

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 (163) 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 +2866 -553
  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/context.md +3 -0
  15. package/dist/base-skills/notis-spaces/references/design.md +37 -18
  16. package/dist/base-skills/notis-spaces/references/reading.md +8 -1
  17. package/dist/base-skills/notis-spaces/references/reports.md +6 -6
  18. package/dist/base-skills/notis-spaces/references/sdk.md +71 -7
  19. package/dist/base-skills/notis-spaces/references/store.md +22 -13
  20. package/dist/base-skills/notis-spaces/references/views.md +99 -6
  21. package/dist/sdk/package.json +3 -0
  22. package/dist/sdk/src/cloudComputerWords.ts +53 -0
  23. package/dist/sdk/src/components/Audience.tsx +76 -0
  24. package/dist/sdk/src/components/DocumentPage.tsx +15 -4
  25. package/dist/sdk/src/components/MarkdownEditor.tsx +44 -14
  26. package/dist/sdk/src/components/MultiSelectActionBar.tsx +16 -5
  27. package/dist/sdk/src/components/NotisSelectionBoundary.tsx +79 -25
  28. package/dist/sdk/src/components/Skeleton.tsx +162 -6
  29. package/dist/sdk/src/hooks/useAction.ts +12 -2
  30. package/dist/sdk/src/hooks/useAgentQueue.ts +125 -0
  31. package/dist/sdk/src/hooks/useCloudComputerJob.ts +142 -0
  32. package/dist/sdk/src/hooks/useCloudComputerService.ts +388 -0
  33. package/dist/sdk/src/hooks/useCloudComputerShell.ts +95 -7
  34. package/dist/sdk/src/hooks/useCollectionInteractions.ts +40 -2
  35. package/dist/sdk/src/hooks/useItemThread.ts +58 -0
  36. package/dist/sdk/src/hooks/useMarqueeSelection.ts +6 -1
  37. package/dist/sdk/src/hooks/useNativeDocuments.ts +61 -8
  38. package/dist/sdk/src/hooks/useNotisNavigation.ts +31 -8
  39. package/dist/sdk/src/hooks/useQuery.ts +67 -10
  40. package/dist/sdk/src/hooks/useViewParams.ts +47 -11
  41. package/dist/sdk/src/index.ts +31 -4
  42. package/dist/sdk/src/interactions.ts +2 -0
  43. package/dist/sdk/src/nativeData.ts +2 -0
  44. package/dist/sdk/src/optimisticRows.ts +329 -0
  45. package/dist/sdk/src/perf.ts +188 -0
  46. package/dist/sdk/src/provider.tsx +2 -1
  47. package/dist/sdk/src/queryCache.ts +366 -17
  48. package/dist/sdk/src/runtime.ts +55 -4
  49. package/dist/sdk/src/skeleton.ts +103 -0
  50. package/dist/sdk/src/space.ts +662 -28
  51. package/dist/sdk/src/spacePublicUI.ts +36 -0
  52. package/dist/sdk/src/ui/engine/step.ts +54 -0
  53. package/dist/sdk/src/ui/icons.tsx +3 -1
  54. package/dist/sdk/src/words/shell.ts +1 -0
  55. package/dist/skill-sync/index.js +88 -13
  56. package/dist/skill-sync-worker.mjs +127 -38
  57. package/dist/space-harness/host.js +272 -105
  58. package/dist/space-sdk/dist/chunk-BWHAORT4.js +5 -0
  59. package/dist/space-sdk/dist/index.js +9 -4
  60. package/dist/space-sdk/dist/ui.js +12 -12
  61. package/dist/space-sdk/package.json +3 -0
  62. package/dist/space-sdk/src/cloudComputerWords.d.ts +34 -0
  63. package/dist/space-sdk/src/components/Audience.d.ts +46 -0
  64. package/dist/space-sdk/src/components/DocumentPage.d.ts +3 -1
  65. package/dist/space-sdk/src/components/MarkdownEditor.d.ts +21 -0
  66. package/dist/space-sdk/src/components/MultiSelectActionBar.d.ts +5 -1
  67. package/dist/space-sdk/src/components/NotisSelectionBoundary.d.ts +19 -2
  68. package/dist/space-sdk/src/components/Skeleton.d.ts +7 -2
  69. package/dist/space-sdk/src/hooks/useAction.d.ts +8 -1
  70. package/dist/space-sdk/src/hooks/useAgentQueue.d.ts +61 -0
  71. package/dist/space-sdk/src/hooks/useCloudComputerJob.d.ts +35 -0
  72. package/dist/space-sdk/src/hooks/useCloudComputerService.d.ts +75 -0
  73. package/dist/space-sdk/src/hooks/useCloudComputerShell.d.ts +36 -3
  74. package/dist/space-sdk/src/hooks/useCollectionInteractions.d.ts +6 -0
  75. package/dist/space-sdk/src/hooks/useItemThread.d.ts +32 -0
  76. package/dist/space-sdk/src/hooks/useMarqueeSelection.d.ts +2 -1
  77. package/dist/space-sdk/src/hooks/useNativeDocumentBody.d.ts +1 -0
  78. package/dist/space-sdk/src/hooks/useNativeDocuments.d.ts +20 -5
  79. package/dist/space-sdk/src/hooks/useNotisNavigation.d.ts +11 -2
  80. package/dist/space-sdk/src/hooks/useQuery.d.ts +24 -2
  81. package/dist/space-sdk/src/hooks/useViewParams.d.ts +2 -0
  82. package/dist/space-sdk/src/index.d.ts +24 -4
  83. package/dist/space-sdk/src/nativeData.d.ts +6 -0
  84. package/dist/space-sdk/src/queryCache.d.ts +97 -2
  85. package/dist/space-sdk/src/runtime.d.ts +53 -4
  86. package/dist/space-sdk/src/skeleton.d.ts +42 -0
  87. package/dist/space-sdk/src/space.ts +662 -28
  88. package/dist/space-sdk/src/tailwind-candidates.d.ts +761 -6
  89. package/dist/space-sdk/src/ui/cloud/CloudComputerFrame.d.ts +29 -0
  90. package/dist/space-sdk/src/ui/cloud/CloudComputerWaking.d.ts +20 -0
  91. package/dist/space-sdk/src/ui/comments/CommentPane.d.ts +15 -2
  92. package/dist/space-sdk/src/ui/comments/PassageComments.d.ts +50 -0
  93. package/dist/space-sdk/src/ui/comments/commentFiles.d.ts +64 -0
  94. package/dist/space-sdk/src/ui/comments/commentModel.d.ts +49 -1
  95. package/dist/space-sdk/src/ui/comments/commentWords.d.ts +26 -0
  96. package/dist/space-sdk/src/ui/comments/index.d.ts +4 -0
  97. package/dist/space-sdk/src/ui/comments/passageModel.d.ts +82 -0
  98. package/dist/space-sdk/src/ui/comments/useComments.d.ts +34 -4
  99. package/dist/space-sdk/src/ui/comments/usePassageComments.d.ts +67 -0
  100. package/dist/space-sdk/src/ui/engine/index.d.ts +2 -2
  101. package/dist/space-sdk/src/ui/engine/step.d.ts +9 -0
  102. package/dist/space-sdk/src/ui/fields/fields.d.ts +2 -1
  103. package/dist/space-sdk/src/ui/index.d.ts +4 -0
  104. package/dist/space-sdk/src/ui/layout/Panels.d.ts +9 -2
  105. package/dist/space-sdk/src/ui/layout/SidePane.d.ts +42 -0
  106. package/dist/space-sdk/src/ui/layout/index.d.ts +2 -1
  107. package/dist/space-sdk/src/ui/layout/panelMath.d.ts +11 -2
  108. package/dist/space-sdk/src/ui/list/ListReader.d.ts +38 -7
  109. package/dist/space-sdk/src/ui/list/Row.d.ts +4 -0
  110. package/dist/space-sdk/src/ui/list/SelectionBar.d.ts +9 -4
  111. package/dist/space-sdk/src/ui/list/useListKeys.d.ts +4 -0
  112. package/dist/space-sdk/src/words/shell.ts +1 -0
  113. package/dist/view-renderer/dist/host.js +355 -188
  114. package/dist/view-renderer/dist/theme.css +1 -1
  115. package/dist/view-renderer/src/dom.js +15 -2
  116. package/dist/view-renderer/src/host.tsx +4 -1
  117. package/dist/view-renderer/src/index.js +3 -0
  118. package/dist/view-renderer/src/pool.js +8 -4
  119. package/dist/view-renderer/src/renderer.js +92 -23
  120. package/dist/view-renderer/src/skeleton.js +450 -0
  121. package/package.json +4 -4
  122. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +8 -4
  123. package/skills/notis-onboarding/BRIEF.md +15 -9
  124. package/skills/notis-spaces/cli.md +43 -4
  125. package/src/command-specs/auth.js +5 -3
  126. package/src/command-specs/cc.js +410 -0
  127. package/src/command-specs/computer.js +320 -0
  128. package/src/command-specs/diagnostics.js +2 -13
  129. package/src/command-specs/documents.js +22 -4
  130. package/src/command-specs/index.js +7 -0
  131. package/src/command-specs/onboarding.js +127 -7
  132. package/src/command-specs/skills.js +2 -2
  133. package/src/command-specs/spaces.js +162 -30
  134. package/src/command-specs/tools.js +26 -8
  135. package/src/command-specs/views.js +4 -1
  136. package/src/runtime/agent-setup.js +20 -2
  137. package/src/runtime/app-boundary-validator.js +2 -1
  138. package/src/runtime/app-platform.js +13 -0
  139. package/src/runtime/auth-recovery.js +5 -0
  140. package/src/runtime/channel.js +16 -2
  141. package/src/runtime/cloud-transfer.js +587 -0
  142. package/src/runtime/computer-ssh.js +127 -0
  143. package/src/runtime/oauth.js +50 -4
  144. package/src/runtime/skill-sync/cloud-client.ts +98 -15
  145. package/src/runtime/skill-sync/index.ts +42 -4
  146. package/src/runtime/skill-sync/local-scanner.ts +1 -0
  147. package/src/runtime/skill-sync/types.ts +6 -0
  148. package/src/runtime/space-audience.js +94 -0
  149. package/src/runtime/space-collection-scaffold.js +2 -1
  150. package/src/runtime/space-fixture-broker.js +2 -1
  151. package/src/runtime/space-lock.js +1 -4
  152. package/src/runtime/space-platform.js +18 -2
  153. package/src/runtime/space-source.js +105 -7
  154. package/src/runtime/space-test-server.js +13 -2
  155. package/src/runtime/space-verification.js +99 -6
  156. package/src/runtime/space-view-manifest.js +22 -4
  157. package/src/runtime/sync-skills.js +24 -20
  158. package/src/runtime/transport.js +19 -0
  159. package/src/runtime/view-render.js +2 -2
  160. package/src/skill-sync-worker.js +5 -1
  161. package/template/.harness/index.html.tmpl +1 -1
  162. package/dist/skill-sync/index.js.map +0 -7
  163. package/dist/space-sdk/dist/chunk-SVZATGZB.js +0 -5
@@ -1,7 +1,7 @@
1
1
  import type { CSSProperties, ClipboardEvent, ReactNode } from 'react';
2
2
  import React, { useCallback } from 'react';
3
3
  import { useNotisRuntime } from '../provider';
4
- import type { ContextResource, ContextSelection } from '../runtime';
4
+ import type { ContextResource, ContextSelection, NotisRuntime } from '../runtime';
5
5
 
6
6
  export const NOTIS_CONTEXT_CLIPBOARD_TYPE = 'application/x-notis-context+json';
7
7
 
@@ -18,6 +18,80 @@ function selectionId(): string {
18
18
  : `selection-${Date.now()}-${Math.random().toString(36).slice(2)}`;
19
19
  }
20
20
 
21
+ /** The selection's markup for other paste targets: hidden parts dropped, links made absolute. */
22
+ function selectionHtml(selection: Selection): string {
23
+ if (typeof document === 'undefined') return '';
24
+ const container = document.createElement('div');
25
+ for (let index = 0; index < selection.rangeCount; index += 1) container.appendChild(selection.getRangeAt(index).cloneContents());
26
+ container.querySelectorAll('[hidden],script,style,template').forEach(node => node.remove());
27
+ container.querySelectorAll('[href],[src]').forEach(node => {
28
+ for (const name of ['href', 'src']) {
29
+ const value = node.getAttribute(name);
30
+ if (value === null) continue;
31
+ try { node.setAttribute(name, new URL(value, document.baseURI).href); } catch { node.removeAttribute(name); }
32
+ }
33
+ });
34
+ return container.innerHTML;
35
+ }
36
+
37
+ /**
38
+ * Adds the copied passage as a Notis quote to a copy event that started inside
39
+ * `event.currentTarget`, and returns that quote (null when nothing inside was
40
+ * copied). Text in a rich editor (a Space's MarkdownEditor, Skill and automation
41
+ * instructions) is quoted too: the editor already wrote its own formats, so they
42
+ * stay as written and the quote reads the editor's plain text. Form fields keep
43
+ * plain copy.
44
+ */
45
+ export function addCopiedSelectionToClipboard(
46
+ event: ClipboardEvent<HTMLElement>,
47
+ context: Omit<ContextSelection, 'id' | 'text'> = {},
48
+ ): ContextSelection | null {
49
+ const boundary = event.currentTarget;
50
+ const target = event.target as Element | null;
51
+ if (!event.clipboardData || target?.closest?.('input,textarea')) return null;
52
+ // An inner boundary already quoted this copy: its resource wins over an outer default.
53
+ if (event.clipboardData.getData(NOTIS_CONTEXT_CLIPBOARD_TYPE)) return null;
54
+ const scope = boundary.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null };
55
+ const selection = scope?.getSelection?.() || window.getSelection();
56
+ if (!selection || !boundary.contains(selection.anchorNode) || !boundary.contains(selection.focusNode)) return null;
57
+ const editorWrote = event.nativeEvent?.defaultPrevented ?? event.defaultPrevented;
58
+ const wrotePlain = editorWrote ? event.clipboardData.getData('text/plain') : '';
59
+ // A handler that cancelled the copy and wrote nothing at all blocked it: quote nothing.
60
+ if (editorWrote && !wrotePlain && !event.clipboardData.getData('text/html')) return null;
61
+ const text = wrotePlain || selection.toString();
62
+ if (!text.trim()) return null;
63
+
64
+ const payload: ContextSelection = { ...context, id: selectionId(), text };
65
+ if (!editorWrote) {
66
+ // Keep the copied formatting (links, bold, tables) for every other paste target.
67
+ const html = selectionHtml(selection);
68
+ event.clipboardData.setData('text/plain', text);
69
+ if (html) event.clipboardData.setData('text/html', html);
70
+ event.preventDefault();
71
+ }
72
+ event.clipboardData.setData(NOTIS_CONTEXT_CLIPBOARD_TYPE, JSON.stringify(payload));
73
+ return payload;
74
+ }
75
+
76
+ /**
77
+ * The Space-wide default every view gets from its host: text copied anywhere in
78
+ * the view quotes as the Space itself (its name on the pill, the view as source).
79
+ * A NotisSelectionBoundary inside the view quotes first and names its own resource.
80
+ */
81
+ export function copySpaceSelection(event: ClipboardEvent<HTMLElement>, runtime: QuoteRuntime | null): void {
82
+ const source = runtime?.contextSource;
83
+ captureCopiedSelection(event, runtime, source ? { source, title: source.appName } : {});
84
+ }
85
+
86
+ type QuoteRuntime = Pick<NotisRuntime, 'contextSource' | 'captureContextSelection'>;
87
+
88
+ /** Quotes a copy for the host chat; a public Site's runtime has no chat, so its copy stays the browser's own. */
89
+ function captureCopiedSelection(event: ClipboardEvent<HTMLElement>, runtime: QuoteRuntime | null, context: Omit<ContextSelection, 'id' | 'text'>): void {
90
+ if (!runtime?.captureContextSelection) return;
91
+ const payload = addCopiedSelectionToClipboard(event, context);
92
+ if (payload) runtime.captureContextSelection(payload);
93
+ }
94
+
21
95
  /**
22
96
  * Adds structured provenance to ordinary copied text. Pasting still works in
23
97
  * every app because `text/plain` is preserved; Notis chat additionally reads
@@ -30,30 +104,10 @@ export function NotisSelectionBoundary({
30
104
  style,
31
105
  }: NotisSelectionBoundaryProps) {
32
106
  const runtime = useNotisRuntime();
33
- const onCopy = useCallback((event: ClipboardEvent<HTMLDivElement>) => {
34
- const target = event.target as Element | null;
35
- if (target?.closest?.('input,textarea,[contenteditable="true"]')) return;
36
- const scope = event.currentTarget.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null };
37
- const selection = scope?.getSelection?.() || window.getSelection();
38
- const text = selection?.toString() ?? '';
39
- if (
40
- !text.trim()
41
- || !selection
42
- || !event.currentTarget.contains(selection.anchorNode)
43
- || !event.currentTarget.contains(selection.focusNode)
44
- ) return;
45
-
46
- const payload: ContextSelection = {
47
- id: selectionId(),
48
- text,
49
- ...(runtime?.contextSource ? { source: runtime.contextSource } : {}),
50
- ...(resource ? { resource: { ...resource, snapshot: undefined } } : {}),
51
- };
52
- event.clipboardData.setData('text/plain', text);
53
- event.clipboardData.setData(NOTIS_CONTEXT_CLIPBOARD_TYPE, JSON.stringify(payload));
54
- event.preventDefault();
55
- runtime?.captureContextSelection?.(payload);
56
- }, [resource, runtime]);
107
+ const onCopy = useCallback((event: ClipboardEvent<HTMLDivElement>) => captureCopiedSelection(event, runtime, {
108
+ ...(runtime?.contextSource ? { source: runtime.contextSource } : {}),
109
+ ...(resource ? { resource: { ...resource, snapshot: undefined } } : {}),
110
+ }), [resource, runtime]);
57
111
 
58
112
  return <div className={className} style={style} onCopy={onCopy}>{children}</div>;
59
113
  }
@@ -1,5 +1,7 @@
1
- import type { CSSProperties } from 'react';
1
+ import { useRef, useState, type CSSProperties } from 'react';
2
2
  import { useNotisRuntime } from '../provider';
3
+ import { isNotisSpaceSkeleton, pickSkeletonEntry, type NotisSkeletonEntry, type NotisSpaceSkeleton, type SkeletonBone } from '../skeleton';
4
+ import { useIsoLayoutEffect } from '../ui/util';
3
5
  import { pick, type Locale, type Words } from '../words/types';
4
6
 
5
7
  /** What a loading placeholder says to screen readers. */
@@ -15,18 +17,172 @@ export function Skeleton({ className, style }: { className?: string; style?: CSS
15
17
  borderRadius: 6, background: 'rgba(128,128,128,.18)', ...style }} />;
16
18
  }
17
19
 
20
+ /** Fill colours of the captured bone types: 0 leaf, 1 filled container, (2 is an outline), 3 divider. */
21
+ const BONE_FILL = ['rgba(128,128,128,.18)', 'rgba(128,128,128,.06)', '', 'rgba(128,128,128,.16)'] as const;
22
+ const BONE_OUTLINE = 'inset 0 0 0 1px rgba(128,128,128,.14)';
23
+ /** Most copies of one repeat row, and most bone elements all repeat rows draw together. */
24
+ const MAX_ROW_COPIES = 200;
25
+ const MAX_ROW_ELEMENTS = 4000;
26
+ /** Under this own width the region draws its 390 px capture, else its 1440 px one. */
27
+ const NARROW_UNDER = 800;
28
+ /** Shortest pane a captured frame stretches, and the line tolerance of its edges, in px. */
29
+ const FRAME_MIN = 120;
30
+ const FRAME_EDGE = 2;
31
+ /** How far, in percent of the width, two panes side by side may overlap at their shared edge. */
32
+ const FRAME_SEAM = 1;
33
+
34
+ /** Skeletons already checked, so many regions on one page check a shared file once. */
35
+ const checked = new WeakMap<object, boolean>();
36
+ function validSkeleton(value: unknown): NotisSpaceSkeleton | null {
37
+ if (typeof value !== 'object' || value === null) return null;
38
+ let ok = checked.get(value);
39
+ if (ok === undefined) { ok = isNotisSpaceSkeleton(value); checked.set(value, ok); }
40
+ return ok ? value as NotisSpaceSkeleton : null;
41
+ }
42
+
43
+ function boneStyle([x, y, w, h, r, t]: SkeletonBone): CSSProperties {
44
+ return { position: 'absolute', left: `${x}%`, width: `${w}%`, top: y, height: h, borderRadius: r, boxSizing: 'border-box',
45
+ ...(t === 2 ? { boxShadow: BONE_OUTLINE } : { background: BONE_FILL[t] }) };
46
+ }
47
+
48
+ const isPane = ([, y, , h, , t]: SkeletonBone) => (t === 1 || t === 2) && y <= FRAME_EDGE && h >= FRAME_MIN;
49
+ const bottomOf = (bone: SkeletonBone) => bone[1] + bone[3];
50
+
51
+ /**
52
+ * The bottom of the captured app frame, else null. A frame is panes that start at the region top and end on one line,
53
+ * two or more side by side across the width (a list beside its detail) with nothing starting below them, or
54
+ * square-cornered ones across the width ending at the bottom of the capture. They were measured at the capture's window height, so the drawing stretches them to
55
+ * the visible pane instead.
56
+ */
57
+ const frames = new WeakMap<NotisSkeletonEntry, number | null>();
58
+ function frameBottomOf(entry: NotisSkeletonEntry): number | null {
59
+ if (!frames.has(entry)) frames.set(entry, findFrameBottom(entry));
60
+ return frames.get(entry) ?? null;
61
+ }
62
+
63
+ function findFrameBottom({ height, bones, rows }: NotisSkeletonEntry): number | null {
64
+ const panes = bones.filter(isPane);
65
+ let frame: number | null = null;
66
+ for (const bottom of new Set(panes.map(bottomOf))) {
67
+ const line = panes.filter((pane) => Math.abs(bottomOf(pane) - bottom) <= FRAME_EDGE);
68
+ const spans = line.map(([x, , w]) => [x, x + w] as const).sort((a, b) => a[0] - b[0]);
69
+ // Side by side counts panes that start where the ones before them end; a card nested in a pane adds none.
70
+ let covered = 0, reach = 0, sideBySide = 0;
71
+ for (const [start, end] of spans) {
72
+ if (start >= reach - FRAME_SEAM) sideBySide += 1;
73
+ covered += Math.max(0, end - Math.max(start, reach));
74
+ reach = Math.max(reach, end);
75
+ }
76
+ // One wide card alone (or with cards nested in it) is content, not a frame: across the width it takes panes side by
77
+ // side. A row of tiles with the page going on below it is content too (a divider on the panes' own bottom edge is
78
+ // not below them). At the bottom of the capture, square-cornered panes across the whole width are the app's own
79
+ // (a phone shows one pane at a time); a rounded card there is still just the last content.
80
+ const edge = Math.max(...line.map(bottomOf));
81
+ const below = bones.some((bone) => bone[1] >= edge) || (rows ?? []).some((row) => row.y >= edge);
82
+ const atCaptureBottom = Math.abs(bottom - height) <= FRAME_EDGE && covered >= 95 && line.every((pane) => pane[4] === 0);
83
+ if ((sideBySide > 1 && covered >= 95 && !below) || atCaptureBottom) frame = Math.max(frame ?? 0, bottom);
84
+ }
85
+ return frame;
86
+ }
87
+
88
+ /** The nearest ancestor that scrolls vertically, else null. */
89
+ function scrollParentOf(node: HTMLElement): HTMLElement | null {
90
+ const view = node.ownerDocument.defaultView;
91
+ for (let parent = node.parentElement; parent && parent !== node.ownerDocument.body; parent = parent.parentElement) {
92
+ const overflow = view?.getComputedStyle(parent).overflowY;
93
+ if ((overflow === 'auto' || overflow === 'scroll' || overflow === 'overlay') && parent.clientHeight > 0) return parent;
94
+ }
95
+ return null;
96
+ }
97
+
98
+ /** The visible height from the box top to the bottom of its scroll parent (or the viewport), else the box's own height. */
99
+ function visibleHeightOf(node: HTMLElement, parent = scrollParentOf(node)): number {
100
+ const top = node.getBoundingClientRect().top;
101
+ if (parent) return parent.clientHeight - Math.max(0, top - parent.getBoundingClientRect().top);
102
+ const viewport = node.ownerDocument.documentElement.clientHeight;
103
+ if (viewport > 0) return viewport - Math.max(0, top);
104
+ return node.clientHeight;
105
+ }
106
+
18
107
  /** A whole view loading: a title bar and table, cards, graph or detail placeholders, named for screen readers in the Space's language. */
19
- export function ViewSkeleton({ variant = 'table', rows = 5, label, locale }: {
108
+ export function ViewSkeleton({ variant = 'table', rows = 5, label, locale, skeletonKey = 'main' }: {
20
109
  variant?: 'table' | 'cards' | 'graph' | 'detail'; rows?: number;
21
110
  /** What loads, said to screen readers ("Loading meetings"). Default "Loading content". */
22
111
  label?: Words | string;
23
112
  /** Default the Space's locale. */
24
113
  locale?: Locale;
114
+ /**
115
+ * The region this skeleton stands for. When the release carries bones measured for it at build time, they are drawn
116
+ * instead of `variant`, which is only the fallback. Give each separately loading region its own key. Default "main".
117
+ */
118
+ skeletonKey?: string;
25
119
  }) {
26
- const runtimeLocale = useNotisRuntime()?.context?.locale;
27
- const shown = locale ?? (runtimeLocale === 'fr' ? 'fr' : 'en');
28
- return <div role="status" aria-label={pick(label ?? SKELETON_WORDS.loading, shown)} aria-busy="true" data-notis-content-skeleton
29
- style={{ width: '100%', display: 'grid', gap: 16, padding: 24 }}>
120
+ const context = useNotisRuntime()?.context;
121
+ const shown = locale ?? (context?.locale === 'fr' ? 'fr' : 'en');
122
+ const captured = validSkeleton(context?.skeleton);
123
+ const region = captured?.regions[skeletonKey] ?? null;
124
+ const rootRef = useRef<HTMLDivElement | null>(null);
125
+ const [boxWidth, setBoxWidth] = useState<number | null>(null);
126
+ const [paneHeight, setPaneHeight] = useState(0);
127
+
128
+ useIsoLayoutEffect(() => {
129
+ const root = rootRef.current;
130
+ if (!region || !root) return;
131
+ const parent = scrollParentOf(root);
132
+ const measure = () => {
133
+ if (root.clientWidth > 0) setBoxWidth(root.clientWidth);
134
+ setPaneHeight(Math.max(0, Math.round(visibleHeightOf(root, parent))));
135
+ };
136
+ measure();
137
+ // Scrolling changes how much of the pane a region lower on the page shows; read at most once a frame.
138
+ const view = root.ownerDocument.defaultView;
139
+ let frame = 0;
140
+ const onScroll = () => {
141
+ if (!view?.requestAnimationFrame) { measure(); return; }
142
+ if (!frame) frame = view.requestAnimationFrame(() => { frame = 0; measure(); });
143
+ };
144
+ root.ownerDocument.addEventListener('scroll', onScroll, { capture: true, passive: true });
145
+ view?.addEventListener('resize', onScroll);
146
+ const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(measure);
147
+ observer?.observe(root);
148
+ if (parent) observer?.observe(parent);
149
+ return () => {
150
+ root.ownerDocument.removeEventListener('scroll', onScroll, { capture: true });
151
+ view?.removeEventListener('resize', onScroll);
152
+ if (frame) view?.cancelAnimationFrame(frame);
153
+ observer?.disconnect();
154
+ };
155
+ }, [region]);
156
+
157
+ const width = boxWidth ?? (typeof window !== 'undefined' && window.innerWidth > 0 ? window.innerWidth : 1440);
158
+ const entry = region ? pickSkeletonEntry(captured, skeletonKey, width < NARROW_UNDER ? '390' : '1440', shown) : null;
159
+ const status = { role: 'status', 'aria-label': pick(label ?? SKELETON_WORDS.loading, shown), 'aria-busy': true,
160
+ 'data-notis-content-skeleton': '', 'data-notis-skeleton-key': skeletonKey } as const;
161
+
162
+ if (entry) {
163
+ const repeats = entry.rows ?? [];
164
+ const budget = Math.floor(MAX_ROW_ELEMENTS / Math.max(1, repeats.reduce((sum, row) => sum + Math.max(1, row.bones.length), 0)));
165
+ const copies = repeats.map((row) => Math.min(MAX_ROW_COPIES, Math.max(1, budget),
166
+ Math.max(1, Math.ceil((paneHeight - row.y) / row.h))));
167
+ // A captured frame fills the visible pane: its panes end at the pane bottom and what lay below is clipped.
168
+ const frame = paneHeight > 0 ? frameBottomOf(entry) : null;
169
+ const height = frame !== null ? Math.max(FRAME_MIN, paneHeight)
170
+ : repeats.reduce((most, row, index) => Math.max(most, row.y + copies[index] * row.h), entry.height);
171
+ const drawn = (bone: SkeletonBone): SkeletonBone => frame !== null && isPane(bone)
172
+ && Math.abs(bottomOf(bone) - frame) <= FRAME_EDGE ? [bone[0], bone[1], bone[2], height - bone[1], bone[4], bone[5]] : bone;
173
+ return <div ref={rootRef} {...status}
174
+ style={{ position: 'relative', width: '100%', boxSizing: 'border-box', height, overflow: 'hidden' }}>
175
+ {entry.bones.map((bone, index) => <span key={index} aria-hidden="true" data-notis-bone={bone[5]} style={boneStyle(drawn(bone))} />)}
176
+ {repeats.map((row, rowIndex) => Array.from({ length: copies[rowIndex] }, (_, copy) =>
177
+ <div key={`${rowIndex}:${copy}`} aria-hidden="true" data-notis-bone-row={rowIndex}
178
+ style={{ position: 'absolute', left: 0, right: 0, top: row.y + copy * row.h, height: row.h }}>
179
+ {row.bones.map((bone, index) => <span key={index} data-notis-bone={bone[5]} style={boneStyle(bone)} />)}
180
+ </div>))}
181
+ </div>;
182
+ }
183
+
184
+ return <div ref={rootRef} {...status}
185
+ style={{ width: '100%', boxSizing: 'border-box', display: 'grid', gap: 16, padding: 24 }}>
30
186
  <Skeleton style={{ width: '32%', height: 28 }} />
31
187
  {variant === 'graph' ? <Skeleton style={{ height: 420 }} /> :
32
188
  <div style={{ display: 'grid', gap: 12, gridTemplateColumns: variant === 'cards' ? 'repeat(auto-fit,minmax(180px,1fr))' : '1fr' }}>
@@ -21,8 +21,18 @@ export function useAction<TInput extends Record<string, unknown> = Record<string
21
21
  return { call, loading: pending > 0, error };
22
22
  }
23
23
 
24
+ export interface UseActionQueryOptions extends UseQueryOptions {
25
+ /**
26
+ * Always the provider's current answer, even while the view opens (a check made right before a send, say): see
27
+ * `SpaceActionOptions.fresh`. A fresh read keeps its own cached answer, apart from the same read without it.
28
+ */
29
+ fresh?: boolean;
30
+ }
31
+
24
32
  export function useActionQuery<TResult = unknown>(actionId: string, inputs: Record<string, unknown>,
25
- options: UseQueryOptions = { readOnly: true }): UseQueryResult<TResult> {
33
+ options: UseActionQueryOptions = { readOnly: true }): UseQueryResult<TResult> {
26
34
  const { call } = useAction<Record<string, unknown>, TResult>(actionId);
27
- return useQuery(['action', actionId, inputs], () => call(inputs, { readOnly: true, dedupe: true }), options);
35
+ const fresh = options.fresh === true;
36
+ return useQuery(fresh ? ['action', actionId, inputs, 'fresh'] : ['action', actionId, inputs],
37
+ () => call(inputs, { readOnly: true, dedupe: true, ...(fresh ? { fresh: true } : {}) }), options);
28
38
  }
@@ -0,0 +1,125 @@
1
+ 'use client';
2
+
3
+ import { useCallback, useEffect } from 'react';
4
+ import { useQuery } from './useQuery';
5
+ import { useNotisRuntime } from '../provider';
6
+ import { pick, w, type Words } from '../words/types';
7
+ import type { SpaceAgentQueue } from '../space';
8
+
9
+ /** What the viewer sees of one agent's latest wake-up. `idle`: nothing woke it yet. */
10
+ export type AgentQueueStatus = SpaceAgentQueue['status'];
11
+
12
+ export const AGENT_QUEUE_WORDS = Object.freeze({
13
+ idle: w('Idle', 'Inactif'),
14
+ queued: w('Queued', 'En file d’attente'),
15
+ working: w('Working', 'En cours'),
16
+ waiting: w('Waiting for you', 'Attend ta réponse'),
17
+ failed: w('Failed', 'Échec'),
18
+ done: w('Done', 'Terminé'),
19
+ approvalRequired: w('Allow this agent to answer your comments', 'Autorise cet agent à répondre à tes commentaires'),
20
+ approve: w('Allow', 'Autoriser'),
21
+ openThread: w('Open the conversation', 'Ouvrir la conversation'),
22
+ unavailable: w('Agents are not available here', 'Les agents ne sont pas disponibles ici'),
23
+ } satisfies Record<string, Words>);
24
+
25
+ export interface UseAgentQueueResult {
26
+ status: AgentQueueStatus;
27
+ /** The status in the viewer's language. */
28
+ label: string;
29
+ /** The thread the agent works in for this scope; null until it first woke. */
30
+ threadId: string | null;
31
+ /** Items waiting in the quiet window (or for approval). */
32
+ pending: number;
33
+ /** True until the viewer allows this version's agents; offer `approve()`. */
34
+ approvalRequired: boolean;
35
+ /** Ask the viewer's permission for this Space version's agents. Held comments then wake their thread. */
36
+ approve: () => Promise<boolean>;
37
+ /** Open the agent's thread in the side chat. Resolves false when there is none or the host has no side chat. */
38
+ openThread: () => Promise<boolean>;
39
+ /** The link label in the viewer's language. */
40
+ openLabel: string;
41
+ /** Why to allow (`approvalRequired`) and the Allow button, in the viewer's language. */
42
+ approvalLabel: string;
43
+ approveLabel: string;
44
+ loading: boolean;
45
+ error: Error | null;
46
+ /** False on hosts without agents (Sites, links, the dev harness). */
47
+ available: boolean;
48
+ refresh: () => Promise<Error | null>;
49
+ }
50
+
51
+ const IDLE: SpaceAgentQueue = { status: 'idle', thread_id: null, pending: 0, approval_required: false, updated_at: null };
52
+ const ACTIVE_POLL_MS = 4_000;
53
+ const IDLE_POLL_MS = 15_000;
54
+
55
+ function visible(): boolean {
56
+ return typeof document === 'undefined' || document.visibilityState !== 'hidden';
57
+ }
58
+
59
+ /**
60
+ * One declared agent's latest wake-up for the signed-in viewer: Queued (in the 20 second quiet window),
61
+ * Working, Waiting for you, Failed or Done, with a link to its thread.
62
+ *
63
+ * ```tsx
64
+ * const queue = useAgentQueue('editor', deckKey);
65
+ * return (
66
+ * <span>
67
+ * {queue.label}
68
+ * {queue.approvalRequired ? <Button onClick={() => void queue.approve()}>{queue.approveLabel}</Button> : null}
69
+ * {queue.threadId ? <Button onClick={() => void queue.openThread()}>{queue.openLabel}</Button> : null}
70
+ * </span>
71
+ * );
72
+ * ```
73
+ *
74
+ * `scope` narrows to one item scope (the `Deck` column, or a root comment's key); omit it for the
75
+ * agent's latest wake-up anywhere in the Space. While the page is visible the status is read again every
76
+ * 4 seconds while the agent is queued or working, and every 15 seconds otherwise.
77
+ */
78
+ export function useAgentQueue(agentId: string, scope?: string | null): UseAgentQueueResult {
79
+ const runtime = useNotisRuntime();
80
+ const transport = runtime?.resource?.kind === 'space' ? runtime.spaceThreads : undefined;
81
+ const locale = runtime?.context?.locale === 'fr' ? 'fr' : 'en';
82
+ const scopeKey = typeof scope === 'string' && scope ? scope : null;
83
+ const query = useQuery<SpaceAgentQueue>(['agent-queue', agentId, scopeKey], async () => {
84
+ if (!transport) return IDLE;
85
+ const status = await transport.agentStatus(agentId, scopeKey ?? undefined);
86
+ return status.queue ? { ...IDLE, ...status.queue } : { ...IDLE, approval_required: !status.approved };
87
+ }, { readOnly: true, enabled: Boolean(transport) && Boolean(agentId), staleTimeMs: 2_000 });
88
+ const queue = query.data ?? IDLE;
89
+ const active = queue.status === 'queued' || queue.status === 'working' || queue.pending > 0;
90
+ const refetch = query.refetch;
91
+ // An interval, not a timeout keyed on the answer: a run reads the same "working" for minutes, and a
92
+ // timeout that waits for a changed answer stopped after one read and left "Working" on screen. While
93
+ // idle it still reads now and then, so a comment (yours or someone else's) shows "Queued" without a reload.
94
+ useEffect(() => {
95
+ if (!transport) return undefined;
96
+ const timer = setInterval(() => { if (visible()) void refetch(); }, active ? ACTIVE_POLL_MS : IDLE_POLL_MS);
97
+ return () => clearInterval(timer);
98
+ }, [active, refetch, transport]);
99
+ const approve = useCallback(async () => {
100
+ if (!transport) return false;
101
+ const result = await transport.approveAgents();
102
+ await refetch();
103
+ return result.approved === true;
104
+ }, [refetch, transport]);
105
+ const openThread = useCallback(async () => {
106
+ if (!transport || !queue.thread_id) return false;
107
+ return transport.open(queue.thread_id);
108
+ }, [queue.thread_id, transport]);
109
+ return {
110
+ status: queue.status,
111
+ label: pick(transport ? AGENT_QUEUE_WORDS[queue.status] : AGENT_QUEUE_WORDS.unavailable, locale),
112
+ threadId: queue.thread_id,
113
+ pending: queue.pending,
114
+ approvalRequired: queue.approval_required,
115
+ approve,
116
+ openThread,
117
+ openLabel: pick(AGENT_QUEUE_WORDS.openThread, locale),
118
+ approvalLabel: pick(AGENT_QUEUE_WORDS.approvalRequired, locale),
119
+ approveLabel: pick(AGENT_QUEUE_WORDS.approve, locale),
120
+ loading: query.loading,
121
+ error: query.error,
122
+ available: Boolean(transport),
123
+ refresh: refetch,
124
+ };
125
+ }
@@ -0,0 +1,142 @@
1
+ 'use client';
2
+
3
+ import { useCallback, useEffect, useRef, useState } from 'react';
4
+ import { useNotisRuntime } from '../provider';
5
+ import type { SpaceCloudComputerJobStatus } from '../space';
6
+
7
+ export interface UseCloudComputerJobOptions {
8
+ /** How often a running job is read, in ms (default 2000, at least 500). */
9
+ pollMs?: number;
10
+ /** The most log characters kept, the newest ones (default 200000). */
11
+ maxLogChars?: number;
12
+ }
13
+
14
+ export interface UseCloudComputerJobResult {
15
+ /** The job's last known state, or null before the first read (and without a job id). */
16
+ job: SpaceCloudComputerJobStatus | null;
17
+ /** The output read so far (its newest `maxLogChars` characters). */
18
+ log: string;
19
+ /** True until the job ended and its whole output was read. */
20
+ running: boolean;
21
+ /** The last read that failed; reading goes on. */
22
+ error: Error | null;
23
+ /** False on hosts without jobs (Sites, links, verification harnesses, older hosts) or without `cloudComputer: 'shell'`. */
24
+ available: boolean;
25
+ /** Stop the job. */
26
+ cancel(): Promise<SpaceCloudComputerJobStatus | null>;
27
+ /** Read again now (and resume after repeated failures). */
28
+ refresh(): void;
29
+ }
30
+
31
+ /** Log reads one poll makes at most while catching up with a job's output. */
32
+ const LOG_READS_PER_POLL = 8;
33
+ const LOG_CHUNK_BYTES = 65_536;
34
+ /** Failed reads in a row after which polling stops until `refresh()`. */
35
+ const MAX_FAILURES = 5;
36
+
37
+ function documentVisible(): boolean {
38
+ return typeof document === 'undefined' || document.visibilityState !== 'hidden';
39
+ }
40
+
41
+ /**
42
+ * Follow a background job started with `useCloudComputerShell().run(command, { detach: true })`: its state, and its
43
+ * output appended as it arrives, until the job ends. Reading pauses while the page is hidden.
44
+ *
45
+ * ```tsx
46
+ * const shell = useCloudComputerShell();
47
+ * const [jobId, setJobId] = useState<string | null>(null);
48
+ * const { job, log, running } = useCloudComputerJob(jobId);
49
+ * // start: setJobId((await shell.run('npm run build', { detach: true, cwd: { space: '' } })).job_id ?? null);
50
+ * ```
51
+ */
52
+ export function useCloudComputerJob(jobId: string | null | undefined, options: UseCloudComputerJobOptions = {}): UseCloudComputerJobResult {
53
+ const runtime = useNotisRuntime();
54
+ const transport = runtime?.spaceCloudComputer;
55
+ const available = Boolean(transport?.job && runtime?.space?.cloudComputer === 'shell');
56
+ const pollMs = Math.max(500, options.pollMs ?? 2000);
57
+ const maxLogChars = Math.max(1000, options.maxLogChars ?? 200_000);
58
+ const [job, setJob] = useState<SpaceCloudComputerJobStatus | null>(null);
59
+ const [log, setLog] = useState('');
60
+ const [error, setError] = useState<Error | null>(null);
61
+ const [done, setDone] = useState(false);
62
+ const [attempt, setAttempt] = useState(0);
63
+ const offset = useRef(0);
64
+ const following = useRef<string | null>(null);
65
+
66
+ useEffect(() => {
67
+ if (following.current !== (jobId || null)) {
68
+ following.current = jobId || null;
69
+ offset.current = 0;
70
+ setJob(null); setLog(''); setError(null); setDone(false);
71
+ }
72
+ if (!jobId || !available || !transport?.job) return undefined;
73
+ const read = transport.job.bind(transport);
74
+ let alive = true;
75
+ let timer: ReturnType<typeof setTimeout> | null = null;
76
+ let busy = false;
77
+ let finished = false;
78
+ let failures = 0;
79
+
80
+ const schedule = () => {
81
+ if (timer) clearTimeout(timer);
82
+ timer = setTimeout(() => { timer = null; void poll(); }, pollMs);
83
+ };
84
+ const poll = async () => {
85
+ if (!alive || busy || finished || !documentVisible()) return;
86
+ busy = true;
87
+ try {
88
+ const status = await read('job.status', { job_id: jobId });
89
+ if (!alive) return;
90
+ setJob(status);
91
+ const ended = status.status !== 'running';
92
+ let eof = false;
93
+ for (let reads = 0; reads < LOG_READS_PER_POLL; reads += 1) {
94
+ const chunk = await read('job.logs', { job_id: jobId, offset: offset.current, max_bytes: LOG_CHUNK_BYTES });
95
+ if (!alive) return;
96
+ const advanced = chunk.next_offset > offset.current;
97
+ offset.current = Math.max(offset.current, chunk.next_offset);
98
+ if (chunk.text) setLog((current) => (current + chunk.text).slice(-maxLogChars));
99
+ eof = chunk.eof;
100
+ // Keep reading only while a full chunk came back: the rest waits for the next poll.
101
+ if (eof || !advanced || chunk.next_offset - chunk.offset < LOG_CHUNK_BYTES) break;
102
+ }
103
+ failures = 0;
104
+ setError(null);
105
+ if (ended && eof) { finished = true; setDone(true); return; }
106
+ // An ended job whose output never reports its end is not read forever.
107
+ if (ended && status.log_bytes <= offset.current) { finished = true; setDone(true); return; }
108
+ schedule();
109
+ } catch (reason) {
110
+ if (!alive) return;
111
+ failures += 1;
112
+ setError(reason instanceof Error ? reason : new Error(String(reason)));
113
+ if (failures < MAX_FAILURES) schedule();
114
+ } finally {
115
+ busy = false;
116
+ }
117
+ };
118
+ const onVisibility = () => {
119
+ if (!alive) return;
120
+ if (documentVisible()) void poll();
121
+ else if (timer) { clearTimeout(timer); timer = null; }
122
+ };
123
+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisibility);
124
+ void poll();
125
+ return () => {
126
+ alive = false;
127
+ if (timer) clearTimeout(timer);
128
+ if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisibility);
129
+ };
130
+ }, [jobId, available, transport, pollMs, maxLogChars, attempt]);
131
+
132
+ const cancel = useCallback(async () => {
133
+ if (!jobId || !available || !transport?.job) return null;
134
+ const status = await transport.job('job.cancel', { job_id: jobId });
135
+ setJob(status);
136
+ setAttempt((value) => value + 1);
137
+ return status;
138
+ }, [jobId, available, transport]);
139
+ const refresh = useCallback(() => { setDone(false); setAttempt((value) => value + 1); }, []);
140
+
141
+ return { job, log, running: Boolean(jobId) && available && !done, error, available, cancel, refresh };
142
+ }