@gemies/sdk 10.11.0 → 10.14.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
+ ## 10.14.0
4
+
5
+ ### What a coding agent's turn changed, and the way back
6
+
7
+ A turn that carries a checkpoint (Gemies ADR 0052) shows its changes once, in the "N files changed"
8
+ chip, and not as a step of the work log. The diff viewer now draws a tree of the changed files above
9
+ the diffs, and pressing a file opens its diff. From a checkpointed turn the viewer also offers the
10
+ whole conversation's changes and, where Gemies allows it, reverting to before the turn, after asking.
11
+
12
+ Two optional host callbacks carry what the SDK cannot ask `/v1` for: `listTurnCheckpoints` and
13
+ `revertTurnCheckpoint`. Without them a turn's diffs still show, from the thread alone. New copy under
14
+ `chat.checkpoints.*` and `chat.fileTree.*`.
15
+
16
+ ## 10.13.0
17
+
18
+ ### A usage limit says when it resets
19
+
20
+ `UsageLimitDetails` carries `resetsAt` (ISO 8601) and `autoResume`. A model provider's usage limit
21
+ (`details.limitType: 'provider_usage'`, exported as `PROVIDER_USAGE_LIMIT_TYPE`) is now raised as a
22
+ `UsageLimitError` of type `rate_limit` instead of a failed turn. When `autoResume` is true the
23
+ server has kept the message and answers it after the reset, so the send ends `sent` and the message
24
+ stays in the thread rather than going back to the composer. The plan window's `details` and
25
+ `suggestedAction` now also arrive on the open stream.
26
+
3
27
  ## 10.11.0
4
28
 
5
29
  ### Error rows name the request
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gemies/sdk",
3
- "version": "10.11.0",
3
+ "version": "10.14.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",
@@ -5,14 +5,25 @@ import { Text } from '@oxy.so/bloom/typography';
5
5
  import { useMemo, useState } from 'react';
6
6
  import { View } from 'react-native';
7
7
  import { useLabels } from '../../lib/labels';
8
+ import type { MessageCheckpoint } from '../../runtime/thread/checkpoints';
8
9
  import { type CallFileChange, fileChangeTotals } from '../../runtime/thread/file-changes';
9
10
  import { FileChangesViewer } from './FileChangesViewer';
11
+ import { TurnChangesViewer } from './TurnChangesViewer';
10
12
 
11
13
  /**
12
14
  * "3 files changed +42 −7", under a turn in which an agent edited files: a chip that opens the
13
15
  * viewer on every file the turn changed. Nothing is drawn for a turn that changed none.
16
+ *
17
+ * A turn with a checkpoint (`checkpoint`) opens the viewer with the rest it offers: the whole
18
+ * conversation's changes and, where Gemies allows it, going back to before the turn.
14
19
  */
