@opengeni/react 0.20.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-6BXBGJ3B.js → chunk-6XUS5VFM.js} +2 -2
- package/dist/{chunk-MRSECXRP.js → chunk-AVPU5PMC.js} +87 -57
- package/dist/chunk-AVPU5PMC.js.map +1 -0
- package/dist/{chunk-HHFA4AFX.js → chunk-I3BJZIG5.js} +15 -1
- package/dist/chunk-I3BJZIG5.js.map +1 -0
- package/dist/{chunk-LAZ2A743.js → chunk-RDPDU4TA.js} +8 -7
- package/dist/chunk-RDPDU4TA.js.map +1 -0
- package/dist/{chunk-6UT5OC3P.js → chunk-SHOFILHJ.js} +130 -16
- package/dist/chunk-SHOFILHJ.js.map +1 -0
- package/dist/{chunk-EBTT3MYN.js → chunk-YDNWMKXO.js} +11 -1
- package/dist/chunk-YDNWMKXO.js.map +1 -0
- package/dist/{composer-DvUaa5ki.d.ts → composer-BXb0Q1HF.d.ts} +19 -5
- package/dist/composer.d.ts +3 -3
- package/dist/composer.js +3 -3
- package/dist/fleet-decision-projection-SLNZMS42.js +241 -0
- package/dist/fleet-decision-projection-SLNZMS42.js.map +1 -0
- package/dist/fleet-decision-row-GGCAT4E4.js +351 -0
- package/dist/fleet-decision-row-GGCAT4E4.js.map +1 -0
- package/dist/index.d.ts +14 -11
- package/dist/index.js +466 -244
- package/dist/index.js.map +1 -1
- package/dist/machines.d.ts +1 -1
- package/dist/machines.js +2 -2
- package/dist/{queue-surface-implementation-NQMV2ML3.js → queue-surface-implementation-3UW3MIIR.js} +9 -9
- package/dist/queue-surface-implementation-3UW3MIIR.js.map +1 -0
- package/dist/{session-Gd4iVPYw.d.ts → session-BEvtFWhe.d.ts} +71 -24
- package/dist/{session-context-DIFFlXKc.d.ts → session-context-rgrfElMl.d.ts} +7 -1
- package/dist/session.d.ts +3 -3
- package/dist/session.js +7 -3
- package/dist/{use-composer-BCfm4mzX.d.ts → use-composer-BnEzheSk.d.ts} +13 -20
- package/package.json +2 -2
- package/src/client.ts +4 -0
- package/src/components/composer.tsx +7 -6
- package/src/components/message-timeline.tsx +197 -25
- package/src/components/queue-draft-policy.ts +18 -0
- package/src/components/queue-surface-implementation.tsx +6 -10
- package/src/components/queue-surface.tsx +1 -0
- package/src/hooks/use-composer.ts +143 -83
- package/src/hooks/use-file-attachments.ts +95 -2
- package/src/hooks/use-goal.ts +22 -4
- package/src/hooks/use-session-mcp-approval-policy.ts +161 -0
- package/src/hooks/use-workspace-sessions.ts +30 -5
- package/src/index.ts +9 -0
- package/src/session-context.ts +25 -0
- package/src/session.ts +10 -0
- package/src/timeline/activity-rail.tsx +17 -1
- package/src/timeline/fleet-decision-projection.ts +366 -0
- package/src/timeline/fleet-decision-row.tsx +412 -0
- package/src/timeline/index.ts +2 -0
- package/src/timeline/projection.ts +19 -8
- package/src/timeline/tool-display-name.ts +16 -0
- package/src/timeline/tool-renderers.tsx +1 -1
- package/src/timeline/types.ts +76 -16
- package/dist/chunk-6UT5OC3P.js.map +0 -1
- package/dist/chunk-EBTT3MYN.js.map +0 -1
- package/dist/chunk-HHFA4AFX.js.map +0 -1
- package/dist/chunk-LAZ2A743.js.map +0 -1
- package/dist/chunk-MRSECXRP.js.map +0 -1
- package/dist/queue-surface-implementation-NQMV2ML3.js.map +0 -1
- /package/dist/{chunk-6BXBGJ3B.js.map → chunk-6XUS5VFM.js.map} +0 -0
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
useMutationRunner,
|
|
9
9
|
useOpenGeni,
|
|
10
10
|
usePolledValue
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-I3BJZIG5.js";
|
|
12
12
|
|
|
13
13
|
// src/types/machines.ts
|
|
14
14
|
function connectionStatusForState(state) {
|
|
@@ -1953,4 +1953,4 @@ export {
|
|
|
1953
1953
|
EnrollmentDeviceFlow,
|
|
1954
1954
|
EnrollmentConsent
|
|
1955
1955
|
};
|
|
1956
|
-
//# sourceMappingURL=chunk-
|
|
1956
|
+
//# sourceMappingURL=chunk-6XUS5VFM.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useEmbeddedSession,
|
|
3
3
|
useSessionEventTrigger
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-I3BJZIG5.js";
|
|
5
5
|
|
|
6
6
|
// src/hooks/use-composer.ts
|
|
7
7
|
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
|
|
@@ -21,31 +21,32 @@ function useComposer(sessionId, options = {}) {
|
|
|
21
21
|
const [draftConflict, setDraftConflict] = useState(null);
|
|
22
22
|
const [restoredResources, setRestoredResources] = useState([]);
|
|
23
23
|
const pendingClientEventId = useRef(null);
|
|
24
|
+
const valueRef = useRef("");
|
|
24
25
|
const draftRef = useRef(null);
|
|
25
|
-
const
|
|
26
|
-
const draftReadGeneration = useRef(0);
|
|
26
|
+
const restoredResourcesRef = useRef([]);
|
|
27
27
|
const localEditRevision = useRef(0);
|
|
28
28
|
const targetGeneration = useRef(0);
|
|
29
|
+
const draftReadGeneration = useRef(0);
|
|
29
30
|
const lastSavedSignature = useRef(null);
|
|
30
31
|
const saveChain = useRef(Promise.resolve());
|
|
31
32
|
const onSent = options.onSent;
|
|
32
33
|
const onDraftApplied = options.onDraftApplied;
|
|
33
34
|
const sendExtrasRef = useRef(options.sendExtras);
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const
|
|
38
|
-
const liveExtrasVersion = JSON.stringify(liveExtras);
|
|
35
|
+
sendExtrasRef.current = options.sendExtras;
|
|
36
|
+
const sendBlockedRef = useRef(options.sendBlocked);
|
|
37
|
+
sendBlockedRef.current = options.sendBlocked;
|
|
38
|
+
const liveExtrasVersion = JSON.stringify(resolveSendExtras(options.sendExtras));
|
|
39
39
|
const targetKeyRef = useRef(targetKey);
|
|
40
40
|
useLayoutEffect(() => {
|
|
41
41
|
if (targetKeyRef.current === targetKey) return;
|
|
42
42
|
targetKeyRef.current = targetKey;
|
|
43
43
|
targetGeneration.current += 1;
|
|
44
|
+
draftReadGeneration.current += 1;
|
|
44
45
|
pendingClientEventId.current = null;
|
|
45
46
|
localEditRevision.current = 0;
|
|
46
|
-
|
|
47
|
+
valueRef.current = "";
|
|
47
48
|
draftRef.current = null;
|
|
48
|
-
|
|
49
|
+
restoredResourcesRef.current = [];
|
|
49
50
|
lastSavedSignature.current = null;
|
|
50
51
|
saveChain.current = Promise.resolve();
|
|
51
52
|
setStateTargetKey(targetKey);
|
|
@@ -66,6 +67,8 @@ function useComposer(sessionId, options = {}) {
|
|
|
66
67
|
if (!durableDrafts) {
|
|
67
68
|
pendingClientEventId.current = null;
|
|
68
69
|
localEditRevision.current += 1;
|
|
70
|
+
valueRef.current = next.text;
|
|
71
|
+
restoredResourcesRef.current = next.resources;
|
|
69
72
|
draftRef.current = null;
|
|
70
73
|
lastSavedSignature.current = null;
|
|
71
74
|
setDraft(null);
|
|
@@ -74,7 +77,9 @@ function useComposer(sessionId, options = {}) {
|
|
|
74
77
|
setDraftConflict(null);
|
|
75
78
|
return;
|
|
76
79
|
}
|
|
80
|
+
valueRef.current = next.text;
|
|
77
81
|
draftRef.current = next;
|
|
82
|
+
restoredResourcesRef.current = next.resources;
|
|
78
83
|
lastSavedSignature.current = draftSignature(draftPayload(next));
|
|
79
84
|
localEditRevision.current += 1;
|
|
80
85
|
pendingClientEventId.current = null;
|
|
@@ -87,7 +92,7 @@ function useComposer(sessionId, options = {}) {
|
|
|
87
92
|
[durableDrafts, onDraftApplied, targetKey]
|
|
88
93
|
);
|
|
89
94
|
const loadDraft = useCallback(
|
|
90
|
-
async (replaceLocal
|
|
95
|
+
async (replaceLocal) => {
|
|
91
96
|
if (targetKeyRef.current !== targetKey) return;
|
|
92
97
|
if (!sessionId || !durableDrafts) {
|
|
93
98
|
setDraftLoading(false);
|
|
@@ -96,43 +101,41 @@ function useComposer(sessionId, options = {}) {
|
|
|
96
101
|
const generation = targetGeneration.current;
|
|
97
102
|
const readTicket = ++draftReadGeneration.current;
|
|
98
103
|
const localAtStart = localEditRevision.current;
|
|
104
|
+
const baseAtStart = draftRef.current;
|
|
105
|
+
const extrasAtStart = resolveSendExtras(sendExtrasRef.current);
|
|
106
|
+
const localSignatureAtStart = baseAtStart ? draftSignature(
|
|
107
|
+
composerDraftPayload(
|
|
108
|
+
baseAtStart,
|
|
109
|
+
valueRef.current,
|
|
110
|
+
restoredResourcesRef.current,
|
|
111
|
+
extrasAtStart
|
|
112
|
+
)
|
|
113
|
+
) : null;
|
|
114
|
+
const localWasDirtyAtStart = localSignatureAtStart === null ? localAtStart !== 0 : localSignatureAtStart !== lastSavedSignature.current;
|
|
99
115
|
setDraftLoading(true);
|
|
100
116
|
try {
|
|
101
117
|
const fetched = await client.getComposerDraft(workspaceId, sessionId);
|
|
102
|
-
if (generation !== targetGeneration.current || targetKeyRef.current !== targetKey) {
|
|
118
|
+
if (generation !== targetGeneration.current || targetKeyRef.current !== targetKey || readTicket !== draftReadGeneration.current) {
|
|
103
119
|
return;
|
|
104
120
|
}
|
|
105
|
-
const ownsLatestRead = readTicket === draftReadGeneration.current;
|
|
106
121
|
const currentRevision = draftRef.current?.revision ?? -1;
|
|
107
|
-
if (
|
|
122
|
+
if (fetched.revision >= currentRevision) {
|
|
108
123
|
draftRef.current = fetched;
|
|
109
124
|
setDraft(fetched);
|
|
110
125
|
setDraftConflict(null);
|
|
111
|
-
if (replaceLocal || localAtStart === localEditRevision.current) {
|
|
126
|
+
if (replaceLocal || !localWasDirtyAtStart && localAtStart === localEditRevision.current) {
|
|
127
|
+
valueRef.current = fetched.text;
|
|
128
|
+
restoredResourcesRef.current = fetched.resources;
|
|
112
129
|
lastSavedSignature.current = draftSignature(draftPayload(fetched));
|
|
113
130
|
setValue(fetched.text);
|
|
114
131
|
setRestoredResources(fetched.resources);
|
|
115
132
|
onDraftApplied?.(fetched);
|
|
116
133
|
}
|
|
117
134
|
}
|
|
118
|
-
const authoritativeRevision = draftRef.current?.revision ?? -1;
|
|
119
|
-
if (rejectOnFailure && authoritativeRevision < fetched.revision) {
|
|
120
|
-
throw new TypeError("Composer draft reconciliation did not commit authoritative state");
|
|
121
|
-
}
|
|
122
|
-
if (ownsLatestRead || rejectOnFailure) {
|
|
123
|
-
const recoveredError = draftLoadErrorRef.current;
|
|
124
|
-
draftLoadErrorRef.current = null;
|
|
125
|
-
if (recoveredError) {
|
|
126
|
-
setError((current) => current === recoveredError ? null : current);
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
135
|
} catch (cause) {
|
|
130
|
-
if (generation === targetGeneration.current && targetKeyRef.current === targetKey &&
|
|
131
|
-
|
|
132
|
-
draftLoadErrorRef.current = failure;
|
|
133
|
-
setError(failure);
|
|
136
|
+
if (generation === targetGeneration.current && targetKeyRef.current === targetKey && readTicket === draftReadGeneration.current) {
|
|
137
|
+
setError(asError(cause));
|
|
134
138
|
}
|
|
135
|
-
if (rejectOnFailure) throw cause;
|
|
136
139
|
} finally {
|
|
137
140
|
if (generation === targetGeneration.current && targetKeyRef.current === targetKey && readTicket === draftReadGeneration.current) {
|
|
138
141
|
setDraftLoading(false);
|
|
@@ -161,28 +164,22 @@ function useComposer(sessionId, options = {}) {
|
|
|
161
164
|
{
|
|
162
165
|
enabled: Boolean(sessionId) && durableDrafts,
|
|
163
166
|
...options.events !== void 0 ? { events: options.events } : {}
|
|
164
|
-
}
|
|
165
|
-
async () => await loadDraft(false, true)
|
|
167
|
+
}
|
|
166
168
|
);
|
|
167
169
|
const currentDraftPayload = useCallback(() => {
|
|
168
|
-
if (targetKeyRef.current !== targetKey) return null;
|
|
170
|
+
if (!durableDrafts || targetKeyRef.current !== targetKey) return null;
|
|
169
171
|
const base = draftRef.current;
|
|
170
172
|
if (!base) return null;
|
|
171
173
|
const extras = resolveSendExtras(sendExtrasRef.current);
|
|
172
|
-
return
|
|
173
|
-
|
|
174
|
-
text: value,
|
|
175
|
-
resources: mergeResources(restoredResources, extras.resources ?? []),
|
|
176
|
-
tools: extras.tools ?? base.tools,
|
|
177
|
-
model: extras.model ?? base.model,
|
|
178
|
-
reasoningEffort: extras.reasoningEffort ?? base.reasoningEffort
|
|
179
|
-
};
|
|
180
|
-
}, [restoredResources, targetKey, value]);
|
|
174
|
+
return composerDraftPayload(base, value, restoredResources, extras);
|
|
175
|
+
}, [durableDrafts, restoredResources, targetKey, value]);
|
|
181
176
|
const persistPayload = useCallback(
|
|
182
177
|
async (payload) => {
|
|
183
178
|
const ownedTargetKey = targetKey;
|
|
184
179
|
const ownedGeneration = targetGeneration.current;
|
|
185
|
-
if (!sessionId || targetKeyRef.current !== ownedTargetKey)
|
|
180
|
+
if (!sessionId || !durableDrafts || targetKeyRef.current !== ownedTargetKey) {
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
186
183
|
let success = false;
|
|
187
184
|
const run = async () => {
|
|
188
185
|
if (targetKeyRef.current !== ownedTargetKey || targetGeneration.current !== ownedGeneration) {
|
|
@@ -223,7 +220,7 @@ function useComposer(sessionId, options = {}) {
|
|
|
223
220
|
await saveChain.current;
|
|
224
221
|
return success;
|
|
225
222
|
},
|
|
226
|
-
[client, sessionId, targetKey, workspaceId]
|
|
223
|
+
[client, durableDrafts, sessionId, targetKey, workspaceId]
|
|
227
224
|
);
|
|
228
225
|
useEffect(() => {
|
|
229
226
|
if (!durableDrafts || !sessionId || draftLoading || sending || !draftRef.current || draftConflict)
|
|
@@ -251,7 +248,7 @@ function useComposer(sessionId, options = {}) {
|
|
|
251
248
|
const hasText = rawText.trim().length > 0;
|
|
252
249
|
const extras = resolveSendExtras(sendExtrasRef.current);
|
|
253
250
|
const hasResources = restoredResources.length > 0 || (extras.resources?.length ?? 0) > 0;
|
|
254
|
-
if (!hasText && !hasResources || !sessionId || sending || targetKeyRef.current !== ownedTargetKey) {
|
|
251
|
+
if (!hasText && !hasResources || !sessionId || sending || sendBlockedRef.current?.() === true || targetKeyRef.current !== ownedTargetKey) {
|
|
255
252
|
return false;
|
|
256
253
|
}
|
|
257
254
|
pendingClientEventId.current ??= generateClientEventId();
|
|
@@ -265,9 +262,11 @@ function useComposer(sessionId, options = {}) {
|
|
|
265
262
|
if (targetKeyRef.current !== ownedTargetKey || targetGeneration.current !== ownedGeneration) {
|
|
266
263
|
return false;
|
|
267
264
|
}
|
|
268
|
-
const
|
|
265
|
+
const acknowledgedDraft = draftRef.current;
|
|
266
|
+
const sendExtras = acknowledgedDraft?.toolsProvided === true && !Object.prototype.hasOwnProperty.call(extras, "tools") ? { ...extras, tools: acknowledgedDraft.tools } : extras;
|
|
267
|
+
const input = composeSendInput(sendText, pendingClientEventId.current, sendExtras, {
|
|
269
268
|
...options.effectiveControl?.controlEtag ? { controlEtag: options.effectiveControl.controlEtag } : {},
|
|
270
|
-
...draftRef.current ? { expectedDraftRevision: draftRef.current.revision } : {},
|
|
269
|
+
...durableDrafts && draftRef.current ? { expectedDraftRevision: draftRef.current.revision } : {},
|
|
271
270
|
resources: mergeResources(restoredResources, extras.resources ?? [])
|
|
272
271
|
});
|
|
273
272
|
if (delivery === "steer") {
|
|
@@ -291,14 +290,18 @@ function useComposer(sessionId, options = {}) {
|
|
|
291
290
|
updatedAt: null
|
|
292
291
|
};
|
|
293
292
|
draftRef.current = cleared;
|
|
293
|
+
restoredResourcesRef.current = [];
|
|
294
294
|
setDraft(cleared);
|
|
295
295
|
setRestoredResources([]);
|
|
296
296
|
lastSavedSignature.current = draftSignature(draftPayload(cleared));
|
|
297
297
|
}
|
|
298
298
|
if (explicit === void 0) {
|
|
299
|
-
|
|
299
|
+
if (valueRef.current === draftAtSend) {
|
|
300
|
+
valueRef.current = "";
|
|
301
|
+
setValue("");
|
|
302
|
+
}
|
|
300
303
|
}
|
|
301
|
-
onSent?.(sendText);
|
|
304
|
+
onSent?.(sendText, input);
|
|
302
305
|
return true;
|
|
303
306
|
} catch (cause) {
|
|
304
307
|
if (targetKeyRef.current === ownedTargetKey && targetGeneration.current === ownedGeneration) {
|
|
@@ -314,6 +317,7 @@ function useComposer(sessionId, options = {}) {
|
|
|
314
317
|
[
|
|
315
318
|
client,
|
|
316
319
|
currentDraftPayload,
|
|
320
|
+
durableDrafts,
|
|
317
321
|
onSent,
|
|
318
322
|
options.effectiveControl?.controlEtag,
|
|
319
323
|
persistPayload,
|
|
@@ -327,7 +331,7 @@ function useComposer(sessionId, options = {}) {
|
|
|
327
331
|
);
|
|
328
332
|
const send = useCallback(async (text) => await dispatch("send", text), [dispatch]);
|
|
329
333
|
const steer = useCallback(async (text) => await dispatch("steer", text), [dispatch]);
|
|
330
|
-
const hasReadyResources = restoredResources.length > 0 || (
|
|
334
|
+
const hasReadyResources = restoredResources.length > 0 || (resolveSendExtras(sendExtrasRef.current).resources?.length ?? 0) > 0;
|
|
331
335
|
const pause = useCallback(
|
|
332
336
|
async (reason) => {
|
|
333
337
|
const ownedTargetKey = targetKey;
|
|
@@ -387,12 +391,14 @@ function useComposer(sessionId, options = {}) {
|
|
|
387
391
|
setError(null);
|
|
388
392
|
try {
|
|
389
393
|
if (option.scope === "workspace") {
|
|
390
|
-
if (!client.setWorkspaceInferenceState) {
|
|
391
|
-
throw new Error("Workspace-level resume is not available through this client");
|
|
392
|
-
}
|
|
393
394
|
const workspaceBlocker = options.effectiveControl?.blockers.find(
|
|
394
395
|
(blocker) => blocker.kind === "workspace"
|
|
395
396
|
);
|
|
397
|
+
if (!client.setWorkspaceInferenceState) {
|
|
398
|
+
throw new Error(
|
|
399
|
+
"@opengeni/react: workspace-scoped resume requires setWorkspaceInferenceState."
|
|
400
|
+
);
|
|
401
|
+
}
|
|
396
402
|
await client.setWorkspaceInferenceState(workspaceId, {
|
|
397
403
|
action: "resume",
|
|
398
404
|
clientEventId: generateClientEventId(),
|
|
@@ -428,6 +434,7 @@ function useComposer(sessionId, options = {}) {
|
|
|
428
434
|
if (targetKeyRef.current !== targetKey) return;
|
|
429
435
|
pendingClientEventId.current = null;
|
|
430
436
|
localEditRevision.current += 1;
|
|
437
|
+
valueRef.current = next;
|
|
431
438
|
setValue(next);
|
|
432
439
|
},
|
|
433
440
|
[targetKey]
|
|
@@ -436,10 +443,19 @@ function useComposer(sessionId, options = {}) {
|
|
|
436
443
|
(index) => {
|
|
437
444
|
if (targetKeyRef.current !== targetKey) return;
|
|
438
445
|
localEditRevision.current += 1;
|
|
439
|
-
|
|
446
|
+
const next = restoredResourcesRef.current.filter((_, candidate) => candidate !== index);
|
|
447
|
+
restoredResourcesRef.current = next;
|
|
448
|
+
setRestoredResources(next);
|
|
440
449
|
},
|
|
441
450
|
[targetKey]
|
|
442
451
|
);
|
|
452
|
+
const hasDraftContent = useCallback(() => {
|
|
453
|
+
const current = draftRef.current;
|
|
454
|
+
const extras = resolveSendExtras(sendExtrasRef.current);
|
|
455
|
+
const toolsProvidedByHost = Object.prototype.hasOwnProperty.call(extras, "tools");
|
|
456
|
+
const tools = toolsProvidedByHost ? extras.tools ?? [] : current?.tools ?? [];
|
|
457
|
+
return valueRef.current.length > 0 || restoredResourcesRef.current.length > 0 || (extras.resources?.length ?? 0) > 0 || tools.length > 0 || current?.sourceTurnId !== null && current?.sourceTurnId !== void 0;
|
|
458
|
+
}, []);
|
|
443
459
|
const resolveDraftConflict = useCallback(
|
|
444
460
|
async (choice) => {
|
|
445
461
|
const ownedTargetKey = targetKey;
|
|
@@ -480,10 +496,11 @@ function useComposer(sessionId, options = {}) {
|
|
|
480
496
|
return {
|
|
481
497
|
value: identityMatches ? value : "",
|
|
482
498
|
setValue: updateValue,
|
|
499
|
+
hasDraftContent,
|
|
483
500
|
send,
|
|
484
501
|
steer,
|
|
485
502
|
sending: identityMatches ? sending : false,
|
|
486
|
-
canSend: identityMatches && Boolean(sessionId) && !sending && (value.trim().length > 0 || hasReadyResources),
|
|
503
|
+
canSend: identityMatches && Boolean(sessionId) && !sending && sendBlockedRef.current?.() !== true && (value.trim().length > 0 || hasReadyResources),
|
|
487
504
|
pause,
|
|
488
505
|
pausing: identityMatches ? pausing : false,
|
|
489
506
|
resume,
|
|
@@ -535,10 +552,23 @@ function draftPayload(draft) {
|
|
|
535
552
|
text: draft.text,
|
|
536
553
|
resources: draft.resources,
|
|
537
554
|
tools: draft.tools,
|
|
555
|
+
toolsProvided: draft.toolsProvided,
|
|
538
556
|
model: draft.model,
|
|
539
557
|
reasoningEffort: draft.reasoningEffort
|
|
540
558
|
};
|
|
541
559
|
}
|
|
560
|
+
function composerDraftPayload(base, text, restoredResources, extras) {
|
|
561
|
+
const toolsProvidedByHost = Object.prototype.hasOwnProperty.call(extras, "tools");
|
|
562
|
+
return {
|
|
563
|
+
expectedRevision: base.revision,
|
|
564
|
+
text,
|
|
565
|
+
resources: mergeResources(restoredResources, extras.resources ?? []),
|
|
566
|
+
tools: toolsProvidedByHost ? extras.tools ?? [] : base.tools,
|
|
567
|
+
toolsProvided: toolsProvidedByHost ? true : base.toolsProvided,
|
|
568
|
+
model: extras.model ?? base.model,
|
|
569
|
+
reasoningEffort: extras.reasoningEffort ?? base.reasoningEffort
|
|
570
|
+
};
|
|
571
|
+
}
|
|
542
572
|
function draftSignature(payload) {
|
|
543
573
|
const { expectedRevision: _revision, ...content } = payload;
|
|
544
574
|
return JSON.stringify(content);
|
|
@@ -560,4 +590,4 @@ export {
|
|
|
560
590
|
shouldSubmitOnKey,
|
|
561
591
|
shouldSteerOnKey
|
|
562
592
|
};
|
|
563
|
-
//# sourceMappingURL=chunk-
|
|
593
|
+
//# sourceMappingURL=chunk-AVPU5PMC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-composer.ts"],"sourcesContent":["import type {\n ComposerDraft,\n EffectiveControlResumeOption,\n EffectiveSessionControl,\n ResourceRef,\n SaveComposerDraftRequest,\n SendMessageInput,\n SessionEvent,\n} from \"@opengeni/sdk\";\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport { useEmbeddedSession, type EmbeddedSessionClientOverride } from \"../session-context\";\nimport { useSessionEventTrigger, type SessionEventFeedOptions } from \"./internal\";\n\nexport type ComposerSendExtras = Omit<SendMessageInput, \"text\" | \"clientEventId\">;\n\nexport type UseComposerOptions = EmbeddedSessionClientOverride &\n SessionEventFeedOptions & {\n /** Called with the exact accepted wire input after a successful send. */\n onSent?: ((text: string, input: SendMessageInput) => void) | undefined;\n /**\n * Extra message fields (resources, tools, model, reasoningEffort) merged\n * into every send. A function is evaluated at send time so it can read the\n * surrounding UI state (attachment pickers, model selectors, ...).\n */\n sendExtras?: ComposerSendExtras | (() => ComposerSendExtras) | undefined;\n /**\n * Fail-closed delivery guard evaluated at send time. Attachment hosts use\n * this to preserve unresolved upload cards until the operator waits,\n * retries, or removes them; direct hook callers cannot bypass the UI gate.\n */\n sendBlocked?: (() => boolean) | undefined;\n /** Latest server-derived workstream control; bound into Send/Steer OCC. */\n effectiveControl?: EffectiveSessionControl | null | undefined;\n /** Apply durable model/tool/reasoning settings in the host's controlled UI. */\n onDraftApplied?: ((draft: ComposerDraft) => void) | undefined;\n /** Disable remote composer-draft reads and writes for embedded hosts. */\n draftPersistence?: \"durable\" | \"disabled\" | undefined;\n };\n\nexport type ComposerState = {\n value: string;\n setValue: (value: string) => void;\n /** Read the current draft synchronously before a destructive replacement. */\n hasDraftContent: () => boolean;\n /** Append the draft behind prompts already visible in the queue. */\n send: (text?: string) => Promise<boolean>;\n /** Supersede current direction with the draft. */\n steer: (text?: string) => Promise<boolean>;\n sending: boolean;\n canSend: boolean;\n /** Pause the session without deleting its prompt queue. */\n pause: (reason?: string) => Promise<void>;\n pausing: boolean;\n resume: (reason?: string) => Promise<void>;\n resumeScope: (option: EffectiveControlResumeOption) => Promise<void>;\n resuming: boolean;\n draft: ComposerDraft | null;\n draftRevision: number;\n draftLoading: boolean;\n draftSaving: boolean;\n draftConflict: Error | null;\n /** Whether this controller owns a durable server-side draft. */\n draftPersistence?: \"durable\" | \"disabled\" | undefined;\n /** Apply an atomic queue Edit checkout without a second read. */\n applyDraft: (draft: ComposerDraft) => void;\n reloadDraft: () => Promise<void>;\n resolveDraftConflict: (choice: \"keep_mine\" | \"use_remote\") => Promise<void>;\n restoredResources: ResourceRef[];\n removeRestoredResource: (index: number) => void;\n error: Error | null;\n clearError: () => void;\n};\n\n/**\n * Draft + send + Pause/Resume state for the chat composer — the only\n * human-to-agent input surface. The draft survives a failed send (nothing is\n * more hostile than losing a typed message); each send carries a generated\n * `clientEventId` so retries stay idempotent server-side.\n */\nexport function useComposer(\n sessionId: string | null | undefined,\n options: UseComposerOptions = {},\n): ComposerState {\n const { client, workspaceId, registerSessionReconciler } = useEmbeddedSession(options);\n const durableDrafts = options.draftPersistence !== \"disabled\";\n const targetKey = `${workspaceId}\\u0000${sessionId ?? \"\"}\\u0000${durableDrafts ? \"durable\" : \"disabled\"}`;\n const [value, setValue] = useState(\"\");\n // Keep rendered state behind the committed target identity for one frame:\n // a parent may switch sessionId without remounting this public hook.\n const [stateTargetKey, setStateTargetKey] = useState(targetKey);\n const [sending, setSending] = useState(false);\n const [pausing, setPausing] = useState(false);\n const [resuming, setResuming] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [draft, setDraft] = useState<ComposerDraft | null>(null);\n const [draftLoading, setDraftLoading] = useState(Boolean(sessionId) && durableDrafts);\n const [draftSaving, setDraftSaving] = useState(false);\n const [draftConflict, setDraftConflict] = useState<Error | null>(null);\n const [restoredResources, setRestoredResources] = useState<ResourceRef[]>([]);\n const pendingClientEventId = useRef<string | null>(null);\n const valueRef = useRef(\"\");\n const draftRef = useRef<ComposerDraft | null>(null);\n const restoredResourcesRef = useRef<ResourceRef[]>([]);\n const localEditRevision = useRef(0);\n const targetGeneration = useRef(0);\n const draftReadGeneration = useRef(0);\n const lastSavedSignature = useRef<string | null>(null);\n const saveChain = useRef<Promise<void>>(Promise.resolve());\n const onSent = options.onSent;\n const onDraftApplied = options.onDraftApplied;\n // Read through a ref so a new extras closure (created every render by\n // callers passing inline functions) does not invalidate `send`.\n const sendExtrasRef = useRef(options.sendExtras);\n sendExtrasRef.current = options.sendExtras;\n const sendBlockedRef = useRef(options.sendBlocked);\n sendBlockedRef.current = options.sendBlocked;\n const liveExtrasVersion = JSON.stringify(resolveSendExtras(options.sendExtras));\n\n // A composer is bound to one session: switching targets must not leak the\n // previous session's draft, error, or retry idempotency key.\n const targetKeyRef = useRef(targetKey);\n useLayoutEffect(() => {\n if (targetKeyRef.current === targetKey) return;\n targetKeyRef.current = targetKey;\n targetGeneration.current += 1;\n draftReadGeneration.current += 1;\n pendingClientEventId.current = null;\n localEditRevision.current = 0;\n valueRef.current = \"\";\n draftRef.current = null;\n restoredResourcesRef.current = [];\n lastSavedSignature.current = null;\n // Old saves may still be awaiting the network. Their generation fence\n // prevents settlement, and a fresh chain avoids blocking this target.\n saveChain.current = Promise.resolve();\n setStateTargetKey(targetKey);\n setValue(\"\");\n setSending(false);\n setPausing(false);\n setResuming(false);\n setError(null);\n setDraft(null);\n setDraftLoading(Boolean(sessionId) && durableDrafts);\n setDraftSaving(false);\n setDraftConflict(null);\n setRestoredResources([]);\n }, [durableDrafts, sessionId, targetKey]);\n\n const applyDraft = useCallback(\n (next: ComposerDraft): void => {\n if (targetKeyRef.current !== targetKey) return;\n if (!durableDrafts) {\n pendingClientEventId.current = null;\n localEditRevision.current += 1;\n valueRef.current = next.text;\n restoredResourcesRef.current = next.resources;\n draftRef.current = null;\n lastSavedSignature.current = null;\n setDraft(null);\n setValue(next.text);\n setRestoredResources(next.resources);\n setDraftConflict(null);\n return;\n }\n valueRef.current = next.text;\n draftRef.current = next;\n restoredResourcesRef.current = next.resources;\n lastSavedSignature.current = draftSignature(draftPayload(next));\n localEditRevision.current += 1;\n pendingClientEventId.current = null;\n setDraft(next);\n setValue(next.text);\n setRestoredResources(next.resources);\n setDraftConflict(null);\n onDraftApplied?.(next);\n },\n [durableDrafts, onDraftApplied, targetKey],\n );\n\n const loadDraft = useCallback(\n async (replaceLocal: boolean): Promise<void> => {\n if (targetKeyRef.current !== targetKey) return;\n if (!sessionId || !durableDrafts) {\n setDraftLoading(false);\n return;\n }\n const generation = targetGeneration.current;\n const readTicket = ++draftReadGeneration.current;\n const localAtStart = localEditRevision.current;\n const baseAtStart = draftRef.current;\n const extrasAtStart = resolveSendExtras(sendExtrasRef.current);\n const localSignatureAtStart = baseAtStart\n ? draftSignature(\n composerDraftPayload(\n baseAtStart,\n valueRef.current,\n restoredResourcesRef.current,\n extrasAtStart,\n ),\n )\n : null;\n const localWasDirtyAtStart =\n localSignatureAtStart === null\n ? localAtStart !== 0\n : localSignatureAtStart !== lastSavedSignature.current;\n setDraftLoading(true);\n try {\n const fetched = await client.getComposerDraft(workspaceId, sessionId);\n if (\n generation !== targetGeneration.current ||\n targetKeyRef.current !== targetKey ||\n readTicket !== draftReadGeneration.current\n ) {\n return;\n }\n const currentRevision = draftRef.current?.revision ?? -1;\n if (fetched.revision >= currentRevision) {\n draftRef.current = fetched;\n setDraft(fetched);\n setDraftConflict(null);\n if (\n replaceLocal ||\n (!localWasDirtyAtStart && localAtStart === localEditRevision.current)\n ) {\n valueRef.current = fetched.text;\n restoredResourcesRef.current = fetched.resources;\n lastSavedSignature.current = draftSignature(draftPayload(fetched));\n setValue(fetched.text);\n setRestoredResources(fetched.resources);\n onDraftApplied?.(fetched);\n }\n }\n } catch (cause) {\n if (\n generation === targetGeneration.current &&\n targetKeyRef.current === targetKey &&\n readTicket === draftReadGeneration.current\n ) {\n setError(asError(cause));\n }\n } finally {\n if (\n generation === targetGeneration.current &&\n targetKeyRef.current === targetKey &&\n readTicket === draftReadGeneration.current\n ) {\n setDraftLoading(false);\n }\n }\n },\n [client, durableDrafts, onDraftApplied, sessionId, targetKey, workspaceId],\n );\n\n useEffect(() => {\n if (!sessionId || !durableDrafts) {\n setDraftLoading(false);\n return;\n }\n void loadDraft(false);\n }, [durableDrafts, loadDraft, sessionId]);\n useEffect(() => {\n if (!sessionId || !durableDrafts) return;\n return registerSessionReconciler(sessionId, \"composer\", async () => await loadDraft(false));\n }, [durableDrafts, loadDraft, registerSessionReconciler, sessionId]);\n useSessionEventTrigger(\n client,\n workspaceId,\n sessionId,\n isComposerDraftEvent,\n () => void loadDraft(false),\n {\n enabled: Boolean(sessionId) && durableDrafts,\n ...(options.events !== undefined ? { events: options.events } : {}),\n },\n );\n\n const currentDraftPayload = useCallback((): SaveComposerDraftRequest | null => {\n if (!durableDrafts || targetKeyRef.current !== targetKey) return null;\n const base = draftRef.current;\n if (!base) return null;\n const extras = resolveSendExtras(sendExtrasRef.current);\n return composerDraftPayload(base, value, restoredResources, extras);\n }, [durableDrafts, restoredResources, targetKey, value]);\n\n const persistPayload = useCallback(\n async (payload: SaveComposerDraftRequest): Promise<boolean> => {\n const ownedTargetKey = targetKey;\n const ownedGeneration = targetGeneration.current;\n if (!sessionId || !durableDrafts || targetKeyRef.current !== ownedTargetKey) {\n return false;\n }\n let success = false;\n const run = async () => {\n if (\n targetKeyRef.current !== ownedTargetKey ||\n targetGeneration.current !== ownedGeneration\n ) {\n return;\n }\n const current = draftRef.current;\n if (!current) return;\n const request = { ...payload, expectedRevision: current.revision };\n const signature = draftSignature(request);\n if (signature === lastSavedSignature.current) {\n success = true;\n return;\n }\n setDraftSaving(true);\n try {\n const saved = await client.saveComposerDraft(workspaceId, sessionId, request);\n if (\n targetKeyRef.current !== ownedTargetKey ||\n targetGeneration.current !== ownedGeneration\n ) {\n return;\n }\n draftRef.current = saved;\n setDraft(saved);\n lastSavedSignature.current = signature;\n setDraftConflict(null);\n success = true;\n } catch (cause) {\n if (\n targetKeyRef.current === ownedTargetKey &&\n targetGeneration.current === ownedGeneration\n ) {\n const problem = asError(cause);\n setDraftConflict(problem);\n setError(problem);\n }\n } finally {\n if (\n targetKeyRef.current === ownedTargetKey &&\n targetGeneration.current === ownedGeneration\n ) {\n setDraftSaving(false);\n }\n }\n };\n saveChain.current = saveChain.current.then(run, run);\n await saveChain.current;\n return success;\n },\n [client, durableDrafts, sessionId, targetKey, workspaceId],\n );\n\n // Private durable autosave. A newer local edit is never replaced by an older\n // response; saves serialize and each reads the latest acknowledged revision.\n useEffect(() => {\n if (\n !durableDrafts ||\n !sessionId ||\n draftLoading ||\n sending ||\n !draftRef.current ||\n draftConflict\n )\n return;\n const payload = currentDraftPayload();\n if (!payload || draftSignature(payload) === lastSavedSignature.current) return;\n const timer = window.setTimeout(() => void persistPayload(payload), 500);\n return () => window.clearTimeout(timer);\n }, [\n currentDraftPayload,\n durableDrafts,\n draftConflict,\n draftLoading,\n liveExtrasVersion,\n persistPayload,\n sending,\n sessionId,\n ]);\n\n const dispatch = useCallback(\n async (delivery: \"send\" | \"steer\", explicit?: string): Promise<boolean> => {\n const ownedTargetKey = targetKey;\n const ownedGeneration = targetGeneration.current;\n const draftAtSend = value;\n const rawText = explicit ?? draftAtSend;\n const hasText = rawText.trim().length > 0;\n // Resolve the extras once: a file-only message (empty text + ≥1 ready\n // resource) is legitimate, so we must not bail on empty text alone.\n const extras = resolveSendExtras(sendExtrasRef.current);\n const hasResources = restoredResources.length > 0 || (extras.resources?.length ?? 0) > 0;\n if (\n (!hasText && !hasResources) ||\n !sessionId ||\n sending ||\n sendBlockedRef.current?.() === true ||\n targetKeyRef.current !== ownedTargetKey\n ) {\n return false;\n }\n // Reuse the clientEventId across retries of the same draft so a\n // timeout + resend cannot double-deliver the message.\n pendingClientEventId.current ??= generateClientEventId();\n setSending(true);\n setError(null);\n try {\n // Trimming is only an emptiness check. A non-blank prompt is persisted\n // and submitted byte-for-byte, while file-only sends use the same\n // placeholder for both operations so the server content fence cannot\n // reject its own client.\n const sendText = hasText ? rawText : FILE_ONLY_MESSAGE_TEXT;\n const currentPayload = currentDraftPayload();\n const payload = currentPayload ? { ...currentPayload, text: sendText } : null;\n if (payload && !(await persistPayload(payload))) return false;\n if (\n targetKeyRef.current !== ownedTargetKey ||\n targetGeneration.current !== ownedGeneration\n ) {\n return false;\n }\n // The wire contract requires non-empty text (z.string().min(1)) and the\n // worker rejects whitespace-only text; a file-only message therefore\n // carries a minimal default so the attachments still get delivered.\n const acknowledgedDraft = draftRef.current;\n const sendExtras =\n acknowledgedDraft?.toolsProvided === true &&\n !Object.prototype.hasOwnProperty.call(extras, \"tools\")\n ? { ...extras, tools: acknowledgedDraft.tools }\n : extras;\n const input = composeSendInput(sendText, pendingClientEventId.current, sendExtras, {\n ...(options.effectiveControl?.controlEtag\n ? { controlEtag: options.effectiveControl.controlEtag }\n : {}),\n ...(durableDrafts && draftRef.current\n ? { expectedDraftRevision: draftRef.current.revision }\n : {}),\n resources: mergeResources(restoredResources, extras.resources ?? []),\n });\n if (delivery === \"steer\") {\n await client.steerMessage(workspaceId, sessionId, input);\n } else {\n await client.sendMessage(workspaceId, sessionId, input);\n }\n if (\n targetKeyRef.current !== ownedTargetKey ||\n targetGeneration.current !== ownedGeneration\n ) {\n return false;\n }\n pendingClientEventId.current = null;\n const previousDraft = draftRef.current;\n if (previousDraft) {\n const cleared = {\n ...previousDraft,\n revision: 0,\n text: \"\",\n resources: [],\n sourceTurnId: null,\n sourceTurnVersion: null,\n updatedAt: null,\n };\n draftRef.current = cleared;\n restoredResourcesRef.current = [];\n setDraft(cleared);\n setRestoredResources([]);\n lastSavedSignature.current = draftSignature(draftPayload(cleared));\n }\n if (explicit === undefined) {\n // Clear only the draft that was sent: edits made while the request\n // was in flight were never delivered and must survive.\n if (valueRef.current === draftAtSend) {\n valueRef.current = \"\";\n setValue(\"\");\n }\n }\n onSent?.(sendText, input);\n return true;\n } catch (cause) {\n if (\n targetKeyRef.current === ownedTargetKey &&\n targetGeneration.current === ownedGeneration\n ) {\n setError(cause instanceof Error ? cause : new Error(String(cause)));\n }\n return false;\n } finally {\n if (\n targetKeyRef.current === ownedTargetKey &&\n targetGeneration.current === ownedGeneration\n ) {\n setSending(false);\n }\n }\n },\n [\n client,\n currentDraftPayload,\n durableDrafts,\n onSent,\n options.effectiveControl?.controlEtag,\n persistPayload,\n restoredResources,\n sending,\n sessionId,\n targetKey,\n value,\n workspaceId,\n ],\n );\n\n const send = useCallback(async (text?: string) => await dispatch(\"send\", text), [dispatch]);\n const steer = useCallback(async (text?: string) => await dispatch(\"steer\", text), [dispatch]);\n\n // A send is possible with non-empty text OR with ≥1 attached resource (a\n // file-only message). Resources ride in `sendExtras`, so we resolve them here\n // — keeping useComposer attachment-agnostic while still lighting up the send\n // affordance the moment a file is ready. Attachment hosts bind `sendBlocked`\n // to unresolved uploads so direct send()/steer() calls fail closed too.\n const hasReadyResources =\n restoredResources.length > 0 ||\n (resolveSendExtras(sendExtrasRef.current).resources?.length ?? 0) > 0;\n\n const pause = useCallback(\n async (reason?: string): Promise<void> => {\n const ownedTargetKey = targetKey;\n const ownedGeneration = targetGeneration.current;\n if (!sessionId || pausing || targetKeyRef.current !== ownedTargetKey) {\n return;\n }\n setPausing(true);\n setError(null);\n try {\n await client.pauseSession(workspaceId, sessionId, {\n ...(reason !== undefined ? { reason } : {}),\n ...(options.effectiveControl?.controlEtag\n ? { expectedControlEtag: options.effectiveControl.controlEtag }\n : {}),\n });\n } catch (cause) {\n if (\n targetKeyRef.current === ownedTargetKey &&\n targetGeneration.current === ownedGeneration\n ) {\n setError(cause instanceof Error ? cause : new Error(String(cause)));\n }\n } finally {\n if (\n targetKeyRef.current === ownedTargetKey &&\n targetGeneration.current === ownedGeneration\n ) {\n setPausing(false);\n }\n }\n },\n [client, workspaceId, sessionId, pausing, options.effectiveControl?.controlEtag, targetKey],\n );\n\n const resume = useCallback(\n async (reason?: string): Promise<void> => {\n const ownedTargetKey = targetKey;\n const ownedGeneration = targetGeneration.current;\n if (!sessionId || resuming || targetKeyRef.current !== ownedTargetKey) return;\n setResuming(true);\n setError(null);\n try {\n await client.resumeSession(workspaceId, sessionId, {\n ...(reason !== undefined ? { reason } : {}),\n ...(options.effectiveControl?.controlEtag\n ? { expectedControlEtag: options.effectiveControl.controlEtag }\n : {}),\n });\n } catch (cause) {\n if (\n targetKeyRef.current === ownedTargetKey &&\n targetGeneration.current === ownedGeneration\n ) {\n setError(cause instanceof Error ? cause : new Error(String(cause)));\n }\n } finally {\n if (\n targetKeyRef.current === ownedTargetKey &&\n targetGeneration.current === ownedGeneration\n ) {\n setResuming(false);\n }\n }\n },\n [client, workspaceId, sessionId, resuming, options.effectiveControl?.controlEtag, targetKey],\n );\n\n const resumeScope = useCallback(\n async (option: EffectiveControlResumeOption): Promise<void> => {\n const ownedTargetKey = targetKey;\n const ownedGeneration = targetGeneration.current;\n if (!sessionId || resuming || targetKeyRef.current !== ownedTargetKey) return;\n setResuming(true);\n setError(null);\n try {\n if (option.scope === \"workspace\") {\n const workspaceBlocker = options.effectiveControl?.blockers.find(\n (blocker) => blocker.kind === \"workspace\",\n );\n if (!client.setWorkspaceInferenceState) {\n throw new Error(\n \"@opengeni/react: workspace-scoped resume requires setWorkspaceInferenceState.\",\n );\n }\n await client.setWorkspaceInferenceState(workspaceId, {\n action: \"resume\",\n clientEventId: generateClientEventId(),\n ...(workspaceBlocker ? { expectedRevision: workspaceBlocker.revision } : {}),\n });\n } else if (option.scope === \"session\" && option.targetId) {\n const target = await client.getQueue(workspaceId, option.targetId);\n if (\n targetKeyRef.current !== ownedTargetKey ||\n targetGeneration.current !== ownedGeneration\n ) {\n return;\n }\n await client.resumeSession(workspaceId, option.targetId, {\n expectedControlEtag: target.effectiveControl.controlEtag,\n });\n } else {\n await client.resumeSession(workspaceId, sessionId, {\n ...(options.effectiveControl?.controlEtag\n ? { expectedControlEtag: options.effectiveControl.controlEtag }\n : {}),\n });\n }\n } catch (cause) {\n if (\n targetKeyRef.current === ownedTargetKey &&\n targetGeneration.current === ownedGeneration\n ) {\n setError(asError(cause));\n }\n } finally {\n if (\n targetKeyRef.current === ownedTargetKey &&\n targetGeneration.current === ownedGeneration\n ) {\n setResuming(false);\n }\n }\n },\n [client, options.effectiveControl, resuming, sessionId, targetKey, workspaceId],\n );\n\n const updateValue = useCallback(\n (next: string) => {\n if (targetKeyRef.current !== targetKey) return;\n pendingClientEventId.current = null;\n localEditRevision.current += 1;\n valueRef.current = next;\n setValue(next);\n },\n [targetKey],\n );\n\n const removeRestoredResource = useCallback(\n (index: number) => {\n if (targetKeyRef.current !== targetKey) return;\n localEditRevision.current += 1;\n const next = restoredResourcesRef.current.filter((_, candidate) => candidate !== index);\n restoredResourcesRef.current = next;\n setRestoredResources(next);\n },\n [targetKey],\n );\n\n const hasDraftContent = useCallback((): boolean => {\n const current = draftRef.current;\n const extras = resolveSendExtras(sendExtrasRef.current);\n const toolsProvidedByHost = Object.prototype.hasOwnProperty.call(extras, \"tools\");\n const tools = toolsProvidedByHost ? (extras.tools ?? []) : (current?.tools ?? []);\n return (\n valueRef.current.length > 0 ||\n restoredResourcesRef.current.length > 0 ||\n (extras.resources?.length ?? 0) > 0 ||\n tools.length > 0 ||\n (current?.sourceTurnId !== null && current?.sourceTurnId !== undefined)\n );\n }, []);\n\n const resolveDraftConflict = useCallback(\n async (choice: \"keep_mine\" | \"use_remote\"): Promise<void> => {\n const ownedTargetKey = targetKey;\n const ownedGeneration = targetGeneration.current;\n if (!sessionId || !durableDrafts || targetKeyRef.current !== ownedTargetKey) return;\n const remote = await client.getComposerDraft(workspaceId, sessionId);\n if (targetKeyRef.current !== ownedTargetKey || targetGeneration.current !== ownedGeneration) {\n return;\n }\n if (choice === \"use_remote\") {\n applyDraft(remote);\n return;\n }\n draftRef.current = remote;\n setDraft(remote);\n setDraftConflict(null);\n const payload = currentDraftPayload();\n if (payload) await persistPayload({ ...payload, expectedRevision: remote.revision });\n },\n [\n applyDraft,\n client,\n currentDraftPayload,\n durableDrafts,\n persistPayload,\n sessionId,\n targetKey,\n workspaceId,\n ],\n );\n\n const identityMatches = stateTargetKey === targetKey;\n const reloadDraft = useCallback(async () => await loadDraft(true), [loadDraft]);\n const clearError = useCallback(() => {\n if (targetKeyRef.current !== targetKey) return;\n setError(null);\n setDraftConflict(null);\n }, [targetKey]);\n\n return {\n value: identityMatches ? value : \"\",\n setValue: updateValue,\n hasDraftContent,\n send,\n steer,\n sending: identityMatches ? sending : false,\n canSend:\n identityMatches &&\n Boolean(sessionId) &&\n !sending &&\n sendBlockedRef.current?.() !== true &&\n (value.trim().length > 0 || hasReadyResources),\n pause,\n pausing: identityMatches ? pausing : false,\n resume,\n resumeScope,\n resuming: identityMatches ? resuming : false,\n draft: identityMatches ? draft : null,\n draftRevision: identityMatches ? (draft?.revision ?? 0) : 0,\n draftLoading: identityMatches ? draftLoading : Boolean(sessionId) && durableDrafts,\n draftSaving: identityMatches ? draftSaving : false,\n draftConflict: identityMatches ? draftConflict : null,\n draftPersistence: durableDrafts ? \"durable\" : \"disabled\",\n applyDraft,\n reloadDraft,\n resolveDraftConflict,\n restoredResources: identityMatches ? restoredResources : [],\n removeRestoredResource,\n error: identityMatches ? error : null,\n clearError,\n };\n}\n\n/** Events that can atomically replace or clear this subject's durable draft. */\nexport function isComposerDraftEvent(event: Pick<SessionEvent, \"type\">): boolean {\n return event.type === \"user.message\" || event.type === \"session.queue.changed\";\n}\n\n/**\n * Default text for a file-only message (attachment(s) present, no typed draft).\n * Kept non-empty so the wire contract (`text: z.string().min(1)`) and the\n * worker's non-whitespace guard accept it; the attached files still ride in\n * `resources`. Exported for tests.\n */\nexport const FILE_ONLY_MESSAGE_TEXT = \"(see attached files)\";\n\n/** Resolve possibly-deferred extras to a concrete bag (function evaluated now). */\nexport function resolveSendExtras(\n extras: ComposerSendExtras | (() => ComposerSendExtras) | undefined,\n): ComposerSendExtras {\n return (typeof extras === \"function\" ? extras() : extras) ?? {};\n}\n\n/**\n * Merge the draft text + idempotency key with caller-provided extras. The\n * text and clientEventId always win over extras. Exported for tests.\n */\nexport function composeSendInput(\n text: string,\n clientEventId: string,\n extras: ComposerSendExtras | (() => ComposerSendExtras) | undefined,\n bound: Partial<SendMessageInput> = {},\n): SendMessageInput {\n return { ...resolveSendExtras(extras), ...bound, text, clientEventId };\n}\n\n/** Submit on plain Enter; Shift+Enter inserts a newline. Exported for tests. */\nexport function shouldSubmitOnKey(event: {\n key: string;\n shiftKey: boolean;\n metaKey?: boolean;\n ctrlKey?: boolean;\n nativeEvent?: { isComposing?: boolean };\n}): boolean {\n if (event.key !== \"Enter\" || event.shiftKey) {\n return false;\n }\n return event.nativeEvent?.isComposing !== true;\n}\n\n/** Cmd/Ctrl+Enter steers; ordinary Enter appends to the queue. */\nexport function shouldSteerOnKey(event: { metaKey?: boolean; ctrlKey?: boolean }): boolean {\n return event.metaKey === true || event.ctrlKey === true;\n}\n\nfunction generateClientEventId(): string {\n return globalThis.crypto.randomUUID();\n}\n\nfunction asError(cause: unknown): Error {\n return cause instanceof Error ? cause : new Error(String(cause));\n}\n\nfunction draftPayload(draft: ComposerDraft): SaveComposerDraftRequest {\n return {\n expectedRevision: draft.revision,\n text: draft.text,\n resources: draft.resources,\n tools: draft.tools,\n toolsProvided: draft.toolsProvided,\n model: draft.model,\n reasoningEffort: draft.reasoningEffort,\n };\n}\n\nfunction composerDraftPayload(\n base: ComposerDraft,\n text: string,\n restoredResources: ResourceRef[],\n extras: ComposerSendExtras,\n): SaveComposerDraftRequest {\n const toolsProvidedByHost = Object.prototype.hasOwnProperty.call(extras, \"tools\");\n return {\n expectedRevision: base.revision,\n text,\n resources: mergeResources(restoredResources, extras.resources ?? []),\n tools: toolsProvidedByHost ? (extras.tools ?? []) : base.tools,\n toolsProvided: toolsProvidedByHost ? true : base.toolsProvided,\n model: extras.model ?? base.model,\n reasoningEffort: extras.reasoningEffort ?? base.reasoningEffort,\n };\n}\n\nfunction draftSignature(payload: SaveComposerDraftRequest): string {\n const { expectedRevision: _revision, ...content } = payload;\n return JSON.stringify(content);\n}\n\nfunction mergeResources(base: ResourceRef[], additions: ResourceRef[]): ResourceRef[] {\n const seen = new Set<string>();\n return [...base, ...additions].filter((resource) => {\n const key = JSON.stringify(resource);\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n"],"mappings":";;;;;;AASA,SAAS,aAAa,WAAW,iBAAiB,QAAQ,gBAAgB;AAsEnE,SAAS,YACd,WACA,UAA8B,CAAC,GAChB;AACf,QAAM,EAAE,QAAQ,aAAa,0BA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53
|
};
|
|
54
54
|
}
|
|
55
|
+
function useEmbeddedSessionMcpApprovalPolicy(override = {}) {
|
|
56
|
+
const embedded = useEmbeddedSession(override);
|
|
57
|
+
const client = embedded.client;
|
|
58
|
+
if (typeof client.updateSessionMcpApprovalPolicy !== "function") {
|
|
59
|
+
throw new Error(
|
|
60
|
+
"@opengeni/react: useSessionMcpApprovalPolicy requires updateSessionMcpApprovalPolicy."
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
...embedded,
|
|
65
|
+
client
|
|
66
|
+
};
|
|
67
|
+
}
|
|
55
68
|
function useOpenGeniClient(override = {}) {
|
|
56
69
|
const context = useContext(OpenGeniContext);
|
|
57
70
|
const client = override.client ?? context?.client;
|
|
@@ -408,6 +421,7 @@ export {
|
|
|
408
421
|
useOpenGeni,
|
|
409
422
|
useEmbeddedSession,
|
|
410
423
|
useEmbeddedHumanInputSession,
|
|
424
|
+
useEmbeddedSessionMcpApprovalPolicy,
|
|
411
425
|
useOpenGeniClient,
|
|
412
426
|
usePolledValue,
|
|
413
427
|
useMutationRunner,
|
|
@@ -422,4 +436,4 @@ export {
|
|
|
422
436
|
isCreditExhaustion,
|
|
423
437
|
humanizeFailureReason
|
|
424
438
|
};
|
|
425
|
-
//# sourceMappingURL=chunk-
|
|
439
|
+
//# sourceMappingURL=chunk-I3BJZIG5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/session-context.ts","../src/lib/format.ts","../src/hooks/internal.ts"],"sourcesContent":["import type { StreamConnectionState, WorkspaceControlEvent } from \"@opengeni/sdk\";\nimport { createContext, useContext } from \"react\";\nimport type {\n EmbeddedHumanInputSessionClientLike,\n EmbeddedSessionMcpApprovalPolicyClientLike,\n EmbeddedSessionClientLike,\n SessionClientLike,\n} from \"./client\";\n\nexport type OpenGeniContextValue = {\n client: SessionClientLike;\n workspaceId: string;\n workspaceControlEvent: WorkspaceControlEvent | null;\n workspaceControlConnectionState: StreamConnectionState | \"idle\" | \"error\";\n registerSessionReconciler: (\n sessionId: string,\n key: string,\n reconcile: () => Promise<void>,\n ) => () => void;\n reconcileSession: (sessionId: string) => Promise<void>;\n};\n\nexport const OpenGeniContext = createContext<OpenGeniContextValue | null>(null);\n\nconst NOOP_REGISTER_RECONCILER: OpenGeniContextValue[\"registerSessionReconciler\"] = () => () =>\n undefined;\nconst NOOP_RECONCILE_SESSION: OpenGeniContextValue[\"reconcileSession\"] = async () => undefined;\n\nexport type ClientOverride = {\n client?: SessionClientLike | undefined;\n workspaceId?: string | undefined;\n};\n\nexport type EmbeddedSessionClientOverride = {\n client?: EmbeddedSessionClientLike | undefined;\n workspaceId?: string | undefined;\n};\n\nexport type EmbeddedHumanInputClientOverride = {\n client?: EmbeddedHumanInputSessionClientLike | undefined;\n workspaceId?: string | undefined;\n};\n\nexport type EmbeddedSessionMcpApprovalPolicyClientOverride = {\n client?: EmbeddedSessionMcpApprovalPolicyClientLike | undefined;\n workspaceId?: string | undefined;\n};\n\nexport type EmbeddedSessionContextValue = Omit<OpenGeniContextValue, \"client\"> & {\n client: EmbeddedSessionClientLike;\n};\n\n/** Resolve client + workspace from explicit overrides or the provider. */\nexport function useOpenGeni(override: ClientOverride = {}): OpenGeniContextValue {\n const context = useContext(OpenGeniContext);\n const client = override.client ?? context?.client;\n const workspaceId = override.workspaceId ?? context?.workspaceId;\n if (!client || !workspaceId) {\n throw new Error(\n \"@opengeni/react: no OpenGeni client/workspace available. Wrap the tree in <OpenGeniProvider> or pass { client, workspaceId } to the hook.\",\n );\n }\n return {\n client,\n workspaceId,\n workspaceControlEvent: context?.workspaceControlEvent ?? null,\n workspaceControlConnectionState: context?.workspaceControlConnectionState ?? \"idle\",\n registerSessionReconciler: context?.registerSessionReconciler ?? NOOP_REGISTER_RECONCILER,\n reconcileSession: context?.reconcileSession ?? NOOP_RECONCILE_SESSION,\n };\n}\n\n/**\n * Resolve the narrow client required by the session-only hooks. The full\n * provider client is structurally compatible, while an explicit host proxy\n * only needs to expose session/event/composer/queue/control operations.\n */\nexport function useEmbeddedSession(\n override: EmbeddedSessionClientOverride = {},\n): EmbeddedSessionContextValue {\n const context = useContext(OpenGeniContext);\n const client = override.client ?? context?.client;\n const workspaceId = override.workspaceId ?? context?.workspaceId;\n if (!client || !workspaceId) {\n throw new Error(\n \"@opengeni/react: no OpenGeni client/workspace available. Wrap the tree in <OpenGeniProvider> or pass { client, workspaceId } to the hook.\",\n );\n }\n return {\n client,\n workspaceId,\n workspaceControlEvent: context?.workspaceControlEvent ?? null,\n workspaceControlConnectionState: context?.workspaceControlConnectionState ?? \"idle\",\n registerSessionReconciler: context?.registerSessionReconciler ?? NOOP_REGISTER_RECONCILER,\n reconcileSession: context?.reconcileSession ?? NOOP_RECONCILE_SESSION,\n };\n}\n\n/**\n * Resolve the structured-input refinement without widening the baseline\n * session-only proxy contract.\n */\nexport function useEmbeddedHumanInputSession(override: EmbeddedHumanInputClientOverride = {}): Omit<\n EmbeddedSessionContextValue,\n \"client\"\n> & {\n client: EmbeddedHumanInputSessionClientLike;\n} {\n const embedded = useEmbeddedSession(override);\n const client = embedded.client as Partial<EmbeddedHumanInputSessionClientLike>;\n if (\n typeof client.listHumanInputRequests !== \"function\" ||\n typeof client.getHumanInputRequest !== \"function\" ||\n typeof client.submitHumanInputResponse !== \"function\"\n ) {\n throw new Error(\n \"@opengeni/react: useHumanInputRequests requires listHumanInputRequests, getHumanInputRequest, and submitHumanInputResponse.\",\n );\n }\n return {\n ...embedded,\n client: client as EmbeddedHumanInputSessionClientLike,\n };\n}\n\n/** Resolve the approval-policy refinement without widening session-only hosts. */\nexport function useEmbeddedSessionMcpApprovalPolicy(\n override: EmbeddedSessionMcpApprovalPolicyClientOverride = {},\n): Omit<EmbeddedSessionContextValue, \"client\"> & {\n client: EmbeddedSessionMcpApprovalPolicyClientLike;\n} {\n const embedded = useEmbeddedSession(override);\n const client = embedded.client as Partial<EmbeddedSessionMcpApprovalPolicyClientLike>;\n if (typeof client.updateSessionMcpApprovalPolicy !== \"function\") {\n throw new Error(\n \"@opengeni/react: useSessionMcpApprovalPolicy requires updateSessionMcpApprovalPolicy.\",\n );\n }\n return {\n ...embedded,\n client: client as EmbeddedSessionMcpApprovalPolicyClientLike,\n };\n}\n\n/**\n * Resolve the client only — for hooks that are not workspace-scoped\n * (`useWorkspaces`, `useBillingUsage`).\n */\nexport function useOpenGeniClient(\n override: Pick<ClientOverride, \"client\"> = {},\n): SessionClientLike {\n const context = useContext(OpenGeniContext);\n const client = override.client ?? context?.client;\n if (!client) {\n throw new Error(\n \"@opengeni/react: no OpenGeni client available. Wrap the tree in <OpenGeniProvider> or pass { client } to the hook.\",\n );\n }\n return client;\n}\n","/** Compact relative time: \"now\", \"42s\", \"7m\", \"3h\", \"2d\", then a date. */\nexport function formatRelativeTime(iso: string, now: Date = new Date()): string {\n const then = new Date(iso).getTime();\n if (Number.isNaN(then)) {\n return \"\";\n }\n const seconds = Math.max(0, Math.floor((now.getTime() - then) / 1000));\n if (seconds < 10) {\n return \"now\";\n }\n if (seconds < 60) {\n return `${seconds}s`;\n }\n const minutes = Math.floor(seconds / 60);\n if (minutes < 60) {\n return `${minutes}m`;\n }\n const hours = Math.floor(minutes / 60);\n if (hours < 24) {\n return `${hours}h`;\n }\n const days = Math.floor(hours / 24);\n if (days < 14) {\n return `${days}d`;\n }\n return new Date(iso).toLocaleDateString();\n}\n\n/** Human-readable byte size: \"512 B\", \"8.0 KB\", \"1.4 MB\", \"3 GB\". */\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) {\n return `${bytes} B`;\n }\n const units = [\"KB\", \"MB\", \"GB\"] as const;\n let value = bytes / 1024;\n for (const unit of units) {\n if (value < 1024 || unit === \"GB\") {\n return `${value.toFixed(value < 10 ? 1 : 0)} ${unit}`;\n }\n value /= 1024;\n }\n return `${bytes} B`;\n}\n\n/** Single-line preview of arbitrary text, for tiles and collapsed rows. */\nexport function truncate(text: string, maxLength: number): string {\n const collapsed = text.replace(/\\s+/g, \" \").trim();\n if (collapsed.length <= maxLength) {\n return collapsed;\n }\n return `${collapsed.slice(0, Math.max(0, maxLength - 1)).trimEnd()}…`;\n}\n\n/** Render an unknown payload as readable text (pretty JSON when possible). */\nexport function stringifyPayload(value: unknown): string {\n if (value === null || value === undefined) {\n return \"\";\n }\n if (typeof value === \"string\") {\n const parsed = tryParseJson(value);\n if (parsed !== undefined && typeof parsed === \"object\") {\n return stringifyPayload(parsed);\n }\n return value;\n }\n try {\n return JSON.stringify(value, null, 2) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\n/** JSON.parse that returns `undefined` instead of throwing. */\nexport function tryParseJson(text: string): unknown {\n const trimmed = text.trim();\n if (!trimmed.startsWith(\"{\") && !trimmed.startsWith(\"[\") && !trimmed.startsWith('\"')) {\n return undefined;\n }\n try {\n return JSON.parse(trimmed) as unknown;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The canonical credit-death sentence. Credit exhaustion is the one failure a\n * user can fix themselves — the copy must say what happened (empty balance),\n * what to do (add credits), and what is safe (nothing was lost). Crucially it\n * must NOT say \"send a message to revive\": a revive turn burns credits the\n * workspace no longer has.\n */\nexport const CREDIT_EXHAUSTION_MESSAGE =\n \"Out of OpenGeni credits — this workspace's balance is empty. Add credits to continue; the conversation is preserved.\";\n\n/**\n * Does this failure/completion payload (or raw error string) mean the\n * workspace ran out of OpenGeni credits? Matches the engine's\n * \"insufficient OpenGeni credits\" text (case-insensitive, substring — it\n * arrives both bare and wrapped in \"Activity task failed: …\") and the\n * budget-exhausted segment limit the engine stamps on a turn it ended early.\n */\nexport function isCreditExhaustion(\n input: { error?: string | null; detail?: string | null; segmentLimit?: string | null } | string,\n): boolean {\n if (typeof input === \"string\") {\n return input.toLowerCase().includes(\"insufficient opengeni credits\");\n }\n if (input.segmentLimit === \"budget_exhausted\") {\n return true;\n }\n for (const text of [input.error, input.detail]) {\n if (typeof text === \"string\" && text.toLowerCase().includes(\"insufficient opengeni credits\")) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Humanize engine/provider failure text before it reaches the timeline or a\n * failure banner. Raw provider errors leak the wrong audience's instructions —\n * \"Incorrect API key … find your API key at platform.openai.com\" tells a\n * managed-deployment USER to fix credentials only an OPERATOR controls (and is\n * flatly wrong for Azure or subscription-backed engines). Auth, quota, and\n * credit-exhaustion failures collapse to one neutral, honest sentence; every\n * other reason passes through untouched. Raw payloads stay available in the\n * debug surfaces.\n */\nexport function humanizeFailureReason(reason: string | null): string | null {\n if (!reason) {\n return reason;\n }\n if (isCreditExhaustion(reason)) {\n return CREDIT_EXHAUSTION_MESSAGE;\n }\n const normalized = reason.toLowerCase();\n const authFailure =\n normalized.includes(\"incorrect api key\") ||\n normalized.includes(\"invalid api key\") ||\n normalized.includes(\"invalid_api_key\") ||\n normalized.includes(\"platform.openai.com/account/api-keys\") ||\n (normalized.includes(\"401\") &&\n (normalized.includes(\"api key\") || normalized.includes(\"unauthorized\")));\n if (authFailure) {\n return \"The model provider rejected this deployment's engine credentials. Sending messages won't help until the deployment's engine configuration is fixed.\";\n }\n const quotaFailure =\n normalized.includes(\"insufficient_quota\") || normalized.includes(\"exceeded your current quota\");\n if (quotaFailure) {\n return \"The model provider refused the request: this deployment's provider quota is exhausted.\";\n }\n return reason;\n}\n","import type { SessionEvent } from \"@opengeni/sdk\";\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport type { EmbeddedSessionClientLike } from \"../client\";\n\nexport type AsyncListState<T> = {\n data: T | null;\n loading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n};\n\n/**\n * Shared fetch + optional polling loop for the list/read hooks. Stale\n * responses (superseded by a newer load or an unmount) are dropped.\n */\nexport function usePolledValue<T>(\n load: (signal?: AbortSignal) => Promise<T>,\n options: { pollIntervalMs?: number | undefined; enabled?: boolean | undefined } = {},\n): AsyncListState<T> {\n const enabled = options.enabled ?? true;\n const pollIntervalMs = options.pollIntervalMs;\n const [data, setData] = useState<T | null>(null);\n const [loading, setLoading] = useState(enabled);\n const [error, setError] = useState<Error | null>(null);\n const generation = useRef(0);\n const activeLoadRef = useRef(load);\n useLayoutEffect(() => {\n activeLoadRef.current = load;\n }, [load]);\n const requestAbortRef = useRef<AbortController | null>(null);\n const [stateIdentity, setStateIdentity] = useState<{ load: typeof load }>(() => ({ load }));\n\n // A new loader identity means a new query (different session/workspace/...):\n // drop the previous result instead of showing it as the new query's data.\n useEffect(() => {\n if (stateIdentity.load !== load) {\n setStateIdentity({ load });\n setData(null);\n setError(null);\n }\n }, [load, stateIdentity.load]);\n\n const run = useCallback(async () => {\n // A callback retained by a completed mutation from the previous query must\n // not supersede or settle the current query's request.\n if (activeLoadRef.current !== load) return;\n const ticket = ++generation.current;\n requestAbortRef.current?.abort();\n const requestAbort = new AbortController();\n requestAbortRef.current = requestAbort;\n try {\n const result = await load(requestAbort.signal);\n if (\n ticket === generation.current &&\n activeLoadRef.current === load &&\n !requestAbort.signal.aborted\n ) {\n setData(result);\n setError(null);\n setLoading(false);\n }\n } catch (cause) {\n if (\n ticket === generation.current &&\n activeLoadRef.current === load &&\n !requestAbort.signal.aborted\n ) {\n setError(cause instanceof Error ? cause : new Error(String(cause)));\n setLoading(false);\n }\n } finally {\n if (requestAbortRef.current === requestAbort) {\n requestAbortRef.current = null;\n }\n }\n }, [load]);\n\n useEffect(() => {\n if (!enabled) {\n setLoading(false);\n return;\n }\n setLoading(true);\n void run();\n if (pollIntervalMs === undefined || pollIntervalMs <= 0) {\n return () => {\n generation.current += 1;\n requestAbortRef.current?.abort();\n };\n }\n const timer = setInterval(() => void run(), pollIntervalMs);\n return () => {\n clearInterval(timer);\n generation.current += 1;\n requestAbortRef.current?.abort();\n };\n }, [run, enabled, pollIntervalMs]);\n\n const identityMatches = stateIdentity.load === load;\n return {\n data: identityMatches ? data : null,\n loading: identityMatches ? loading : enabled,\n error: identityMatches ? error : null,\n refresh: run,\n };\n}\n\nexport type MutationState = {\n mutating: boolean;\n mutationError: Error | null;\n clearMutationError: () => void;\n};\n\n/**\n * Shared async mutation runner for the write hooks. `run` resolves with the\n * operation's value, or `null` after capturing the error in `mutationError`\n * (callers then roll back optimistic state).\n */\nexport function useMutationRunner(identity: unknown = undefined): MutationState & {\n run: <T>(operation: () => Promise<T>) => Promise<T | null>;\n} {\n const [mutating, setMutating] = useState(false);\n const [mutationError, setMutationError] = useState<Error | null>(null);\n const [stateIdentity, setStateIdentity] = useState<unknown>(() => identity);\n const inFlight = useRef(0);\n const generation = useRef(0);\n const identityRef = useRef(identity);\n useLayoutEffect(() => {\n if (Object.is(identityRef.current, identity)) return;\n identityRef.current = identity;\n generation.current += 1;\n inFlight.current = 0;\n }, [identity]);\n const mounted = useRef(true);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n useEffect(() => {\n if (!Object.is(stateIdentity, identity)) {\n setStateIdentity(() => identity);\n setMutating(false);\n setMutationError(null);\n }\n }, [identity, stateIdentity]);\n const run = useCallback(\n async <T>(operation: () => Promise<T>): Promise<T | null> => {\n const ownedIdentity = identity;\n const ownedGeneration = generation.current;\n if (!Object.is(identityRef.current, ownedIdentity)) return null;\n inFlight.current += 1;\n if (mounted.current) {\n setMutating(true);\n setMutationError(null);\n }\n try {\n const result = await operation();\n if (\n !mounted.current ||\n generation.current !== ownedGeneration ||\n !Object.is(identityRef.current, ownedIdentity)\n ) {\n return null;\n }\n return result;\n } catch (cause) {\n if (\n mounted.current &&\n generation.current === ownedGeneration &&\n Object.is(identityRef.current, ownedIdentity)\n ) {\n setMutationError(cause instanceof Error ? cause : new Error(String(cause)));\n }\n return null;\n } finally {\n if (\n generation.current === ownedGeneration &&\n Object.is(identityRef.current, ownedIdentity)\n ) {\n inFlight.current -= 1;\n if (mounted.current && inFlight.current === 0) {\n setMutating(false);\n }\n }\n }\n },\n [identity],\n );\n const identityMatches = Object.is(stateIdentity, identity);\n return {\n mutating: identityMatches && mutating,\n mutationError: identityMatches ? mutationError : null,\n clearMutationError: useCallback(() => {\n if (Object.is(identityRef.current, identity)) setMutationError(null);\n }, [identity]),\n run,\n };\n}\n\nexport type SessionEventFeedOptions = {\n /**\n * Share an existing event log (from `useSessionEvents`) instead of opening\n * a second stream. When omitted the hook tails the session's event stream\n * itself, starting at the current `lastSequence`.\n */\n events?: SessionEvent[] | undefined;\n enabled?: boolean | undefined;\n};\n\n/**\n * Invoke `onEvent` for every session event matching `match` — the live-update\n * primitive behind `useTurnQueue` and `useGoal`. Either watches a shared\n * `events` log or tails the stream directly (reconnect handled by the SDK).\n */\nexport function useSessionEventTrigger(\n client: EmbeddedSessionClientLike,\n workspaceId: string,\n sessionId: string | null | undefined,\n match: (event: SessionEvent) => boolean,\n onEvent: (event: SessionEvent) => void,\n options: SessionEventFeedOptions = {},\n reconcileBeforeLive?: (() => void | Promise<void>) | undefined,\n): void {\n const enabled = options.enabled ?? true;\n const events = options.events;\n const sharedFeed = events !== undefined;\n const matchRef = useRef(match);\n const onEventRef = useRef(onEvent);\n const reconcileBeforeLiveRef = useRef(reconcileBeforeLive);\n useLayoutEffect(() => {\n matchRef.current = match;\n onEventRef.current = onEvent;\n reconcileBeforeLiveRef.current = reconcileBeforeLive;\n }, [match, onEvent, reconcileBeforeLive]);\n const consumedRef = useRef(0);\n const feedKeyRef = useRef<string | null>(null);\n\n // Shared-log mode: scan only the unseen tail on every append.\n useEffect(() => {\n if (!sharedFeed || !enabled || !sessionId) {\n return;\n }\n const feedKey = `${workspaceId}\\u0000${sessionId}`;\n const firstSequence = events[0]?.sequence ?? 0;\n // A new session target or a log reset (sequence restarted below the\n // cursor) restarts consumption from the top of the shared log.\n if (feedKeyRef.current !== feedKey || firstSequence > consumedRef.current + 1) {\n feedKeyRef.current = feedKey;\n consumedRef.current = 0;\n }\n for (const event of events) {\n if (event.sequence <= consumedRef.current) {\n continue;\n }\n consumedRef.current = event.sequence;\n if (matchRef.current(event)) {\n onEventRef.current(event);\n }\n }\n }, [sharedFeed, enabled, events, workspaceId, sessionId]);\n\n // Self-stream mode: tail from the session's current lastSequence.\n useEffect(() => {\n if (sharedFeed || !enabled || !sessionId) {\n return;\n }\n const controller = new AbortController();\n void (async () => {\n try {\n const session = await client.getSession(workspaceId, sessionId);\n if (controller.signal.aborted) {\n return;\n }\n const stream = client.streamEvents(workspaceId, sessionId, {\n after: session.lastSequence,\n signal: controller.signal,\n beforeLive: async () => await reconcileBeforeLiveRef.current?.(),\n });\n for await (const event of stream) {\n if (matchRef.current(event)) {\n onEventRef.current(event);\n }\n }\n } catch {\n // Live updates are best-effort: the read hooks still expose refresh()\n // and the initial load already populated state.\n }\n })();\n return () => {\n controller.abort();\n };\n }, [sharedFeed, enabled, client, workspaceId, sessionId]);\n}\n\n/** Debounce rapid event bursts into one trailing call (default 150ms). */\nexport function useDebouncedCallback(callback: () => void, delayMs = 150): () => void {\n const callbackRef = useRef(callback);\n useLayoutEffect(() => {\n callbackRef.current = callback;\n }, [callback]);\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(() => {\n return () => {\n if (timerRef.current !== null) {\n clearTimeout(timerRef.current);\n }\n };\n }, []);\n return useCallback(() => {\n if (timerRef.current !== null) {\n clearTimeout(timerRef.current);\n }\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n callbackRef.current();\n }, delayMs);\n }, [delayMs]);\n}\n"],"mappings":";AACA,SAAS,eAAe,kBAAkB;AAqBnC,IAAM,kBAAkB,cAA2C,IAAI;AAE9E,IAAM,2BAA8E,MAAM,MACxF;AACF,IAAM,yBAAmE,YAAY;AA2B9E,SAAS,YAAY,WAA2B,CAAC,GAAyB;AAC/E,QAAM,UAAU,WAAW,eAAe;AAC1C,QAAM,SAAS,SAAS,UAAU,SAAS;AAC3C,QAAM,cAAc,SAAS,eAAe,SAAS;AACrD,MAAI,CAAC,UAAU,CAAC,aAAa;AAC3B,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,uBAAuB,SAAS,yBAAyB;A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AU,MAAM;AACd,WAAO,MAAM;AACX,UAAI,SAAS,YAAY,MAAM;AAC7B,qBAAa,SAAS,OAAO;AAAA,MAC/B;AAAA,IACF;AAAA,EACF,GAAG,CAAC,CAAC;AACL,SAAO,YAAY,MAAM;AACvB,QAAI,SAAS,YAAY,MAAM;AAC7B,mBAAa,SAAS,OAAO;AAAA,IAC/B;AACA,aAAS,UAAU,WAAW,MAAM;AAClC,eAAS,UAAU;AACnB,kBAAY,QAAQ;AAAA,IACtB,GAAG,OAAO;AAAA,EACZ,GAAG,CAAC,OAAO,CAAC;AACd;","names":[]}
|
|
@@ -4,11 +4,11 @@ import {
|
|
|
4
4
|
import {
|
|
5
5
|
shouldSteerOnKey,
|
|
6
6
|
shouldSubmitOnKey
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-AVPU5PMC.js";
|
|
8
8
|
import {
|
|
9
9
|
formatBytes,
|
|
10
10
|
formatRelativeTime
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-I3BJZIG5.js";
|
|
12
12
|
|
|
13
13
|
// src/commands/registry.ts
|
|
14
14
|
function parseCommandLine(value) {
|
|
@@ -696,7 +696,7 @@ function useChatComposerController({
|
|
|
696
696
|
document.addEventListener(OPEN_WORKSTREAM_CONTROL_EVENT, openControl);
|
|
697
697
|
return () => document.removeEventListener(OPEN_WORKSTREAM_CONTROL_EVENT, openControl);
|
|
698
698
|
}, [id, paused]);
|
|
699
|
-
const
|
|
699
|
+
const blockedByAttachment = attachments?.hasUnresolved === true;
|
|
700
700
|
const hasReadyAttachment = (attachments?.readyResources.length ?? 0) > 0;
|
|
701
701
|
const [dragging, setDragging] = useState2(false);
|
|
702
702
|
const dragCarriesFiles = (event) => event.dataTransfer !== null && [...event.dataTransfer.types].includes("Files");
|
|
@@ -778,7 +778,7 @@ function useChatComposerController({
|
|
|
778
778
|
});
|
|
779
779
|
const paletteEnabled = commandContext !== void 0;
|
|
780
780
|
const commandDraftBlocked = paletteEnabled && palette.isCommandDraft;
|
|
781
|
-
const submitBlocker = disabled ? "disabled" :
|
|
781
|
+
const submitBlocker = disabled ? "disabled" : blockedByAttachment ? "attachment" : delivery.sending || submitting ? "sending" : commandDraftBlocked ? "command" : delivery.canSend || hasReadyAttachment ? null : "empty";
|
|
782
782
|
const canSubmit = submitBlocker === null;
|
|
783
783
|
const submit = useCallback2(
|
|
784
784
|
async (mode) => {
|
|
@@ -787,7 +787,8 @@ function useChatComposerController({
|
|
|
787
787
|
delivery.clearError();
|
|
788
788
|
return false;
|
|
789
789
|
}
|
|
790
|
-
if (disabled ||
|
|
790
|
+
if (disabled || blockedByAttachment || delivery.sending || submittingRef.current)
|
|
791
|
+
return false;
|
|
791
792
|
if (!delivery.canSend && !hasReadyAttachment) return false;
|
|
792
793
|
submittingRef.current = true;
|
|
793
794
|
setSubmitting(true);
|
|
@@ -799,7 +800,7 @@ function useChatComposerController({
|
|
|
799
800
|
}
|
|
800
801
|
},
|
|
801
802
|
[
|
|
802
|
-
|
|
803
|
+
blockedByAttachment,
|
|
803
804
|
commandDraftBlocked,
|
|
804
805
|
delivery,
|
|
805
806
|
disabled,
|
|
@@ -2390,4 +2391,4 @@ export {
|
|
|
2390
2391
|
useTranscription,
|
|
2391
2392
|
ComposerTranscriptionControl
|
|
2392
2393
|
};
|
|
2393
|
-
//# sourceMappingURL=chunk-
|
|
2394
|
+
//# sourceMappingURL=chunk-RDPDU4TA.js.map
|