@gemies/sdk 6.3.0 → 6.4.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/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # @gemies/sdk
2
2
 
3
+ ## 6.4.0
4
+
5
+ - **Stop no longer cancels an answer that had already finished.** The stop endpoint answers
6
+ `finishing` or `completed` when the turn was past its commit point; Stop cut the stream on any
7
+ `2xx`, so a stored answer settled as `cancelled` and kept `unsaved`. Now only `cancelled` cuts it;
8
+ any other answer lets the stream reach its own end, completed.
9
+ - **Clearing a conversation waits for its running turn to end.** `useConversationStream().stop()`
10
+ now returns `Promise<boolean>`: `true` once the turn's stream is over, `false` when the server
11
+ could not stop it (the error is surfaced, as before). `clearConversation` awaits it before the
12
+ server clear, and refuses (keeping everything) when the turn could not be stopped, so a turn that
13
+ was finishing can no longer save its question and answer back into the cleared thread.
14
+ `GemieChatTurnControl` gains `ended`, which settles when `finish()` has run.
15
+ - **Decks, dashboards and every other canvas open in the host.** `host.onArtifact` now receives
16
+ each finished `canvas` result as a `GemieArtifact` (`type` the canvas type, `content` its data,
17
+ `id` the tool call), read by `canvasResultOf` like the thread. A refused canvas (`{ error }`)
18
+ opens nothing.
19
+
20
+ ## 6.3.1
21
+
22
+ - **A turn's attachments keep the order they were sent in** (`TurnAttachments`): a document sent
23
+ between two photos is drawn between them. Pictures next to each other still share a row.
24
+ - **No voice call in a group**: `GemieChatContent` offers none when `group` is set. A call has one
25
+ gemie and a group's turns are its members'; the API refuses one there too.
26
+
3
27
  ## 6.3.0
4
28
 
5
29
  - **A turn's attachments are drawn as media** (`TurnAttachments`, used by every user turn in the
