@notis_ai/cli 0.2.32 → 0.2.34

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 (95) hide show
  1. package/README.md +75 -11
  2. package/dist/agent-hooks/notis-agent-hook.mjs +4407 -905
  3. package/dist/base-skills/notis-cli/.notis-base-skill.json +1 -1
  4. package/dist/base-skills/notis-cli/SKILL.md +7 -3
  5. package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
  6. package/dist/base-skills/notis-spaces/SKILL.md +5 -3
  7. package/dist/base-skills/notis-spaces/references/comments.md +102 -0
  8. package/dist/base-skills/notis-spaces/references/context.md +20 -19
  9. package/dist/base-skills/notis-spaces/references/design.md +3 -2
  10. package/dist/base-skills/notis-spaces/references/sdk.md +135 -83
  11. package/dist/base-skills/notis-spaces/references/store.md +24 -1
  12. package/dist/sdk/src/components/NotisSelectionBoundary.tsx +13 -5
  13. package/dist/sdk/src/components/SelectionActionBar.tsx +45 -8
  14. package/dist/sdk/src/components/SpaceTextComments.tsx +293 -0
  15. package/dist/sdk/src/components/selectionRange.ts +65 -0
  16. package/dist/sdk/src/config.ts +3 -1
  17. package/dist/sdk/src/functions.ts +218 -0
  18. package/dist/sdk/src/hooks/useAgentQueue.ts +17 -28
  19. package/dist/sdk/src/hooks/useCollectionInteractions.ts +66 -9
  20. package/dist/sdk/src/hooks/useConnection.ts +102 -0
  21. package/dist/sdk/src/hooks/useFunction.ts +42 -0
  22. package/dist/sdk/src/hooks/useNotisSettings.ts +101 -0
  23. package/dist/sdk/src/index.ts +16 -4
  24. package/dist/sdk/src/interactions/shortcuts.tsx +6 -1
  25. package/dist/sdk/src/interactions/swipeDownToDismiss.ts +158 -0
  26. package/dist/sdk/src/interactions/textBoxTwoState.ts +174 -0
  27. package/dist/sdk/src/interactions.ts +17 -0
  28. package/dist/sdk/src/runtime.ts +16 -1
  29. package/dist/sdk/src/space.ts +401 -33
  30. package/dist/sdk/src/ui/comments/passageModel.ts +99 -0
  31. package/dist/sdk/src/ui/comments/textHighlights.ts +33 -0
  32. package/dist/skill-sync/index.js +262 -31
  33. package/dist/skill-sync-worker.mjs +515 -127
  34. package/dist/space-harness/host.js +389 -154
  35. package/dist/space-sdk/dist/chunk-3NPBCE6E.js +3 -0
  36. package/dist/space-sdk/dist/index.js +3 -3
  37. package/dist/space-sdk/dist/ui.js +16 -11
  38. package/dist/space-sdk/src/config.ts +3 -1
  39. package/dist/space-sdk/src/functions.ts +218 -0
  40. package/dist/space-sdk/src/hooks/useAgentQueue.d.ts +2 -13
  41. package/dist/space-sdk/src/hooks/useCollectionInteractions.d.ts +7 -0
  42. package/dist/space-sdk/src/hooks/useConnection.d.ts +42 -0
  43. package/dist/space-sdk/src/hooks/useFunction.d.ts +20 -0
  44. package/dist/space-sdk/src/hooks/useNotisSettings.d.ts +48 -0
  45. package/dist/space-sdk/src/index.d.ts +10 -4
  46. package/dist/space-sdk/src/interactions/shortcuts.d.ts +5 -0
  47. package/dist/space-sdk/src/runtime.d.ts +14 -1
  48. package/dist/space-sdk/src/space.ts +401 -33
  49. package/dist/space-sdk/src/tailwind-candidates.d.ts +400 -204
  50. package/dist/space-sdk/src/ui/comments/CommentPane.d.ts +90 -15
  51. package/dist/space-sdk/src/ui/comments/PassageComments.d.ts +4 -1
  52. package/dist/space-sdk/src/ui/comments/agentRuntime.d.ts +4 -2
  53. package/dist/space-sdk/src/ui/comments/commentDrafts.d.ts +63 -0
  54. package/dist/space-sdk/src/ui/comments/commentModel.d.ts +59 -88
  55. package/dist/space-sdk/src/ui/comments/commentWords.d.ts +32 -1
  56. package/dist/space-sdk/src/ui/comments/handover.d.ts +34 -0
  57. package/dist/space-sdk/src/ui/comments/hostComments.d.ts +13 -9
  58. package/dist/space-sdk/src/ui/comments/hostPanel.d.ts +113 -0
  59. package/dist/space-sdk/src/ui/comments/index.d.ts +7 -2
  60. package/dist/space-sdk/src/ui/comments/paneOutlet.d.ts +33 -0
  61. package/dist/space-sdk/src/ui/comments/paneParts.d.ts +71 -27
  62. package/dist/space-sdk/src/ui/comments/passageModel.d.ts +12 -36
  63. package/dist/space-sdk/src/ui/comments/reviewRun.d.ts +190 -0
  64. package/dist/space-sdk/src/ui/comments/useCommentRouting.d.ts +26 -4
  65. package/dist/space-sdk/src/ui/comments/useComments.d.ts +116 -77
  66. package/dist/space-sdk/src/ui/comments/usePassageComments.d.ts +8 -4
  67. package/dist/space-sdk/src/ui/index.d.ts +1 -1
  68. package/dist/space-sdk/src/ui/layout/SidePane.d.ts +3 -4
  69. package/dist/space-sdk/src/ui/period/dateFormat.d.ts +27 -8
  70. package/dist/view-renderer/dist/host.js +450 -215
  71. package/package.json +3 -3
  72. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +2 -2
  73. package/skills/notis-spaces/cli.md +3 -3
  74. package/src/cli.js +2 -1
  75. package/src/command-specs/index.js +3 -0
  76. package/src/command-specs/repository-secrets.js +171 -0
  77. package/src/command-specs/spaces.js +3 -3
  78. package/src/runtime/agent-credential.js +175 -0
  79. package/src/runtime/agent-identity.js +95 -19
  80. package/src/runtime/app-platform.js +8 -0
  81. package/src/runtime/auth-recovery.js +14 -0
  82. package/src/runtime/profiles.js +74 -2
  83. package/src/runtime/skill-sync/cloud-client.ts +33 -3
  84. package/src/runtime/skill-sync/index.ts +4 -3
  85. package/src/runtime/skill-sync/symlink-manager.ts +354 -35
  86. package/src/runtime/skill-sync/types.ts +14 -2
  87. package/src/runtime/space-functions.js +213 -0
  88. package/src/runtime/space-platform.js +12 -3
  89. package/src/runtime/space-source.js +116 -13
  90. package/src/runtime/space-test-server.js +22 -4
  91. package/src/runtime/space-verification.js +3 -1
  92. package/src/runtime/transport.js +15 -0
  93. package/dist/sdk/src/components/NotisCommentBoundary.tsx +0 -132
  94. package/dist/space-sdk/dist/chunk-I4Z4UFGB.js +0 -3
  95. package/dist/space-sdk/src/components/NotisCommentBoundary.d.ts +0 -26
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Space functions: server code a Space declares once in `defineSpace({ functions })` and Notis calls from the
3
+ * Space's views (`useFunction`), its HTTP API and MCP server, Notis agents, thread items, thread hooks and comment
4
+ * options. A handler never reaches the browser, has no network and no secrets, and reaches only what `uses` lists.
5
+ *
6
+ * ```ts
7
+ * // space.config.ts
8
+ * functions: {
9
+ * count_open: {
10
+ * description: 'Count the open pull requests of a repository.',
11
+ * kind: 'read',
12
+ * input: { type: 'object', additionalProperties: false, required: ['repo'], properties: { repo: { type: 'string' } } },
13
+ * expose: ['page', 'api', 'agents'],
14
+ * access: ['viewer', 'editor', 'key'],
15
+ * uses: { actions: ['list_pull_requests'] },
16
+ * handler: './functions/count-open.ts',
17
+ * },
18
+ * },
19
+ *
20
+ * // functions/count-open.ts
21
+ * import type { SpaceFunctionHandler } from '@notis/sdk';
22
+ * const handler: SpaceFunctionHandler<{ repo: string }, { open: number }> = async (input, ctx) => {
23
+ * const pulls = await ctx.actions.list_pull_requests({ repo: input.repo }) as { items: unknown[] };
24
+ * return { open: pulls.items.length };
25
+ * };
26
+ * export default handler;
27
+ * ```
28
+ *
29
+ * A handler module imports types only from `@notis/sdk`: the SDK's code is for the page, not for functions.
30
+ */
31
+ import type { SpaceCloudComputerLevel, SpaceThreadItemText } from './space';
32
+
33
+ /** What a call does: `read` changes nothing, `write` changes this Space's data, `action` reaches further. */
34
+ export type SpaceFunctionKind = 'read' | 'write' | 'action';
35
+ /** The ways in from outside the Space's own declarations: its views, its API and MCP server, Notis agents. */
36
+ export type SpaceFunctionExposure = 'page' | 'api' | 'agents';
37
+ /** Who may call: a Site or link visitor, a signed-in person who can open the Space, an editor, a Space key. */
38
+ export type SpaceFunctionRole = 'public' | 'viewer' | 'editor' | 'key';
39
+ /** Notis's built-in thread actions a function may run, only on a thread one of the Space's items is attached to. */
40
+ export type SpaceThreadOperation = 'archive' | 'unarchive' | 'read' | 'unread' | 'star' | 'unstar' | 'later' | 'back';
41
+ /** The built-in thread actions a Space can follow with a function (`threadHooks`). */
42
+ export type SpaceThreadHookEvent = SpaceThreadOperation | 'delete' | 'idle';
43
+
44
+ export interface SpaceFunctionUses {
45
+ /** This Space's declared `actions`, run through the sealed action pipeline with the caller as the actor. */
46
+ actions?: string[];
47
+ /** The caller's own cloud computer, at most the level the Space declares, once that person allowed it. */
48
+ cloudComputer?: SpaceCloudComputerLevel;
49
+ /** Built-in thread actions on a thread holding one of this Space's items. Needs `threadItems`. */
50
+ threads?: SpaceThreadOperation[];
51
+ }
52
+
53
+ export interface SpaceFunctionDeclaration {
54
+ /** What the function does and when to call it: agents read it as the tool's description. */
55
+ description: string;
56
+ kind: SpaceFunctionKind;
57
+ /** A closed object schema (`additionalProperties: false`), checked before the handler runs. */
58
+ input: { type: 'object'; additionalProperties: false; properties?: Record<string, unknown>; required?: readonly string[];
59
+ [key: string]: unknown };
60
+ /** Checked on what the handler returns, and given to agents as the tool's output schema. */
61
+ output?: Record<string, unknown>;
62
+ /** Default: none. A closed function still runs from this Space's thread items, thread hooks and comment options. */
63
+ expose?: SpaceFunctionExposure[];
64
+ /** Default: editors only. The handler reads the caller's role in `ctx.caller.role`. */
65
+ access?: SpaceFunctionRole[];
66
+ /** Everything the handler can reach. Undeclared: the handler only computes. */
67
+ uses?: SpaceFunctionUses;
68
+ /** Source-relative module whose default export is the handler. */
69
+ handler: string;
70
+ }
71
+
72
+ /** A comment option that runs a function when a person answers a choice comment with it (`commentOptions`). */
73
+ export interface SpaceCommentOption {
74
+ /** The option as people read it; an agent offers it by writing this label in a choice comment's options. */
75
+ label: SpaceThreadItemText;
76
+ /** A function whose `input` is `commentOptionInput`. */
77
+ function: string;
78
+ }
79
+
80
+ /** The `input` of a function a thread hook runs (`threadHooks`): copy it as written. */
81
+ export const threadHookInput = {
82
+ type: 'object', additionalProperties: false, required: ['event', 'thread', 'items', 'actor'],
83
+ properties: {
84
+ event: { type: 'string', enum: ['archive', 'unarchive', 'read', 'unread', 'star', 'unstar', 'later', 'back', 'delete'] },
85
+ actor: { type: 'string', enum: ['person', 'agent', 'notis'] },
86
+ thread: { type: 'object', additionalProperties: false, required: ['id', 'thread_id'], properties: {
87
+ id: { type: 'string' }, thread_id: { type: 'string' }, title: { type: ['string', 'null'] },
88
+ archived: { type: 'boolean' }, starred: { type: 'boolean' }, read: { type: 'boolean' },
89
+ later_until: { type: ['string', 'null'] } } },
90
+ items: { type: 'array', items: { type: 'object', additionalProperties: false,
91
+ required: ['id', 'kind', 'inputs'], properties: {
92
+ id: { type: 'string' }, kind: { type: 'string' }, inputs: { type: 'object' },
93
+ state: { type: ['string', 'null'] }, title: { type: ['string', 'null'] },
94
+ url: { type: ['string', 'null'] } } } },
95
+ },
96
+ } satisfies SpaceFunctionDeclaration['input'];
97
+
98
+ /** Input for the idle hook after the thread finishes its current work. */
99
+ export const threadIdleInput = {
100
+ ...threadHookInput,
101
+ required: [...threadHookInput.required, 'run_id'],
102
+ properties: {
103
+ ...threadHookInput.properties,
104
+ event: { type: 'string', enum: ['idle'] },
105
+ run_id: { type: 'string' },
106
+ },
107
+ } satisfies SpaceFunctionDeclaration['input'];
108
+
109
+ /**
110
+ * The `input` of the function a thread item kind settles with (`threadItems.<kind>.settle`): copy it as written.
111
+ * Notis runs it once when an item of that kind first reaches a final state, with the item and its thread.
112
+ */
113
+ export const threadSettleInput = {
114
+ type: 'object', additionalProperties: false, required: ['item', 'thread'],
115
+ properties: {
116
+ item: { type: 'object', additionalProperties: false, required: ['id', 'kind', 'inputs'], properties: {
117
+ id: { type: 'string' }, kind: { type: 'string' }, inputs: { type: 'object' },
118
+ state: { type: ['string', 'null'] }, title: { type: ['string', 'null'] },
119
+ url: { type: ['string', 'null'] } } },
120
+ thread: { type: 'object', additionalProperties: false, required: ['id', 'thread_id'], properties: {
121
+ id: { type: 'string' }, thread_id: { type: 'string' }, title: { type: ['string', 'null'] },
122
+ archived: { type: 'boolean' }, starred: { type: 'boolean' }, read: { type: 'boolean' },
123
+ later_until: { type: ['string', 'null'] } } },
124
+ },
125
+ } satisfies SpaceFunctionDeclaration['input'];
126
+
127
+ /** The `input` of a function a comment option runs (`commentOptions`): copy it as written. */
128
+ export const commentOptionInput = {
129
+ type: 'object', additionalProperties: false, required: ['option', 'comment'],
130
+ properties: {
131
+ option: { type: 'string' },
132
+ comment: { type: 'object', additionalProperties: false, required: ['id'], properties: {
133
+ id: { type: 'string' }, body: { type: 'string' }, view: { type: ['string', 'null'] },
134
+ page_key: { type: ['string', 'null'] },
135
+ anchor_keys: { type: 'array', items: { type: 'string' } } } },
136
+ },
137
+ } satisfies SpaceFunctionDeclaration['input'];
138
+
139
+ /** One of the Space's items on a thread, as a hook or an item action receives it. */
140
+ export interface SpaceFunctionThreadItem {
141
+ id: string; kind: string; inputs: Record<string, unknown>;
142
+ state?: string | null; title?: string | null; url?: string | null;
143
+ }
144
+ /** A thread as a function sees it. `id` is what `ctx.threads` takes. */
145
+ export interface SpaceFunctionThread {
146
+ id: string; thread_id: string; title?: string | null;
147
+ archived?: boolean; starred?: boolean; read?: boolean; later_until?: string | null;
148
+ }
149
+ /** What a thread hook's function receives: the built-in action that just happened, and who did it. */
150
+ export interface SpaceThreadHookInput {
151
+ event: Exclude<SpaceThreadHookEvent, 'idle'>;
152
+ /** The person, one of their agents, or Notis itself (an automatic change, or another function's thread action). */
153
+ actor: 'person' | 'agent' | 'notis';
154
+ thread: SpaceFunctionThread;
155
+ /** This Space's items attached to the thread. */
156
+ items: SpaceFunctionThreadItem[];
157
+ }
158
+ export interface SpaceThreadIdleInput extends Omit<SpaceThreadHookInput, 'event'> {
159
+ event: 'idle';
160
+ run_id: string;
161
+ }
162
+ /** What a thread item kind's settle function receives: the item that reached a final state, and its thread. */
163
+ export interface SpaceThreadSettleInput {
164
+ item: SpaceFunctionThreadItem;
165
+ thread: SpaceFunctionThread;
166
+ }
167
+ /** What a comment option's function receives. */
168
+ export interface SpaceCommentOptionInput {
169
+ /** The id of the declared option. */
170
+ option: string;
171
+ comment: { id: string; body?: string; view?: string | null; page_key?: string | null; anchor_keys?: string[] };
172
+ }
173
+
174
+ export interface SpaceFunctionCloudComputer {
175
+ facts(): Promise<Record<string, unknown>>;
176
+ /** Needs `uses.cloudComputer: 'shell'`. `cwd` is a folder inside the machine's workspace. */
177
+ run(input: { command: string; cwd?: string; timeoutMs?: number }): Promise<{ exit_code: number | null; output: string;
178
+ [key: string]: unknown }>;
179
+ }
180
+
181
+ /** What a handler can reach: nothing beyond the function's declared `uses`. */
182
+ export interface SpaceFunctionContext {
183
+ /** Who is calling. `userId` is null for a Site or link visitor and for a Space key. */
184
+ caller: { role: SpaceFunctionRole; userId: string | null };
185
+ space: { id: string; revision: number };
186
+ /** The way this call came in. */
187
+ via: SpaceFunctionExposure | 'thread_item' | 'thread_hook' | 'thread_settle' | 'comment_option';
188
+ /** One method per action named in `uses.actions`: the action's result, or a thrown error. */
189
+ actions: Record<string, (inputs?: Record<string, unknown>) => Promise<unknown>>;
190
+ /** The caller's own cloud computer. Calls throw until that person allowed this Space to use it. */
191
+ cloudComputer: SpaceFunctionCloudComputer;
192
+ /**
193
+ * Built-in thread actions named in `uses.threads`, by thread `id`. Notis refuses a thread none of this Space's
194
+ * items is attached to. `later` takes the time the thread comes back, as an ISO date with its zone.
195
+ */
196
+ threads: { [Operation in SpaceThreadOperation]: Operation extends 'later'
197
+ ? (threadId: string, until: string) => Promise<void> : (threadId: string) => Promise<void> };
198
+ /** Set when a thread item's action or settle runs the function: the item and its thread. */
199
+ item?: SpaceFunctionThreadItem & { thread: SpaceFunctionThread };
200
+ }
201
+
202
+ export type SpaceFunctionHandler<TInput = Record<string, unknown>, TOutput = unknown> =
203
+ (input: TInput, ctx: SpaceFunctionContext) => TOutput | Promise<TOutput>;
204
+
205
+ /** A function the page can call, as the host describes it (`runtime.space.functions`). */
206
+ export interface SpaceFunctionDescriptor {
207
+ kind: SpaceFunctionKind;
208
+ description?: string;
209
+ inputSchema: Record<string, unknown>;
210
+ outputSchema?: Record<string, unknown>;
211
+ /** True when visitors may call it too: what "view as the public" keeps. */
212
+ public?: boolean;
213
+ }
214
+
215
+ export interface SpaceFunctionCallOptions {
216
+ /** A caller-controlled idempotency key, kept across a deliberate retry of a write or an action. */
217
+ requestId?: string;
218
+ }
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
 