15
- export function FileChangesCard({ changes }: { changes: readonly CallFileChange[] }) {
20
+ export function FileChangesCard({
21
+ changes,
22
+ checkpoint,
23
+ }: {
24
+ changes: readonly CallFileChange[];
25
+ checkpoint?: MessageCheckpoint & { conversationId: string };
26
+ }) {
16
27
  const { t } = useLabels();
17
28
  const styles = useStyles();
18
29
  const [open, setOpen] = useState(false);
@@ -37,9 +48,16 @@ export function FileChangesCard({ changes }: { changes: readonly CallFileChange[
37
48
  {' '}
38
49
  <Text style={styles.removed}>{`−${totals.deletions}`}</Text>
39
50
  </Chip>
40
- {open ? (
51
+ {!open ? null : checkpoint === undefined ? (
41
52
  <FileChangesViewer changes={changes} open={open} onClose={() => setOpen(false)} />
42
- ) : null}
53
+ ) : (
54
+ <TurnChangesViewer
55
+ changes={changes}
56
+ checkpoint={checkpoint}
57
+ open={open}
58
+ onClose={() => setOpen(false)}
59
+ />
60
+ )}
43
61
  </View>
44
62
  );
45
63
  }
@@ -10,7 +10,7 @@ import {
10
10
  } from '@oxy.so/bloom/segmented-control';
11
11
  import { createTokenStyles } from '@oxy.so/bloom/theme';
12
12
  import { Muted } from '@oxy.so/bloom/typography';
13
- import { useMemo, useState } from 'react';
13
+ import { type ReactNode, useMemo, useRef, useState } from 'react';
14
14
  import { View } from 'react-native';
15
15
  import { useLabels } from '../../lib/labels';
16
16
  import { type DiffComment, diffCommentsOn } from '../../runtime/thread/diff-comments';
@@ -18,6 +18,7 @@ import { type CallFileChange, fileChangeTotals } from '../../runtime/thread/file
18
18
  import { useDiffCommentsDraft } from './diff-comments-context';
19
19
  import { type DiffLayout, useFileDiffRenderer } from './diff-renderer';
20
20
  import { FileChangeSection } from './FileChangeSection';
21
+ import { FileTree } from './FileTree';
21
22
 
22
23
  /**
23
24
  * How many changed lines open on their own, file by file in order. A turn that changed a handful
@@ -51,6 +52,8 @@ export interface FileChangesViewerProps {
51
52
  changes: readonly CallFileChange[];
52
53
  open: boolean;
53
54
  onClose: () => void;
55
+ /** What stands above the files: a turn's checkpoint puts its controls here. */
56
+ header?: ReactNode;
54
57
  }
55
58
 
56
59
  /**
@@ -59,18 +62,38 @@ export interface FileChangesViewerProps {
59
62
  * every file at once. Where a composer is listening (`DiffCommentsProvider`), the lines take
60
63
  * comments that go with the next message.
61
64
  */
62
- export function FileChangesViewer({ changes, open, onClose }: FileChangesViewerProps) {
65
+ export function FileChangesViewer({ changes, open, onClose, header }: FileChangesViewerProps) {
63
66
  const { t } = useLabels();
64
67
  const styles = useStyles();
65
68
  const renderer = useFileDiffRenderer();
66
69
  const draft = useDiffCommentsDraft();
67
70
  const totals = useMemo(() => fileChangeTotals(changes), [changes]);
68
71
  const [opened, setOpened] = useState(() => initiallyOpen(changes, draft?.comments));
72
+ // Another list (a turn's, then the conversation's) opens as a first one does. Told by the
73
+ // sections' keys: the thread hands in a new array of the same changes on every render.
74
+ const listed = changes.map((change) => change.key).join('\n');
75
+ const [shown, setShown] = useState(listed);
76
+ if (shown !== listed) {
77
+ setShown(listed);
78
+ setOpened(initiallyOpen(changes, draft?.comments));
79
+ }
80
+ const sections = useRef(new Map<string, unknown>());
69
81
  const [layout, setLayout] = useState<DiffLayout>('unified');
70
82
  const [wrap, setWrap] = useState(false);
71
83
  const allOpen = changes.every((change) => opened.has(change.key));
72
84
  const canSplit = renderer?.layouts.includes('split') === true;
73
85
 
86
+ const manyFiles = totals.files > 1;
87
+ /** From the tree: that file's diffs alone, brought into view where the page can scroll to them. */
88
+ const showFile = (path: string) => {
89
+ const keys = changes.filter((change) => change.path === path).map((change) => change.key);
90
+ setOpened(new Set(keys));
91
+ const node = sections.current.get(keys[0] ?? '') as
92
+ | { scrollIntoView?: (options: { block: 'start'; behavior: 'smooth' }) => void }
93
+ | undefined;
94
+ node?.scrollIntoView?.({ block: 'start', behavior: 'smooth' });
95
+ };
96
+
74
97
  const toggle = (key: string) =>
75
98
  setOpened((current) => {
76
99
  const next = new Set(current);
@@ -91,6 +114,8 @@ export function FileChangesViewer({ changes, open, onClose }: FileChangesViewerP
91
114
  deletions: totals.deletions,
92
115
  })}
93
116
  >
117
+ {header}
118
+ {manyFiles ? <FileTree changes={changes} onSelect={showFile} /> : null}
94
119
  <View style={styles.toolbar}>
95
120
  {canSplit ? (
96
121
  <SegmentedControl
@@ -123,16 +148,23 @@ export function FileChangesViewer({ changes, open, onClose }: FileChangesViewerP
123
148
  {draft === null ? null : <Muted style={styles.hint}>{t('chat.diffComments.hint')}</Muted>}
124
149
  <View>
125
150
  {changes.map((change) => (
126
- <FileChangeSection
151
+ <View
127
152
  key={change.key}
128
- change={change}
129
- expanded={opened.has(change.key)}
130
- onToggle={() => toggle(change.key)}
131
- layout={layout}
132
- wrap={wrap}
133
- renderer={renderer}
134
- draft={draft}
135
- />
153
+ ref={(node) => {
154
+ if (node) sections.current.set(change.key, node);
155
+ else sections.current.delete(change.key);
156
+ }}
157
+ >
158
+ <FileChangeSection
159
+ change={change}
160
+ expanded={opened.has(change.key)}
161
+ onToggle={() => toggle(change.key)}
162
+ layout={layout}
163
+ wrap={wrap}
164
+ renderer={renderer}
165
+ draft={draft}
166
+ />
167
+ </View>
136
168
  ))}
137
169
  </View>
138
170
  </Dialog>
@@ -0,0 +1,75 @@
1
+ import { RiArrowDownSLine } from '@oxy.so/bloom/icons/RiArrowDownSLine';
2
+ import { RiArrowRightSLine } from '@oxy.so/bloom/icons/RiArrowRightSLine';
3
+ import { Item } from '@oxy.so/bloom/item';
4
+ import { createTokenStyles, useTheme } from '@oxy.so/bloom/theme';
5
+ import { useMemo, useState } from 'react';
6
+ import { View } from 'react-native';
7
+ import { useLabels } from '../../lib/labels';
8
+ import type { FileChange } from '../../runtime/thread/file-changes';
9
+ import { buildFileTree, fileTreeRows } from '../../runtime/thread/file-tree';
10
+ import { DiffStat } from './FileChangeSection';
11
+
12
+ /** How far each level of folders is set in. */
13
+ const INDENT = 14;
14
+
15
+ export interface FileTreeProps {
16
+ changes: readonly FileChange[];
17
+ /** A file was pressed: show its diff. */
18
+ onSelect: (path: string) => void;
19
+ }
20
+
21
+ /** The changed files as a tree: folders open and close, a file's row jumps to its diff. */
22
+ export function FileTree({ changes, onSelect }: FileTreeProps) {
23
+ const { t } = useLabels();
24
+ const { colors } = useTheme();
25
+ const styles = useStyles();
26
+ const tree = useMemo(() => buildFileTree(changes), [changes]);
27
+ const [closed, setClosed] = useState<ReadonlySet<string>>(() => new Set());
28
+ const toggle = (path: string) =>
29
+ setClosed((current) => {
30
+ const next = new Set(current);
31
+ if (!next.delete(path)) next.add(path);
32
+ return next;
33
+ });
34
+
35
+ return (
36
+ <View role="list" accessibilityLabel={t('chat.fileTree.label')} style={styles.tree}>
37
+ {fileTreeRows(tree, closed).map(({ node, depth }) => {
38
+ const folder = node.type === 'folder';
39
+ const open = folder && !closed.has(node.path);
40
+ const Chevron = open ? RiArrowDownSLine : RiArrowRightSLine;
41
+ return (
42
+ <View
43
+ key={`${node.type}:${node.path}`}
44
+ role="listitem"
45
+ style={{ paddingLeft: depth * INDENT }}
46
+ >
47
+ <Item
48
+ density="compact"
49
+ leading={
50
+ folder ? (
51
+ <Chevron size="sm" fill={colors.textSecondary} />
52
+ ) : (
53
+ <View style={styles.gap} />
54
+ )
55
+ }
56
+ title={node.name}
57
+ trailing={
58
+ folder ? null : <DiffStat additions={node.additions} deletions={node.deletions} />
59
+ }
60
+ expanded={folder ? open : undefined}
61
+ onPress={() => (folder ? toggle(node.path) : onSelect(node.path))}
62
+ accessibilityLabel={folder ? node.path : t('chat.fileTree.open', { path: node.path })}
63
+ testID={`file-tree-${node.path}`}
64
+ />
65
+ </View>
66
+ );
67
+ })}
68
+ </View>
69
+ );
70
+ }
71
+
72
+ const useStyles = createTokenStyles((t) => ({
73
+ tree: { borderBottomWidth: 1, borderColor: t.border, paddingBottom: 8, marginBottom: 8 },
74
+ gap: { width: 16 },
75
+ }));
@@ -0,0 +1,175 @@
1
+ import { Button } from '@oxy.so/bloom/button';
2
+ import {
3
+ SegmentedControl,
4
+ SegmentedControlItem,
5
+ SegmentedControlItemText,
6
+ } from '@oxy.so/bloom/segmented-control';
7
+ import { confirm } from '@oxy.so/bloom/surfaces';
8
+ import { createTokenStyles } from '@oxy.so/bloom/theme';
9
+ import { toast } from '@oxy.so/bloom/toast';
10
+ import { Muted } from '@oxy.so/bloom/typography';
11
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
12
+ import { View } from 'react-native';
13
+ import { useLabels } from '../../lib/labels';
14
+ import { useGemieRuntime } from '../../runtime/config';
15
+ import {
16
+ conversationFileChanges,
17
+ type MessageCheckpoint,
18
+ type TurnCheckpointList,
19
+ } from '../../runtime/thread/checkpoints';
20
+ import { type CallFileChange, fileChangeTotals } from '../../runtime/thread/file-changes';
21
+ import { FileChangesViewer } from './FileChangesViewer';
22
+
23
+ export interface TurnChangesViewerProps {
24
+ /** What the turn changed, as the thread stored it. */
25
+ changes: readonly CallFileChange[];
26
+ checkpoint: MessageCheckpoint & { conversationId: string };
27
+ open: boolean;
28
+ onClose: () => void;
29
+ }
30
+
31
+ /**
32
+ * A coding agent's turn that has a checkpoint (Gemies ADR 0052): its changes in the diff viewer,
33
+ * with the whole conversation's beside them and, where Gemies reverts turns, a way back to before
34
+ * this one. The turn's own diffs come from the thread; the rest is read when the viewer opens.
35
+ */
36
+ export function TurnChangesViewer({ changes, checkpoint, open, onClose }: TurnChangesViewerProps) {
37
+ const { t } = useLabels();
38
+ const styles = useStyles();
39
+ const { host } = useGemieRuntime();
40
+ const { listTurnCheckpoints, revertTurnCheckpoint } = host;
41
+ const { agentId, conversationId, checkpointId, files } = checkpoint;
42
+ const [list, setList] = useState<TurnCheckpointList>();
43
+ const [failed, setFailed] = useState(false);
44
+ const [scope, setScope] = useState<'turn' | 'conversation'>('turn');
45
+ const [reverting, setReverting] = useState(false);
46
+ const mounted = useRef(true);
47
+ useEffect(() => {
48
+ mounted.current = true;
49
+ return () => {
50
+ mounted.current = false;
51
+ };
52
+ }, []);
53
+
54
+ const load = useCallback(async () => {
55
+ if (!listTurnCheckpoints) return;
56
+ try {
57
+ const found = await listTurnCheckpoints(agentId, conversationId);
58
+ if (!mounted.current) return;
59
+ setList(found);
60
+ setFailed(false);
61
+ } catch {
62
+ if (mounted.current) setFailed(true);
63
+ }
64
+ }, [listTurnCheckpoints, agentId, conversationId]);
65
+ useEffect(() => {
66
+ void load();
67
+ }, [load]);
68
+
69
+ const whole = useMemo(() => conversationFileChanges(list?.checkpoints ?? []), [list]);
70
+ const mine = list?.checkpoints.find((c) => c.id === checkpointId);
71
+ const shown = scope === 'conversation' ? whole : changes;
72
+ const unlisted = scope === 'turn' ? files - fileChangeTotals(changes).files : 0;
73
+ const canRevert =
74
+ list?.revertAvailable === true &&
75
+ revertTurnCheckpoint !== undefined &&
76
+ mine !== undefined &&
77
+ mine.revertedAt === null &&
78
+ mine.blocked === null;
79
+
80
+ const revert = async () => {
81
+ if (!revertTurnCheckpoint) return;
82
+ const confirmed = await confirm({
83
+ title: t('chat.checkpoints.revertTitle'),
84
+ description: t('chat.checkpoints.revertDescription'),
85
+ confirmLabel: t('chat.checkpoints.revertConfirm'),
86
+ cancelLabel: t('chat.checkpoints.revertCancel'),
87
+ destructive: true,
88
+ });
89
+ if (!confirmed) return;
90
+ setReverting(true);
91
+ try {
92
+ const answer = await revertTurnCheckpoint(agentId, checkpointId);
93
+ if (answer.ok) {
94
+ toast.success(t('chat.checkpoints.revertedFiles', { count: answer.paths.length }));
95
+ } else {
96
+ toast.error(t(`chat.checkpoints.refused.${answer.reason}`));
97
+ }
98
+ } catch {
99
+ toast.error(t('chat.checkpoints.refused.offline'));
100
+ } finally {
101
+ await load();
102
+ if (mounted.current) setReverting(false);
103
+ }
104
+ };
105
+
106
+ // Why there is no way back, said only where there would otherwise be one.
107
+ const note =
108
+ mine?.revertedAt != null
109
+ ? t('chat.checkpoints.reverted')
110
+ : list?.revertAvailable === true && mine?.blocked != null
111
+ ? t(`chat.checkpoints.refused.${mine.blocked}`)
112
+ : failed
113
+ ? t('chat.checkpoints.loadFailed')
114
+ : null;
115
+
116
+ return (
117
+ <FileChangesViewer
118
+ changes={shown}
119
+ open={open}
120
+ onClose={onClose}
121
+ header={
122
+ <View style={styles.header}>
123
+ {list !== undefined && list.checkpoints.length > 1 ? (
124
+ <SegmentedControl
125
+ label={t('chat.checkpoints.scope')}
126
+ type="radio"
127
+ value={scope}
128
+ onValueChange={(next: string) =>
129
+ setScope(next === 'conversation' ? 'conversation' : 'turn')
130
+ }
131
+ >
132
+ <SegmentedControlItem value="turn">
133
+ <SegmentedControlItemText>
134
+ {t('chat.checkpoints.scopeTurn')}
135
+ </SegmentedControlItemText>
136
+ </SegmentedControlItem>
137
+ <SegmentedControlItem value="conversation">
138
+ <SegmentedControlItemText>
139
+ {t('chat.checkpoints.scopeConversation')}
140
+ </SegmentedControlItemText>
141
+ </SegmentedControlItem>
142
+ </SegmentedControl>
143
+ ) : null}
144
+ {canRevert ? (
145
+ <Button
146
+ size="sm"
147
+ appearance="outline"
148
+ tone="danger"
149
+ disabled={reverting}
150
+ onPress={() => {
151
+ void revert();
152
+ }}
153
+ >
154
+ {t('chat.checkpoints.revert')}
155
+ </Button>
156
+ ) : null}
157
+ {note === null ? null : <Muted>{note}</Muted>}
158
+ {unlisted > 0 ? (
159
+ <Muted>{t('chat.checkpoints.moreFiles', { count: unlisted })}</Muted>
160
+ ) : null}
161
+ </View>
162
+ }
163
+ />
164
+ );
165
+ }
166
+
167
+ const useStyles = createTokenStyles(() => ({
168
+ header: {
169
+ flexDirection: 'row',
170
+ flexWrap: 'wrap',
171
+ alignItems: 'center',
172
+ gap: 8,
173
+ paddingBottom: 12,
174
+ },
175
+ }));
@@ -43,6 +43,7 @@ import {
43
43
  formatElapsed,
44
44
  getToolPillLabel,
45
45
  isExternalStep,
46
+ messageCheckpoint,
46
47
  turnFileChanges,
47
48
  } from '../../runtime/model';
48
49
  import type { OpenThought } from '../../hooks/useOpenThought';
@@ -362,6 +363,8 @@ function ReplyTurn({
362
363
  });
363
364
  // The files an external agent edited this turn, whose patches its edit calls carry.
364
365
  const fileChanges = turnFileChanges(toolInvocations);
366
+ // Its checkpoint, where it is the person's own stored conversation (ADR 0052).
367
+ const checkpoint = readOnly || storedIn === undefined ? null : messageCheckpoint(toolInvocations);
365
368
  /** The template swaps the steps for the reply once the turn is done. */
366
369
  const turnWorking = isLoading && isLastReply && message.isStreaming === true;
367
370
  // What a coding agent on the person's computer did: one row, whoever's turn it is.
@@ -607,7 +610,14 @@ function ReplyTurn({
607
610
  ))}
608
611
  {fileChanges.length === 0 ? null : (
609
612
  <MessageBlockBoundary>
610
- <FileChangesCard changes={fileChanges} />
613
+ <FileChangesCard
614
+ changes={fileChanges}
615
+ checkpoint={
616
+ checkpoint === null || storedIn === undefined
617
+ ? undefined
618
+ : { ...checkpoint, conversationId: storedIn }
619
+ }
620
+ />
611
621
  </MessageBlockBoundary>
612
622
  )}
613
623
  {gemieConversations.map(({ key, conversation }) => (
@@ -84,6 +84,38 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
84
84
  'chat.dislike': 'Dislike',
85
85
  'chat.edit': 'Edit',
86
86
  'chat.feedbackFailed': "Your feedback couldn't be saved.",
87
+ 'chat.checkpoints.loadFailed': 'Could not load the changes of this conversation',
88
+ 'chat.checkpoints.moreFiles': {
89
+ one: '1 more file is not listed',
90
+ other: '{{count}} more files are not listed',
91
+ },
92
+ 'chat.checkpoints.refused.already_reverted': 'This turn was already reverted',
93
+ 'chat.checkpoints.refused.busy': 'The agent is working in that folder. Try when it finishes',
94
+ 'chat.checkpoints.refused.conflict': 'Some of these files changed since. Nothing was reverted',
95
+ 'chat.checkpoints.refused.failed': 'The revert did not finish. Check the files in the folder',
96
+ 'chat.checkpoints.refused.folder': 'This computer no longer allows that folder',
97
+ 'chat.checkpoints.refused.head_moved':
98
+ 'The branch moved since this turn (a commit or a switch), so it cannot be reverted',
99
+ 'chat.checkpoints.refused.ignore_rules_changed':
100
+ 'This turn changed .gitignore, so it cannot be reverted safely',
101
+ 'chat.checkpoints.refused.missing': 'That computer no longer has this checkpoint',
102
+ 'chat.checkpoints.refused.offline': 'The computer is not connected. Nothing was reverted',
103
+ 'chat.checkpoints.refused.session_not_rewindable':
104
+ 'This session was started in a terminal, and its conversation cannot be taken back',
105
+ 'chat.checkpoints.refused.shared_checkout':
106
+ 'Another agent was writing in the same folder, so these changes cannot be told apart',
107
+ 'chat.checkpoints.refused.unsupported': 'A nested repository changed, which cannot be reverted',
108
+ 'chat.checkpoints.revert': 'Revert to before this turn',
109
+ 'chat.checkpoints.revertCancel': 'Cancel',
110
+ 'chat.checkpoints.revertConfirm': 'Revert',
111
+ 'chat.checkpoints.revertDescription':
112
+ 'Files changed by this turn and any later one go back to how they were before it. The agent starts a new session. Your branch and commits are not touched.',
113
+ 'chat.checkpoints.revertTitle': 'Revert these changes?',
114
+ 'chat.checkpoints.reverted': 'This turn was reverted',
115
+ 'chat.checkpoints.revertedFiles': { one: '1 file restored', other: '{{count}} files restored' },
116
+ 'chat.checkpoints.scope': 'Changes shown',
117
+ 'chat.checkpoints.scopeConversation': 'Whole conversation',
118
+ 'chat.checkpoints.scopeTurn': 'This turn',
87
119
  'chat.diffComments.add': 'Add to message',
88
120
  'chat.diffComments.cancel': 'Cancel',
89
121
  'chat.diffComments.chip': '{{file}}, {{lines}}',
@@ -127,6 +159,8 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
127
159
  'chat.fileChanges.unified': 'Unified',
128
160
  'chat.fileChanges.unrecorded': 'The agent did not record what changed in this file',
129
161
  'chat.fileChanges.wrap': 'Wrap lines',
162
+ 'chat.fileTree.label': 'Changed files',
163
+ 'chat.fileTree.open': 'Show the changes to {{path}}',
130
164
  'chat.find.count': '{{current}} of {{total}}',
131
165
  'chat.find.loadedOnly': 'Only the messages loaded here are searched.',
132
166
  'chat.find.newer': 'Next match',
@@ -80,6 +80,43 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
80
80
  'chat.dislike': 'No me gusta',
81
81
  'chat.edit': 'Editar',
82
82
  'chat.feedbackFailed': 'No se ha podido guardar tu opinión.',
83
+ 'chat.checkpoints.loadFailed': 'No se pudieron cargar los cambios de esta conversación',
84
+ 'chat.checkpoints.moreFiles': {
85
+ one: 'Hay 1 archivo más sin listar',
86
+ other: 'Hay {{count}} archivos más sin listar',
87
+ },
88
+ 'chat.checkpoints.refused.already_reverted': 'Este turno ya se revirtió',
89
+ 'chat.checkpoints.refused.busy':
90
+ 'El agente está trabajando en esa carpeta. Prueba cuando termine',
91
+ 'chat.checkpoints.refused.conflict':
92
+ 'Algunos de estos archivos han cambiado desde entonces. No se revirtió nada',
93
+ 'chat.checkpoints.refused.failed': 'La reversión no terminó. Revisa los archivos de la carpeta',
94
+ 'chat.checkpoints.refused.folder': 'Este equipo ya no permite esa carpeta',
95
+ 'chat.checkpoints.refused.head_moved':
96
+ 'La rama se movió desde este turno (un commit o un cambio de rama), así que no se puede revertir',
97
+ 'chat.checkpoints.refused.ignore_rules_changed':
98
+ 'Este turno cambió .gitignore, así que no se puede revertir con seguridad',
99
+ 'chat.checkpoints.refused.missing': 'Ese equipo ya no tiene este punto de control',
100
+ 'chat.checkpoints.refused.offline': 'El equipo no está conectado. No se revirtió nada',
101
+ 'chat.checkpoints.refused.session_not_rewindable':
102
+ 'Esta sesión empezó en una terminal y su conversación no se puede deshacer',
103
+ 'chat.checkpoints.refused.shared_checkout':
104
+ 'Otro agente escribía en la misma carpeta, así que estos cambios no se pueden separar',
105
+ 'chat.checkpoints.refused.unsupported': 'Cambió un repositorio anidado, que no se puede revertir',
106
+ 'chat.checkpoints.revert': 'Volver a antes de este turno',
107
+ 'chat.checkpoints.revertCancel': 'Cancelar',
108
+ 'chat.checkpoints.revertConfirm': 'Revertir',
109
+ 'chat.checkpoints.revertDescription':
110
+ 'Los archivos que cambiaron este turno y los siguientes vuelven a como estaban antes. El agente empieza una sesión nueva. Tu rama y tus commits no se tocan.',
111
+ 'chat.checkpoints.revertTitle': '¿Revertir estos cambios?',
112
+ 'chat.checkpoints.reverted': 'Este turno se revirtió',
113
+ 'chat.checkpoints.revertedFiles': {
114
+ one: '1 archivo restaurado',
115
+ other: '{{count}} archivos restaurados',
116
+ },
117
+ 'chat.checkpoints.scope': 'Cambios mostrados',
118
+ 'chat.checkpoints.scopeConversation': 'Toda la conversación',
119
+ 'chat.checkpoints.scopeTurn': 'Este turno',
83
120
  'chat.diffComments.add': 'Añadir al mensaje',
84
121
  'chat.diffComments.cancel': 'Cancelar',
85
122
  'chat.diffComments.chip': '{{file}}, {{lines}}',
@@ -126,6 +163,8 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
126
163
  'chat.fileChanges.unified': 'Unificada',
127
164
  'chat.fileChanges.unrecorded': 'El agente no registró qué cambió en este archivo',
128
165
  'chat.fileChanges.wrap': 'Ajustar líneas',
166
+ 'chat.fileTree.label': 'Archivos modificados',
167
+ 'chat.fileTree.open': 'Ver los cambios de {{path}}',
129
168
  'chat.find.count': '{{current}} de {{total}}',
130
169
  'chat.find.loadedOnly': 'Solo se busca en los mensajes cargados aquí.',
131
170
  'chat.find.newer': 'Coincidencia siguiente',
@@ -1,6 +1,7 @@
1
1
  import { createContext, type ReactNode, useContext, useMemo } from 'react';
2
2
  import { GEMIES_API_URL } from '../lib/origins';
3
3
  import type { ApprovalDecision, ApprovalDetails, ApprovalGrant } from './approvals';
4
+ import type { TurnCheckpointList, TurnRevertAnswer } from './thread/checkpoints';
4
5
  import type { AgentRun } from './types';
5
6
  import { GemieRealtimeProvider } from '../realtime/react';
6
7
 
@@ -142,6 +143,17 @@ export interface GemieRuntimeHost {
142
143
  listApprovalGrants?(agentId: string, conversationId: string): Promise<readonly ApprovalGrant[]>;
143
144
  /** Takes one allowance back: the next such question is asked again. */
144
145
  revokeApprovalGrant?(agentId: string, grantId: string): Promise<void>;
146
+ /**
147
+ * A coding agent's checkpoints in a conversation: what each write turn changed, for the "whole
148
+ * conversation" view of its changes. Omitted, a turn's changes are shown from the thread alone.
149
+ */
150
+ listTurnCheckpoints?(agentId: string, conversationId: string): Promise<TurnCheckpointList>;
151
+ /**
152
+ * Puts the agent's folder back to how it was before a turn, the later ones with it. Offered only
153
+ * where Gemies says reverting is available. Answers why when it is refused; throws when the
154
+ * request itself failed.
155
+ */
156
+ revertTurnCheckpoint?(agentId: string, checkpointId: string): Promise<TurnRevertAnswer>;
145
157
  /** The agent's row in the host's list, ahead of the server: your line, then her answer. */
146
158
  onTurnPreview?: (agentId: string | null | undefined, text: string) => void;
147
159
  /**
@@ -15,6 +15,13 @@
15
15
 
16
16
  export { GemieRuntimeProvider, useGemieRuntime } from './config';
17
17
  export { ApprovalExpiredError } from './approvals';
18
+ export { turnRevertRefusalOf } from './thread/checkpoints';
19
+ export type {
20
+ TurnCheckpoint,
21
+ TurnCheckpointList,
22
+ TurnRevertAnswer,
23
+ TurnRevertRefusal,
24
+ } from './thread/checkpoints';
18
25
  export type {
19
26
  ApprovalDecision,
20
27
  ApprovalDetails,
@@ -15,6 +15,7 @@ export type { Translate } from '../lib/copy';
15
15
  export * from './thread/agent-activity';
16
16
  export * from './thread/agent-work';
17
17
  export * from './thread/automation-labels';
18
+ export * from './thread/checkpoints';
18
19
  export * from './thread/command-output';
19
20
  export * from './thread/conversation-export';
20
21
  export * from './thread/diff-comments';
@@ -38,5 +39,5 @@ export type {
38
39
  SendOptions,
39
40
  ToolInvocation,
40
41
  } from './types';
41
- export { UsageLimitError } from './usage-limit-error';
42
+ export { PROVIDER_USAGE_LIMIT_TYPE, UsageLimitError } from './usage-limit-error';
42
43
  export type { UsageLimitDetails, UsageLimitType } from './usage-limit-error';
@@ -1,6 +1,6 @@
1
1
  import { toolCallStatus } from '../../lib/tool-call-status';
2
2
  import type { ToolInvocation } from '../types';
3
- import { type CallFileChange, fileChangesOf } from './file-changes';
3
+ import { type CallFileChange, fileChangesOf, isCheckpointCall } from './file-changes';
4
4
 
5
5
  /**
6
6
  * What a coding agent did in a turn, as one work log: the tool calls of an external agent
@@ -151,7 +151,10 @@ export function buildAgentWork(
151
151
  calls: readonly ToolInvocation[] | undefined,
152
152
  live: boolean,
153
153
  ): AgentWork | null {
154
- const steps = (calls ?? []).filter(isExternalStep).map((call) => agentStepOf(call, live));
154
+ // A turn's checkpoint is not something the agent did: the thread draws it as the turn's changes.
155
+ const steps = (calls ?? [])
156
+ .filter((call) => isExternalStep(call) && !isCheckpointCall(call))
157
+ .map((call) => agentStepOf(call, live));
155
158
  if (steps.length === 0) return null;
156
159
  const first = steps.find((step) => step.startedAt !== undefined);
157
160
  const ends = steps.flatMap((step) =>
@@ -0,0 +1,79 @@
1
+ /**
2
+ * A coding agent's per-turn checkpoints (Gemies ADR 0052): the shapes the host reads from Gemies
3
+ * and the pure reading of what a conversation stored.
4
+ */
5
+ import type { ToolInvocation } from '../types';
6
+ import { type CallFileChange, fileChangesFrom, isCheckpointCall } from './file-changes';
7
+
8
+ /** Why going back to before a turn is refused. `offline`: the computer could not be asked. */
9
+ export const TURN_REVERT_REFUSALS = [
10
+ 'busy',
11
+ 'conflict',
12
+ 'head_moved',
13
+ 'ignore_rules_changed',
14
+ 'session_not_rewindable',
15
+ 'shared_checkout',
16
+ 'missing',
17
+ 'unsupported',
18
+ 'folder',
19
+ 'failed',
20
+ 'already_reverted',
21
+ 'offline',
22
+ ] as const;
23
+ export type TurnRevertRefusal = (typeof TURN_REVERT_REFUSALS)[number];
24
+
25
+ /** One turn's checkpoint, as `GET /agents/external/:agentId/checkpoints` answers it. */
26
+ export interface TurnCheckpoint {
27
+ readonly id: string;
28
+ readonly createdAt: string;
29
+ readonly revertedAt: string | null;
30
+ /** How many files the turn changed; `changes` may list fewer. */
31
+ readonly files: number;
32
+ /** The server's file changes, read with `checkpointChanges`. */
33
+ readonly changes: unknown;
34
+ readonly blocked: TurnRevertRefusal | null;
35
+ }
36
+
37
+ export interface TurnCheckpointList {
38
+ /** Whether this Gemies reverts turns at all; the diffs are shown either way. */
39
+ readonly revertAvailable: boolean;
40
+ /** Oldest first. */
41
+ readonly checkpoints: readonly TurnCheckpoint[];
42
+ }
43
+
44
+ export type TurnRevertAnswer =
45
+ | { readonly ok: true; readonly paths: readonly string[] }
46
+ | { readonly ok: false; readonly reason: TurnRevertRefusal };
47
+
48
+ /** The checkpoint a stored turn names. */
49
+ export interface MessageCheckpoint {
50
+ readonly checkpointId: string;
51
+ readonly agentId: string;
52
+ /** How many files the turn changed. */
53
+ readonly files: number;
54
+ }
55
+
56
+ /** A refusal in words the app has; one it does not know is a failure. */
57
+ export function turnRevertRefusalOf(reason: unknown): TurnRevertRefusal {
58
+ return (TURN_REVERT_REFUSALS as readonly unknown[]).includes(reason)
59
+ ? (reason as TurnRevertRefusal)
60
+ : 'failed';
61
+ }
62
+
63
+ export function messageCheckpoint(calls: readonly ToolInvocation[]): MessageCheckpoint | null {
64
+ const call = calls.filter(isCheckpointCall).at(-1);
65
+ if (call?.state !== 'result') return null;
66
+ const result = call.result as Record<string, unknown> | undefined;
67
+ const { checkpointId, agentId, files } = result ?? {};
68
+ if (typeof checkpointId !== 'string' || typeof agentId !== 'string') return null;
69
+ return { checkpointId, agentId, files: typeof files === 'number' ? files : 0 };
70
+ }
71
+
72
+ export function checkpointChanges(checkpoint: TurnCheckpoint): CallFileChange[] {
73
+ return fileChangesFrom(checkpoint.changes, checkpoint.id);
74
+ }
75
+
76
+ /** What the conversation's turns still change, turn by turn: reverted ones are left out. */
77
+ export function conversationFileChanges(checkpoints: readonly TurnCheckpoint[]): CallFileChange[] {
78
+ return checkpoints.filter((c) => c.revertedAt === null).flatMap(checkpointChanges);
79
+ }
@@ -63,20 +63,39 @@ function fileChange(value: unknown): FileChange | null {
63
63
  };
64
64
  }
65
65
 
66
- /** The files a finished call changed, in the order it reported them; none for any other call. */
67
- export function fileChangesOf(call: ToolInvocation): CallFileChange[] {
68
- if (call.state !== 'result') return [];
69
- const changes = (call.result as { changes?: unknown } | undefined)?.changes;
66
+ /** A list of changes as the server sent it, each keyed under `key`; none for anything else. */
67
+ export function fileChangesFrom(changes: unknown, key: string): CallFileChange[] {
70
68
  if (!Array.isArray(changes)) return [];
71
69
  return changes.flatMap((entry, index) => {
72
70
  const change = fileChange(entry);
73
- return change === null ? [] : [{ ...change, key: `${call.toolCallId}:${index}` }];
71
+ return change === null ? [] : [{ ...change, key: `${key}:${index}` }];
74
72
  });
75
73
  }
76
74
 
77
- /** Every file the calls of a turn changed, call by call. */
75
+ /** The files a finished call changed, in the order it reported them; none for any other call. */
76
+ export function fileChangesOf(call: ToolInvocation): CallFileChange[] {
77
+ if (call.state !== 'result') return [];
78
+ const changes = (call.result as { changes?: unknown } | undefined)?.changes;
79
+ return fileChangesFrom(changes, call.toolCallId);
80
+ }
81
+
82
+ /**
83
+ * The step a turn's checkpoint is stored as (the API's `external_turn_checkpoints`): what the whole
84
+ * turn changed, whatever made the change.
85
+ */
86
+ export const CHECKPOINT_STEP_PREFIX = 'ext_checkpoint_';
87
+
88
+ export function isCheckpointCall(call: Pick<ToolInvocation, 'toolCallId'>): boolean {
89
+ return call.toolCallId.startsWith(CHECKPOINT_STEP_PREFIX);
90
+ }
91
+
92
+ /**
93
+ * Every file a turn changed. A turn with a checkpoint says it with that, once; its edit calls would
94
+ * name the same files again. Otherwise the calls say it, call by call.
95
+ */
78
96
  export function turnFileChanges(calls: readonly ToolInvocation[]): CallFileChange[] {
79
- return calls.flatMap(fileChangesOf);
97
+ const checkpoints = calls.filter(isCheckpointCall);
98
+ return (checkpoints.length > 0 ? checkpoints : calls).flatMap(fileChangesOf);
80
99
  }
81
100
 
82
101
  /** What "N files changed +X −Y" says of a list of changes. */
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The changed files of a turn or a conversation as folders and files. Pure.
3
+ */
4
+ import type { FileChange, FileChangeOperation } from './file-changes';
5
+
6
+ export interface FileTreeFile {
7
+ readonly type: 'file';
8
+ readonly name: string;
9
+ readonly path: string;
10
+ /** What happened to it last. */
11
+ readonly operation: FileChangeOperation;
12
+ readonly additions: number;
13
+ readonly deletions: number;
14
+ }
15
+
16
+ export interface FileTreeFolder {
17
+ readonly type: 'folder';
18
+ /** One folder, or a chain that holds nothing else (`src/lib/chat`). */
19
+ readonly name: string;
20
+ readonly path: string;
21
+ readonly children: readonly FileTreeNode[];
22
+ }
23
+
24
+ export type FileTreeNode = FileTreeFolder | FileTreeFile;
25
+
26
+ export interface FileTreeRow {
27
+ readonly node: FileTreeNode;
28
+ readonly depth: number;
29
+ }
30
+
31
+ interface Folder {
32
+ folders: Map<string, Folder>;
33
+ files: Map<string, FileTreeFile>;
34
+ }
35
+
36
+ const empty = (): Folder => ({ folders: new Map(), files: new Map() });
37
+
38
+ const byName = (a: { name: string }, b: { name: string }) => a.name.localeCompare(b.name);
39
+
40
+ function nodesOf(folder: Folder, prefix: string): FileTreeNode[] {
41
+ const folders: FileTreeFolder[] = [...folder.folders].map(([first, found]) => {
42
+ let name = first;
43
+ let inner = found;
44
+ // A folder that holds only one folder reads better as one row.
45
+ while (inner.files.size === 0 && inner.folders.size === 1) {
46
+ const [next, child] = [...inner.folders][0] as [string, Folder];
47
+ name = `${name}/${next}`;
48
+ inner = child;
49
+ }
50
+ const path = `${prefix}${name}`;
51
+ return { type: 'folder', name, path, children: nodesOf(inner, `${path}/`) };
52
+ });
53
+ return [...folders.sort(byName), ...[...folder.files.values()].sort(byName)];
54
+ }
55
+
56
+ /** Folders first, then files, each by name. A file changed twice is one file with both counted. */
57
+ export function buildFileTree(changes: readonly FileChange[]): FileTreeNode[] {
58
+ const root = empty();
59
+ for (const change of changes) {
60
+ const parts = change.path.split('/').filter((part) => part !== '');
61
+ const name = parts.pop();
62
+ if (name === undefined) continue;
63
+ let folder = root;
64
+ for (const part of parts) {
65
+ const next = folder.folders.get(part) ?? empty();
66
+ folder.folders.set(part, next);
67
+ folder = next;
68
+ }
69
+ const before = folder.files.get(name);
70
+ folder.files.set(name, {
71
+ type: 'file',
72
+ name,
73
+ path: change.path,
74
+ operation: change.operation,
75
+ additions: (before?.additions ?? 0) + change.additions,
76
+ deletions: (before?.deletions ?? 0) + change.deletions,
77
+ });
78
+ }
79
+ return nodesOf(root, '');
80
+ }
81
+
82
+ /** The rows to draw: every node whose folders are all open. */
83
+ export function fileTreeRows(
84
+ nodes: readonly FileTreeNode[],
85
+ closed: ReadonlySet<string>,
86
+ depth = 0,
87
+ ): FileTreeRow[] {
88
+ return nodes.flatMap((node) => [
89
+ { node, depth },
90
+ ...(node.type === 'folder' && !closed.has(node.path)
91
+ ? fileTreeRows(node.children, closed, depth + 1)
92
+ : []),
93
+ ]);
94
+ }
@@ -11,6 +11,23 @@ export interface UsageLimitDetails {
11
11
  current?: number;
12
12
  limit?: number;
13
13
  tier?: string;
14
+ /** When the limit resets, ISO 8601, when the server knows. */
15
+ resetsAt?: string;
16
+ /** The server keeps the message and answers it by itself once the limit resets. */
17
+ autoResume?: boolean;
18
+ }
19
+
20
+ /** `details.limitType` of a usage limit of the model's provider, not of the person's plan. */
21
+ export const PROVIDER_USAGE_LIMIT_TYPE = 'provider_usage';
22
+
23
+ /** The two fields a refusal says about its reset, read off whatever carried them. */
24
+ export function usageResetOf(
25
+ error: { resetsAt?: unknown; autoResume?: unknown } | null | undefined,
26
+ ): Pick<UsageLimitDetails, 'resetsAt' | 'autoResume'> {
27
+ return {
28
+ ...(typeof error?.resetsAt === 'string' ? { resetsAt: error.resetsAt } : {}),
29
+ ...(error?.autoResume === true ? { autoResume: true } : {}),
30
+ };
14
31
  }
15
32
 
16
33
  export class UsageLimitError extends Error {
@@ -49,7 +49,7 @@ import {
49
49
  import { hasUsableStreamOutput, type StreamOutputEvidence } from './stream-outcome';
50
50
  import { failureDetail, readGemieMeta, traceIdOf, type FailedTurn } from './turn-failure';
51
51
  import type { AgentRun, Message, SendOptions, ToolInvocation } from './types';
52
- import { UsageLimitError } from './usage-limit-error';
52
+ import { PROVIDER_USAGE_LIMIT_TYPE, UsageLimitError, usageResetOf } from './usage-limit-error';
53
53
  import { useGemieRealtime } from '../realtime/react';
54
54
 
55
55
  export type { ToolInvocation };
@@ -66,7 +66,8 @@ export type { FailedTurn };
66
66
  * - `failed`: the turn was rolled back to what the list was before the send,
67
67
  * so the caller hands the text back to the composer. Only the usage-limit
68
68
  * errors end this way now: they open a dialog of their own, and a retry
69
- * would be the wrong offer next to "upgrade" or "wait".
69
+ * would be the wrong offer next to "upgrade" or "wait". A limit the server
70
+ * will answer after by itself (`autoResume`) is `sent` instead.
70
71
  * - `aborted`: the person stopped it; partial output is theirs to keep.
71
72
  */
72
73
  export type SendOutcome = 'sent' | 'errored' | 'failed' | 'aborted';
@@ -80,6 +81,8 @@ interface ThrownErrorBody {
80
81
  /** Alia's run id, on a turn that failed after the stream began. */
81
82
  reference?: string;
82
83
  suggestedAction?: 'wait' | 'upgrade';
84
+ resetsAt?: string;
85
+ autoResume?: boolean;
83
86
  }
84
87
 
85
88
  /** Structured `error` object the server may embed in a non-OK response / SSE error event. */
@@ -94,6 +97,9 @@ interface StreamErrorObject {
94
97
  reference?: string;
95
98
  /** The id of the request that produced this error, a refusal's included. */
96
99
  traceId?: string;
100
+ /** A usage limit's reset time, and whether the server answers the message then. */
101
+ resetsAt?: string;
102
+ autoResume?: boolean;
97
103
  details?: {
98
104
  limitType?: string;
99
105
  current?: number;
@@ -488,6 +494,18 @@ export function useConversationStream({
488
494
  return 'sent';
489
495
  };
490
496
 
497
+ /**
498
+ * A usage limit's end. When the server keeps the message and answers it after the reset,
499
+ * the person's turn stays in the thread; handing it back to the composer would send it twice.
500
+ */
501
+ const settleUsageLimit = (error: unknown): SendOutcome => {
502
+ const autoResume = (error as Partial<UsageLimitError>).details?.autoResume === true;
503
+ if (!autoResume || hasUsableStreamOutput(outputEvidence)) return settleError();
504
+ dropPendingUpdates();
505
+ setMessagesAndRef((prev) => prev.filter((m) => m.id !== assistantMessage.id));
506
+ return 'sent';
507
+ };
508
+
491
509
  /**
492
510
  * The server's stand-in for an answer it could not get, if one arrived.
493
511
  *
@@ -868,14 +886,21 @@ export function useConversationStream({
868
886
  return rollback();
869
887
  }
870
888
 
871
- // Detect usage limit errors (429 rate limit, 402 insufficient credits, 403 model access)
872
- if (response.status === 429 || response.status === 402 || response.status === 403) {
873
- const errObj =
874
- errorData?.error && typeof errorData.error === 'object' ? errorData.error : null;
889
+ // Detect usage limit errors (429 rate limit, 402 insufficient credits, 403 model access,
890
+ // and a provider's limit, which fails the turn with 503 and says when it resets)
891
+ const errObj =
892
+ errorData?.error && typeof errorData.error === 'object' ? errorData.error : null;
893
+ const providerLimit = errObj?.details?.limitType === PROVIDER_USAGE_LIMIT_TYPE;
894
+ if (
895
+ providerLimit ||
896
+ response.status === 429 ||
897
+ response.status === 402 ||
898
+ response.status === 403
899
+ ) {
875
900
  const isModelAccess = response.status === 403 && errObj?.code === 'MODEL_NOT_IN_PLAN';
876
901
  const isCredits = response.status === 402 || errObj?.code === 'INSUFFICIENT_CREDITS';
877
902
 
878
- if (isModelAccess || isCredits || response.status === 429) {
903
+ if (providerLimit || isModelAccess || isCredits || response.status === 429) {
879
904
  throw new UsageLimitError({
880
905
  type: isModelAccess ? 'model_access' : isCredits ? 'credits' : 'rate_limit',
881
906
  code:
@@ -900,6 +925,7 @@ export function useConversationStream({
900
925
  current: errObj?.details?.current,
901
926
  limit: errObj?.details?.limit,
902
927
  tier: errObj?.details?.tier,
928
+ ...usageResetOf(errObj),
903
929
  });
904
930
  }
905
931
  }
@@ -1312,13 +1338,15 @@ export function useConversationStream({
1312
1338
  host.onFeatureLocked?.(lockedFeature);
1313
1339
  return settleError();
1314
1340
  }
1315
- // Check for usage limit errors (rate limit, credits, model access)
1341
+ // Check for usage limit errors (rate limit, credits, model access, a provider's)
1342
+ const providerLimit = err.details?.limitType === PROVIDER_USAGE_LIMIT_TYPE;
1316
1343
  if (
1344
+ providerLimit ||
1317
1345
  errorCode(err) === 'MODEL_NOT_IN_PLAN' ||
1318
1346
  errorCode(err) === 'INSUFFICIENT_CREDITS' ||
1319
1347
  err.type === 'rate_limit_error'
1320
1348
  ) {
1321
- const isRateLimit = err.type === 'rate_limit_error';
1349
+ const isRateLimit = providerLimit || err.type === 'rate_limit_error';
1322
1350
  throw new UsageLimitError({
1323
1351
  type:
1324
1352
  errorCode(err) === 'MODEL_NOT_IN_PLAN'
@@ -1345,6 +1373,7 @@ export function useConversationStream({
1345
1373
  current:
1346
1374
  typeof err.details?.current === 'number' ? err.details.current : undefined,
1347
1375
  limit: typeof err.details?.limit === 'number' ? err.details.limit : undefined,
1376
+ ...usageResetOf(err),
1348
1377
  });
1349
1378
  }
1350
1379
 
@@ -1575,7 +1604,7 @@ export function useConversationStream({
1575
1604
  if (e instanceof UsageLimitError || errorName(e) === 'UsageLimitError') {
1576
1605
  setError(e instanceof Error ? e : new Error(getErrorMessage(e)));
1577
1606
  setComposerPhase('error');
1578
- return settleError();
1607
+ return settleUsageLimit(e);
1579
1608
  }
1580
1609
 
1581
1610
  // A streaming fetch may throw a non-Error object (e.g. the response body)
@@ -1605,10 +1634,11 @@ export function useConversationStream({
1605
1634
  retryable: errBody?.retryable ?? !isCredits,
1606
1635
  retryAfterSeconds: errBody?.retryAfter,
1607
1636
  suggestedAction: errBody?.suggestedAction || (isCredits ? 'upgrade' : 'wait'),
1637
+ ...usageResetOf(errBody),
1608
1638
  });
1609
1639
  setError(usageError);
1610
1640
  setComposerPhase('error');
1611
- return settleError();
1641
+ return settleUsageLimit(usageError);
1612
1642
  }
1613
1643
  }
1614
1644