package/README.md CHANGED
@@ -397,7 +397,7 @@ const host: GemieRuntimeHost = {
397
397
  closeConversation: () => router.replace('/'),
398
398
  // what only the host can show: credits, an artifact panel, a haptic tick
399
399
  onUsage: (frame) => updateCredits(frame.credits_remaining),
400
- onArtifact: (artifact) => rightPanel.show(artifact),
400
+ onArtifact: (artifact) => rightPanel.show(artifact), // a generated file or a canvas: deck, dashboard, chart…
401
401
  turnRequest: () => ({ webSearch: composerMenu.webSearch, deepResearch: composerMenu.deepResearch }),
402
402
  // where the work of a turn is read; return false to decline an automatic opening
403
403
  showThought: (opening) => (opening === 'automatic' && panel.isOpen ? false : panel.show('thought')),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gemies/sdk",
3
- "version": "6.3.0",
3
+ "version": "6.4.0",
4
4
  "description": "The Gemies SDK: the conversation runtime, chat UI, voice calls and dictation for Oxy apps that talk to a gemie",
5
5
  "main": "src/index.ts",
6
6
  "react-native": "src/index.ts",
@@ -507,10 +507,11 @@ function GemieConversationView({
507
507
  },
508
508
  [composer],
509
509
  );
510
- // Without a call handed down (a text-only entry), the chat is text-only whatever `voice` says.
510
+ // Without a call handed down (a text-only entry), the chat is text-only whatever `voice` says. A
511
+ // group is too: a call has one gemie, and a group's turns are its members' (the server refuses it).
511
512
  const VoiceCall = useContext(VoiceCallContext);
512
513
  const voice = useChatVoice({
513
- options: VoiceCall === null ? false : voiceOptions,
514
+ options: VoiceCall === null || group !== undefined ? false : voiceOptions,
514
515
  conversationId,
515
516
  agentId,
516
517
  isFocused,
@@ -176,26 +176,42 @@ export function TurnAttachments({
176
176
  tone?: Tone;
177
177
  onColor?: string;
178
178
  }) {
179
- const items = getAttachmentsFromContent(content);
180
- if (items.length === 0) return null;
181
- const inline = items.filter((item) => item.type === 'inline-image');
182
- const files = items.filter((item) => item.type === 'file');
179
+ const runs = attachmentRuns(getAttachmentsFromContent(content));
180
+ if (runs.length === 0) return null;
183
181
  return (
184
182
  <View className="gap-2">
185
- {inline.length > 0 ? (
186
- <View className="flex-row flex-wrap gap-2">
187
- {inline.map((item) => (
188
- <Attachment key={item.url} item={item} tone={tone} onColor={onColor} />
189
- ))}
190
- </View>
191
- ) : null}
192
- {files.map((item) => (
193
- <Attachment key={item.fileId} item={item} tone={tone} onColor={onColor} />
194
- ))}
183
+ {runs.map((run) =>
184
+ Array.isArray(run) ? (
185
+ <View key={`images:${run[0]?.url}`} className="flex-row flex-wrap gap-2">
186
+ {run.map((item) => (
187
+ <Attachment key={item.url} item={item} tone={tone} onColor={onColor} />
188
+ ))}
189
+ </View>
190
+ ) : (
191
+ <Attachment key={run.fileId} item={run} tone={tone} onColor={onColor} />
192
+ ),
193
+ )}
195
194
  </View>
196
195
  );
197
196
  }
198
197
 
198
+ type InlineImage = Extract<TurnAttachment, { type: 'inline-image' }>;
199
+
200
+ /**
201
+ * The attachments in the order they were sent, the pictures next to each other drawn as one row.
202
+ * Drawing every picture first put a document sent between two photos after both of them.
203
+ */
204
+ function attachmentRuns(items: readonly TurnAttachment[]): Array<InlineImage[] | FileAttachment> {
205
+ const runs: Array<InlineImage[] | FileAttachment> = [];
206
+ for (const item of items) {
207
+ const last = runs.at(-1);
208
+ if (item.type === 'file') runs.push(item);
209
+ else if (Array.isArray(last)) last.push(item);
210
+ else runs.push([item]);
211
+ }
212
+ return runs;
213
+ }
214
+
199
215
  /** Whether a turn has anything to draw as an attachment. */
200
216
  export function hasAttachments(content: MessageContent | null | undefined): boolean {
201
217
  return getAttachmentsFromContent(content).length > 0;
@@ -17,6 +17,10 @@ export function createChatTurnControl(
17
17
  const id = createRandomUuid();
18
18
  let stopping: Promise<void> | undefined;
19
19
  let ended = false;
20
+ let markEnded!: () => void;
21
+ const endedPromise = new Promise<void>((resolve) => {
22
+ markEnded = resolve;
23
+ });
20
24
  const lifetime = new AbortController();
21
25
  const epoch = linked.client.getSessionEpoch();
22
26
  const current = () => linked.client.getSessionEpoch() === epoch;
@@ -29,7 +33,15 @@ export function createChatTurnControl(
29
33
  });
30
34
  return {
31
35
  id,
32
- /** Only a deliberate Stop invokes this. View teardown merely aborts its transport. */
36
+ /** Settles once `finish()` has run: the turn's stream is over and nothing more will be written. */
37
+ ended: endedPromise,
38
+ /**
39
+ * Only a deliberate Stop invokes this. View teardown merely aborts its transport.
40
+ *
41
+ * Resolves once the server has answered. Only an answer of `cancelled` cuts the stream here:
42
+ * a turn already past its commit point (`finishing`, `completed`, `failed`) was not stopped,
43
+ * and its stream carries it to its own end, stored. Await `ended` to know it is over.
44
+ */
33
45
  stop(): Promise<void> {
34
46
  if (stopping) return stopping;
35
47
  if (ended || controller.signal.aborted) return Promise.resolve();
@@ -51,8 +63,8 @@ export function createChatTurnControl(
51
63
  await response.body?.cancel();
52
64
  throw new Error('Generation could not be stopped. Try again.');
53
65
  }
54
- await response.body?.cancel();
55
- controller.abort();
66
+ const answer: unknown = await response.json().catch(() => null);
67
+ if ((answer as { state?: unknown } | null)?.state === 'cancelled') controller.abort();
56
68
  })().catch((error) => {
57
69
  stopping = undefined;
58
70
  throw error;
@@ -66,6 +78,7 @@ export function createChatTurnControl(
66
78
  lifetime.abort();
67
79
  unsubscribe();
68
80
  linked.dispose();
81
+ markEnded();
69
82
  },
70
83
  };
71
84
  }
@@ -3,6 +3,7 @@ import { ASK_USER_QUESTION_TOOL } from '../tools';
3
3
  import { useOxy } from '@oxy.so/services/ui/client';
4
4
  import { useQueryClient } from '@tanstack/react-query';
5
5
  import { useCallback, useEffect, useRef, useState } from 'react';
6
+ import { canvasResultOf } from '../lib/canvas-result';
6
7
  import { useLabels } from '../lib/labels';
7
8
  import { useGemieApi } from './api';
8
9
  import { useAppAssertionHeaders } from './app-assertion';
@@ -104,14 +105,31 @@ interface StreamErrorResponse {
104
105
  }
105
106
 
106
107
  /**
107
- * The artifact a tool result carries, if it carries one: a generated file, or
108
- * an `artifact` object a tool returned for its own panel.
108
+ * The artifact a tool result carries, if it carries one: a generated file, a
109
+ * canvas (a deck, a dashboard, a chart…), or an `artifact` object a tool
110
+ * returned for its own panel. A canvas is read by `canvasResultOf`, the reader
111
+ * the thread draws it with, so the host opens exactly what the thread shows.
109
112
  */
110
113
  function artifactOf(
111
114
  toolCallId: string,
112
115
  name: string | undefined,
113
116
  output: unknown,
114
117
  ): GemieArtifact | null {
118
+ const canvas = canvasResultOf({
119
+ toolCallId,
120
+ toolName: name ?? '',
121
+ state: 'result',
122
+ result: output,
123
+ });
124
+ if (canvas) {
125
+ return {
126
+ id: toolCallId,
127
+ type: canvas.type,
128
+ content: canvas.data,
129
+ title: canvas.title,
130
+ timestamp: Date.now(),
131
+ };
132
+ }
115
133
  if (output === null || typeof output !== 'object') return null;
116
134
  // Structural per-tool output, read the way the tools write it.
117
135
  const result = output as Record<string, any>;
@@ -1591,12 +1609,20 @@ export function useConversationStream({
1591
1609
  setComposerPhase('idle');
1592
1610
  }, [setComposerPhase]);
1593
1611
 
1594
- const stop = useCallback(() => {
1612
+ /**
1613
+ * Stop the running turn, and settle once it has really ended: `true` when its stream is over
1614
+ * (cancelled, or — when the server answered that it had already finished — completed and
1615
+ * stored), `false` when the server could not stop it, which is surfaced as the stream's error
1616
+ * and leaves the turn running. With no turn running there is nothing to wait for.
1617
+ */
1618
+ const stop = useCallback(async (): Promise<boolean> => {
1595
1619
  const turn = turnControlRef.current;
1596
1620
  const turnGeneration = turnGenerationRef.current;
1597
- if (!turn) return;
1621
+ if (!turn) return true;
1598
1622
  setComposerPhase('stopping');
1599
- void turn.stop().catch((error: unknown) => {
1623
+ try {
1624
+ await turn.stop();
1625
+ } catch (error: unknown) {
1600
1626
  if (
1601
1627
  turnControlRef.current === turn &&
1602
1628
  turnGenerationRef.current === turnGeneration &&
@@ -1605,7 +1631,10 @@ export function useConversationStream({
1605
1631
  setError(error instanceof Error ? error : new Error('Generation could not be stopped.'));
1606
1632
  setComposerPhase('streaming');
1607
1633
  }
1608
- });
1634
+ return false;
1635
+ }
1636
+ await turn.ended;
1637
+ return true;
1609
1638
  }, [setComposerPhase]);
1610
1639
 
1611
1640
  const clearError = useCallback(() => {
@@ -407,7 +407,7 @@ export function useConversationThread({
407
407
 
408
408
  /** Leave this thread for an empty one. Nothing is deleted: the conversation stays in the list. */
409
409
  const startOver = useCallback(() => {
410
- stop();
410
+ void stop();
411
411
  setMessages([]);
412
412
  clearFailedTurn();
413
413
  host.closeConversation?.();
@@ -526,7 +526,7 @@ export function useConversationThread({
526
526
  );
527
527
 
528
528
  const stopGeneration = useCallback(() => {
529
- stop();
529
+ void stop();
530
530
  }, [stop]);
531
531
 
532
532
  /**
@@ -554,19 +554,27 @@ export function useConversationThread({
554
554
  *
555
555
  * A turn still streaming is stopped first rather than refused: the person
556
556
  * has just confirmed they want the thread empty, and an answer that kept
557
- * arriving into it would be the next thing to clear. Stopping settles the
558
- * assistant placeholder as `cancelled` and lets the server close the turn,
559
- * so the clear that follows is of a thread nothing is writing to.
557
+ * arriving into it would be the next thing to clear. The clear WAITS for
558
+ * that turn to end, not just for Stop to be sent: the server stores a turn
559
+ * (its question and its answer) as it finishes, so a clear sent while it was
560
+ * still finishing was undone by that late save. Once `stop()` settles the
561
+ * turn is over — cancelled, so the server never stores it, or already
562
+ * finished and stored, so the clear removes it — and the clear that follows
563
+ * is of a thread nothing is writing to.
560
564
  *
561
565
  * A refusal keeps everything: the screen is not reset, the cache is not
562
566
  * touched, and the error is surfaced — a cleared view whose history returns
563
- * on the next fetch is exactly the state this exists to end.
567
+ * on the next fetch is exactly the state this exists to end. A turn that
568
+ * could not be stopped is such a refusal.
564
569
  *
565
570
  * With no conversation id there is nothing persisted to clear, so the
566
571
  * screen's own list is all there is and the local reset is the whole job.
567
572
  */
568
573
  const clearConversation = useCallback(async (): Promise<boolean> => {
569
- if (isLoading) stop();
574
+ if (isLoading && !(await stop())) {
575
+ toast.error(labels.conversationClearFailed);
576
+ return false;
577
+ }
570
578
 
571
579
  if (conversationId) {
572
580
  try {