3
- import { useCallback, useEffect } from 'react';
3
+ import { useCallback, useEffect, useRef } from 'react';
4
4
  import { useQuery } from './useQuery';
5
5
  import { useNotisRuntime } from '../provider';
6
6
  import { pick, w, type Words } from '../words/types';
@@ -13,11 +13,8 @@ export const AGENT_QUEUE_WORDS = Object.freeze({
13
13
  idle: w('Idle', 'Inactif'),
14
14
  queued: w('Queued', 'En file d’attente'),
15
15
  working: w('Working', 'En cours'),
16
- waiting: w('Waiting for you', 'Attend ta réponse'),
17
16
  failed: w('Failed', 'Échec'),
18
17
  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
18
  openThread: w('Open the conversation', 'Ouvrir la conversation'),
22
19
  unavailable: w('Agents are not available here', 'Les agents ne sont pas disponibles ici'),
23
20
  } satisfies Record<string, Words>);
@@ -28,19 +25,12 @@ export interface UseAgentQueueResult {
28
25
  label: string;
29
26
  /** The thread the agent works in for this scope; null until it first woke. */
30
27
  threadId: string | null;
31
- /** Items waiting in the quiet window (or for approval). */
28
+ /** Items waiting in the quiet window. */
32
29
  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
30
  /** Open the agent's thread in the side chat. Resolves false when there is none or the host has no side chat. */
38
31
  openThread: () => Promise<boolean>;
39
32
  /** The link label in the viewer's language. */
40
33
  openLabel: string;
41
- /** Why to allow (`approvalRequired`) and the Allow button, in the viewer's language. */
42
- approvalLabel: string;
43
- approveLabel: string;
44
34
  loading: boolean;
45
35
  error: Error | null;
46
36
  /** False on hosts without agents (Sites, links, the dev harness). */
@@ -48,7 +38,7 @@ export interface UseAgentQueueResult {
48
38
  refresh: () => Promise<Error | null>;
49
39
  }
50
40
 
51
- const IDLE: SpaceAgentQueue = { status: 'idle', thread_id: null, pending: 0, approval_required: false, updated_at: null };
41
+ const IDLE: SpaceAgentQueue = { status: 'idle', thread_id: null, pending: 0, updated_at: null };
52
42
  const ACTIVE_POLL_MS = 4_000;
53
43
  const IDLE_POLL_MS = 15_000;
54
44
 
@@ -58,14 +48,13 @@ function visible(): boolean {
58
48
 
59
49
  /**
60
50
  * 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.
51
+ * Working, Failed or Done, with a link to its thread. A comment wakes its agent with no approval first.
62
52
  *
63
53
  * ```tsx
64
54
  * const queue = useAgentQueue('editor', deckKey);
65
55
  * return (
66
56
  * <span>
67
57
  * {queue.label}
68
- * {queue.approvalRequired ? <Button onClick={() => void queue.approve()}>{queue.approveLabel}</Button> : null}
69
58
  * {queue.threadId ? <Button onClick={() => void queue.openThread()}>{queue.openLabel}</Button> : null}
70
59
  * </span>
71
60
  * );
@@ -83,40 +72,40 @@ export function useAgentQueue(agentId: string, scope?: string | null): UseAgentQ
83
72
  const query = useQuery<SpaceAgentQueue>(['agent-queue', agentId, scopeKey], async () => {
84
73
  if (!transport) return IDLE;
85
74
  const status = await transport.agentStatus(agentId, scopeKey ?? undefined);
86
- return status.queue ? { ...IDLE, ...status.queue } : { ...IDLE, approval_required: !status.approved };
75
+ return status.queue ? { ...IDLE, ...status.queue } : IDLE;
87
76
  }, { readOnly: true, enabled: Boolean(transport) && Boolean(agentId), staleTimeMs: 2_000 });
88
77
  const queue = query.data ?? IDLE;
89
78
  const active = queue.status === 'queued' || queue.status === 'working' || queue.pending > 0;
90
79
  const refetch = query.refetch;
80
+ // A read still on its way is never replaced by the next tick: a refetch drops the read in flight, so a status read
81
+ // slower than the 4 second tick (a busy account) never landed and the label kept its first answer for good.
82
+ const fetching = useRef(false);
83
+ fetching.current = query.isFetching;
91
84
  // An interval, not a timeout keyed on the answer: a run reads the same "working" for minutes, and a
92
85
  // timeout that waits for a changed answer stopped after one read and left "Working" on screen. While
93
86
  // idle it still reads now and then, so a comment (yours or someone else's) shows "Queued" without a reload.
94
87
  useEffect(() => {
95
88
  if (!transport) return undefined;
96
- const timer = setInterval(() => { if (visible()) void refetch(); }, active ? ACTIVE_POLL_MS : IDLE_POLL_MS);
89
+ let reading = false;
90
+ const timer = setInterval(() => {
91
+ if (!visible() || reading || fetching.current) return;
92
+ reading = true;
93
+ void refetch().finally(() => { reading = false; });
94
+ }, active ? ACTIVE_POLL_MS : IDLE_POLL_MS);
97
95
  return () => clearInterval(timer);
98
96
  }, [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
97
  const openThread = useCallback(async () => {
106
98
  if (!transport || !queue.thread_id) return false;
107
99
  return transport.open(queue.thread_id);
108
100
  }, [queue.thread_id, transport]);
109
101
  return {
110
102
  status: queue.status,
111
- label: pick(transport ? AGENT_QUEUE_WORDS[queue.status] : AGENT_QUEUE_WORDS.unavailable, locale),
103
+ // A status this SDK has no word for (an older API's 'waiting', or none) reads as idle, never a crash.
104
+ label: pick(transport ? (AGENT_QUEUE_WORDS[queue.status] ?? AGENT_QUEUE_WORDS.idle) : AGENT_QUEUE_WORDS.unavailable, locale),
112
105
  threadId: queue.thread_id,
113
106
  pending: queue.pending,
114
- approvalRequired: queue.approval_required,
115
- approve,
116
107
  openThread,
117
108
  openLabel: pick(AGENT_QUEUE_WORDS.openThread, locale),
118
- approvalLabel: pick(AGENT_QUEUE_WORDS.approvalRequired, locale),
119
- approveLabel: pick(AGENT_QUEUE_WORDS.approve, locale),
120
109
  loading: query.loading,
121
110
  error: query.error,
122
111
  available: Boolean(transport),
@@ -31,6 +31,8 @@ import { useLongPressSelection } from './useLongPressSelection';
31
31
  import { useMarqueeSelection, type SelectionMarqueeRect } from './useMarqueeSelection';
32
32
 
33
33
  export const COLLECTION_ITEM_ATTRIBUTE = 'data-notis-collection-item-id';
34
+ /** Frames a revealed item is waited for before its focus is given up (about a third of a second). */
35
+ const REVEAL_FOCUS_FRAMES = 20;
34
36
  const LEGACY_ROW_ATTRIBUTE = 'data-notis-row-id';
35
37
  const INTERACTIVE_SELECTOR = 'button, a, input, textarea, select, [role="button"], [contenteditable]:not([contenteditable="false"])';
36
38
 
@@ -105,6 +107,11 @@ export interface UseCollectionInteractionsOptions<T> {
105
107
  shortcutPriority?: number;
106
108
  resolveNextId?: (context: CollectionNavigationContext<T>) => string | null;
107
109
  onActiveItemChange?: (id: string | null) => void;
110
+ /**
111
+ * For a view that draws only part of its items (the rows on screen): brings an item into view so it is drawn.
112
+ * Called when the item to focus has no element; the controller then focuses it as soon as it is drawn.
113
+ */
114
+ revealItem?: (id: string) => void;
108
115
  actions?: CollectionAction<T>[];
109
116
  }
110
117
 
@@ -123,6 +130,8 @@ export interface CollectionInteractionController<T> {
123
130
  * that removes the active item continues this way (iOS Photos), else the other way at the edge.
124
131
  */
125
132
  travelDirection: () => TravelDirection;
133
+ /** Moves the active item one step, as J/K or the arrows do (a swipe between open items on a phone). */
134
+ move: (direction: CollectionNavigationDirection) => void;
126
135
  getActionBarProps: () => Pick<MultiSelectActionBarProps, 'selectedCount' | 'actions' | 'collectionOwnerId' | 'isAvailable' | 'shortcutsEnabled' | 'onClearSelection'>;
127
136
 
128
137
  isSelected: (id: string) => boolean;
@@ -224,6 +233,7 @@ export function useCollectionInteractions<T>(
224
233
  shortcutPriority = 0,
225
234
  resolveNextId,
226
235
  onActiveItemChange,
236
+ revealItem,
227
237
  actions: actionDefinitions = [],
228
238
  } = options;
229
239
 
@@ -252,6 +262,7 @@ export function useCollectionInteractions<T>(
252
262
  const onActiveItemChangeRef = useRef(onActiveItemChange);
253
263
  const onActivateRef = useRef(onActivate);
254
264
  const resolveNextIdRef = useRef(resolveNextId);
265
+ const revealItemRef = useRef(revealItem);
255
266
  const containerRef = useRef<HTMLElement | null>(null);
256
267
  const [containerElement, setContainerElement] = useState<HTMLElement | null>(null);
257
268
  const setContainerRef = useCallback((node: HTMLElement | null) => {
@@ -277,6 +288,7 @@ export function useCollectionInteractions<T>(
277
288
  onActiveItemChangeRef.current = onActiveItemChange;
278
289
  onActivateRef.current = onActivate;
279
290
  resolveNextIdRef.current = resolveNextId;
291
+ revealItemRef.current = revealItem;
280
292
 
281
293
  const itemById = useMemo(() => new Map(items.map((item) => [getId(item), item])), [getId, items]);
282
294
  const selectableIds = useMemo(
@@ -325,7 +337,7 @@ export function useCollectionInteractions<T>(
325
337
  const next = id && selectableIdsRef.current.includes(id) ? id : null;
326
338
  if (activeIdRef.current === next) return;
327
339
  // A click or focus further up or down sets the way; keys set it themselves (moveActive), a wrap included.
328
- const travel = reason === 'items-changed' ? null : travelBetween(selectableIdsRef.current, activeIdRef.current, next);
340
+ const travel = reason === 'items-changed' || reason === 'navigate' ? null : travelBetween(selectableIdsRef.current, activeIdRef.current, next);
329
341
  if (travel) travelRef.current = travel;
330
342
  activeIdRef.current = next;
331
343
  if (controlledActiveId === undefined) setUncontrolledActiveId(next);
@@ -447,13 +459,52 @@ export function useCollectionInteractions<T>(
447
459
  }
448
460
  }, [commitSelection, selectableIds, setActive, setAnchor]);
449
461
 
462
+ const pendingRevealRef = useRef<number | null>(null);
463
+ useEffect(() => () => {
464
+ if (pendingRevealRef.current !== null) cancelAnimationFrame(pendingRevealRef.current);
465
+ }, []);
450
466
  const focusItem = useCallback((id: string) => {
451
- const nodes = containerRef.current?.querySelectorAll<HTMLElement>(`[${COLLECTION_ITEM_ATTRIBUTE}]`);
452
- const node = nodes ? Array.from(nodes).find(
453
- (candidate) => candidate.getAttribute(COLLECTION_ITEM_ATTRIBUTE) === id && isInteractionElementVisible(candidate),
454
- ) : null;
455
- node?.focus({ preventScroll: true });
456
- node?.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
467
+ if (pendingRevealRef.current !== null) {
468
+ cancelAnimationFrame(pendingRevealRef.current);
469
+ pendingRevealRef.current = null;
470
+ }
471
+ const find = () => {
472
+ const nodes = containerRef.current?.querySelectorAll<HTMLElement>(`[${COLLECTION_ITEM_ATTRIBUTE}]`);
473
+ return nodes ? Array.from(nodes).find(
474
+ (candidate) => candidate.getAttribute(COLLECTION_ITEM_ATTRIBUTE) === id && isInteractionElementVisible(candidate),
475
+ ) ?? null : null;
476
+ };
477
+ const focus = (node: HTMLElement) => {
478
+ node.focus({ preventScroll: true });
479
+ node.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
480
+ };
481
+ const node = find();
482
+ if (node) { focus(node); return; }
483
+ // A view that draws only the items on screen: ask it to draw this one, then focus it once it is there.
484
+ // Another focus, the active item moving on, or the person putting focus somewhere else (a field, another
485
+ // surface) drops the wait.
486
+ if (!revealItemRef.current || typeof requestAnimationFrame !== 'function') return;
487
+ // Focus is read in the page and, for a view drawn in a shadow root, inside that root too: the page only sees
488
+ // the root's host there.
489
+ const ownerDocument = containerRef.current?.ownerDocument;
490
+ const root = containerRef.current?.getRootNode();
491
+ const focusPlace = () => [
492
+ ownerDocument?.activeElement ?? null,
493
+ root && root !== ownerDocument && 'activeElement' in root ? (root as ShadowRoot).activeElement : null,
494
+ ] as const;
495
+ const before = focusPlace();
496
+ revealItemRef.current(id);
497
+ let frames = REVEAL_FOCUS_FRAMES;
498
+ const retry = () => {
499
+ pendingRevealRef.current = null;
500
+ if (activeIdRef.current !== id) return;
501
+ const now = focusPlace();
502
+ if ((now[0] && now[0] !== before[0] && now[0] !== ownerDocument?.body) || (now[1] && now[1] !== before[1])) return;
503
+ const revealed = find();
504
+ if (revealed) { focus(revealed); return; }
505
+ if (--frames > 0) pendingRevealRef.current = requestAnimationFrame(retry);
506
+ };
507
+ pendingRevealRef.current = requestAnimationFrame(retry);
457
508
  }, []);
458
509
 
459
510
  const focusPointerItem = useCallback((id: string) => {
@@ -515,8 +566,9 @@ export function useCollectionInteractions<T>(
515
566
  keyboardRangeBaseRef.current = new Set();
516
567
  setAnchor(next, 'navigate');
517
568
  }
518
- setActive(next, extend ? 'range' : 'navigate');
569
+ // Set before the change is reported, so the page reads the way of this very move (a wrap included).
519
570
  travelRef.current = forward ? 'next' : 'previous';
571
+ setActive(next, extend ? 'range' : 'navigate');
520
572
  const nextId = next;
521
573
  requestAnimationFrame(() => focusItem(nextId));
522
574
  }, [focusItem, replaceRange, setActive, setAnchor]);
@@ -542,7 +594,10 @@ export function useCollectionInteractions<T>(
542
594
  const extendUp = filterShortcutKeys(keyboard.extendPrevious, (key) => !key.toLowerCase().endsWith('arrowleft'));
543
595
  // An empty collection has nothing to dismiss. Let the enclosing surface
544
596
  // own Escape (for example Desktop's final Inbox navigation layer).
545
- add('collection.clear', 'Clear selection', selectedIds.size > 0 ? keyboard.clear : false, clear);
597
+ // Bound only while something is selected, so the engine clears it whether or not a selected item is drawn.
598
+ if (selectedIds.size > 0 && keyboard.clear) {
599
+ definitions.push({ id: 'collection.clear', label: 'Clear selection', keys: keyboard.clear, onTrigger: clear, whileSelected: true });
600
+ }
546
601
  add('collection.select-all', 'Select all visible items', selectionMode === 'none' ? false : keyboard.selectAll, selectAll);
547
602
  add('collection.toggle', 'Toggle active item', selectionMode === 'none' ? false : keyboard.toggle, () => {
548
603
  const id = activeIdRef.current ?? anchorIdRef.current;
@@ -689,6 +744,7 @@ export function useCollectionInteractions<T>(
689
744
 
690
745
  const getSelectedItems = useCallback(() => getItemsForIds(selectedIdsRef.current), [getItemsForIds]);
691
746
  const travelDirection = useCallback(() => travelRef.current, []);
747
+ const move = useCallback((direction: CollectionNavigationDirection) => moveActive(direction), [moveActive]);
692
748
  const isSelected = useCallback((id: string) => selectedIds.has(id), [selectedIds]);
693
749
 
694
750
  const actionContext = useMemo<CollectionActionContext<T>>(() => ({
@@ -757,6 +813,7 @@ export function useCollectionInteractions<T>(
757
813
  dragRect,
758
814
  actions: resolvedActions,
759
815
  travelDirection,
816
+ move,
760
817
  getActionBarProps,
761
818
  isSelected,
762
819
  getSelectedItems,
@@ -0,0 +1,102 @@
1
+ 'use client';
2
+
3
+ import { useCallback, useState } from 'react';
4
+ import { useQuery } from './useQuery';
5
+ import { useNotisRuntime } from '../provider';
6
+ import { queryKey } from '../queryCache';
7
+ import { SPACE_TOOLKIT_SLUG, spaceQueryKey, type SpaceConnection } from '../space';
8
+ import type { NotisRuntime } from '../runtime';
9
+
10
+ /** Cache key of one toolkit's read; every mounted `useConnection(toolkit)` reads again after a connect. */
11
+ export function connectionQueryKey(toolkit: string) {
12
+ return ['connection', toolkit] as const;
13
+ }
14
+
15
+ /** Marks a toolkit's read stale in the host cache, so every mounted `useConnection` of it reads again. */
16
+ export function invalidateConnection(runtime: NotisRuntime | null, toolkit: string): void {
17
+ try {
18
+ runtime?.queryClient?.invalidate(queryKey(spaceQueryKey(runtime, connectionQueryKey(toolkit))));
19
+ } catch {
20
+ // A host without a Space access context has no shared cache to refresh.
21
+ }
22
+ }
23
+
24
+ export interface UseConnectionResult {
25
+ /** False where the host cannot answer (Sites, shared links, verification, previews offline, older hosts). */
26
+ available: boolean;
27
+ /** The viewer's own account in this app works now. */
28
+ connected: boolean;
29
+ /** The GitHub login for GitHub, else the name the person gave the account, else null. */
30
+ account: string | null;
31
+ /** The newest account's state (`ACTIVE`, `EXPIRED`, `FAILED`...), null when there is none or while loading. */
32
+ status: string | null;
33
+ loading: boolean;
34
+ /** The connect window is open and the host is waiting for the account to work. */
35
+ connecting: boolean;
36
+ error: Error | null;
37
+ /**
38
+ * Opens the Portal's connect flow for this app (a sign-in window on the web, the browser in Desktop). Call it from
39
+ * the person's own click: the host refuses a call no click started. Resolves true once the account works, false
40
+ * when the person closed the window or it timed out, and rejects with a message to show when the host refused.
41
+ */
42
+ connect: () => Promise<boolean>;
43
+ /** Read again. */
44
+ refresh: () => Promise<void>;
45
+ }
46
+
47
+ const unavailable = (toolkit: string): SpaceConnection =>
48
+ ({ toolkit, available: false, connected: false, account: null, status: null });
49
+
50
+ /**
51
+ * The signed-in viewer's own account in one connected app, and a button's way to connect it.
52
+ *
53
+ * ```tsx
54
+ * const github = useConnection('github');
55
+ * if (!github.available) return <OpenInNotis />;
56
+ * return github.connected
57
+ * ? <p>GitHub: {github.account}</p>
58
+ * : <Button onClick={() => github.connect()} disabled={github.connecting}>Connect GitHub</Button>;
59
+ * ```
60
+ *
61
+ * Needs no declaration: it reads only the viewer's own account and never a credential. On a Site, a shared link, in
62
+ * verification and in the vite preview it answers `available: false`; keep a fallback (a link to Integrations).
63
+ */
64
+ export function useConnection(toolkit: string): UseConnectionResult {
65
+ const runtime = useNotisRuntime();
66
+ const slug = typeof toolkit === 'string' ? toolkit.trim().toLowerCase() : '';
67
+ const valid = SPACE_TOOLKIT_SLUG.test(slug);
68
+ const transport = valid ? runtime?.spaceConnections : undefined;
69
+ const [connecting, setConnecting] = useState(false);
70
+ const query = useQuery<SpaceConnection>(connectionQueryKey(slug), async () => (
71
+ transport ? transport.read(slug) : unavailable(slug)
72
+ ), { readOnly: true, staleTimeMs: 30_000 });
73
+
74
+ const connect = useCallback(async () => {
75
+ if (!transport) throw new Error('Connect this app from the Space in Notis.');
76
+ setConnecting(true);
77
+ try {
78
+ // Called before anything awaits: the host opens its window inside the person's click.
79
+ const after = await transport.connect(slug);
80
+ invalidateConnection(runtime, slug);
81
+ await query.refetch();
82
+ return after.connected;
83
+ } finally {
84
+ setConnecting(false);
85
+ }
86
+ }, [query.refetch, runtime, slug, transport]);
87
+
88
+ const refresh = useCallback(async () => { await query.refetch(); }, [query.refetch]);
89
+ const data = query.data ?? (!transport ? unavailable(slug) : null);
90
+ return {
91
+ // A read that failed keeps the hook available: `error` says why, and `refresh` or `connect` still work.
92
+ available: Boolean(transport) && data?.available !== false,
93
+ connected: data?.connected === true,
94
+ account: data?.account ?? null,
95
+ status: data?.status ?? null,
96
+ loading: query.loading,
97
+ connecting,
98
+ error: query.error,
99
+ connect,
100
+ refresh,
101
+ };
102
+ }
@@ -0,0 +1,42 @@
1
+ 'use client';
2
+
3
+ import { useCallback, useState } from 'react';
4
+ import { useNotisRuntime } from '../provider';
5
+ import { useQuery, type UseQueryOptions, type UseQueryResult } from './useQuery';
6
+ import type { SpaceFunctionCallOptions } from '../functions';
7
+
8
+ /**
9
+ * Call one of this Space's functions exposed to its views (`expose: ['page']`). The handler runs on Notis's side;
10
+ * the page only gets its result.
11
+ *
12
+ * ```tsx
13
+ * const settle = useFunction<{ thread: string }, { settled: boolean }>('settle_thread');
14
+ * <Button disabled={settle.loading} onClick={() => void settle.call({ thread: id })}>Settle</Button>
15
+ * ```
16
+ */
17
+ export function useFunction<TInput extends Record<string, unknown> = Record<string, unknown>, TResult = unknown>(name: string): {
18
+ call: (input: TInput, options?: SpaceFunctionCallOptions) => Promise<TResult>; loading: boolean; error: Error | null;
19
+ /** False on hosts that cannot run functions, or when this view may not call this one. */
20
+ available: boolean;
21
+ } {
22
+ const runtime = useNotisRuntime();
23
+ const [pending, setPending] = useState(0);
24
+ const [error, setError] = useState<Error | null>(null);
25
+ const available = runtime?.resource?.kind === 'space' && Boolean(runtime.callFunction)
26
+ && Boolean(runtime.space?.functions && Object.hasOwn(runtime.space.functions, name));
27
+ const call = useCallback(async (input: TInput, options?: SpaceFunctionCallOptions) => {
28
+ if (runtime?.resource?.kind !== 'space' || !runtime.callFunction) throw new Error('A Space function runtime is required.');
29
+ setPending((value) => value + 1); setError(null);
30
+ try { return await runtime.callFunction<TResult>(name, input, options); }
31
+ catch (cause) { const failure = cause instanceof Error ? cause : new Error(String(cause)); setError(failure); throw failure; }
32
+ finally { setPending((value) => value - 1); }
33
+ }, [runtime, name]);
34
+ return { call, loading: pending > 0, error, available };
35
+ }
36
+
37
+ /** A `read` function as a cached query: it runs again when `input` changes. */
38
+ export function useFunctionQuery<TResult = unknown>(name: string, input: Record<string, unknown>,
39
+ options: UseQueryOptions = { readOnly: true }): UseQueryResult<TResult> {
40
+ const { call } = useFunction<Record<string, unknown>, TResult>(name);
41
+ return useQuery(['function', name, input], () => call(input), options);
42
+ }