@gemies/sdk 10.1.0 → 10.2.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,26 @@
1
1
  # @gemies/sdk
2
2
 
3
+ ## 10.2.0
4
+
5
+ ### The files an agent changed, as a diff
6
+
7
+ A turn in which an external agent (Claude Code, Codex, OpenCode) edited files now ends with a
8
+ "N files changed +X −Y" chip under it, and the chip opens a viewer: one section per file with its
9
+ `+`/`−` counts, folding on its own and all at once, copying its path, with a choice of unified or
10
+ split layout where the host's renderer has both, and line wrapping. The patches come from the edit
11
+ call's tool result (`changes`, one standard `diff --git` patch per file, made by the server from
12
+ whatever each CLI recorded). A file with no patch says why: binary, too large to keep, or never
13
+ recorded by the agent.
14
+
15
+ The SDK draws a patch itself, as numbered monospace lines with the added and removed ones tinted,
16
+ on every platform, a page of 400 lines at a time. A host that wants more passes `fileDiffRenderer`
17
+ to `GemieChatContent` (`{ PatchView, layouts }`, typed `GemieFileDiffRenderer`): the Gemies web app
18
+ brings `@pierre/diffs`, with syntax highlighting in a worker pool and a split layout, which the SDK
19
+ does not depend on. `PatchLines` is exported as the fallback for a host's own renderer while it loads.
20
+
21
+ `@gemies/sdk/model` carries the data side: `fileChangesOf`, `turnFileChanges`, `fileChangeTotals`
22
+ and `patchLines`.
23
+
3
24
  ## 10.1.0
4
25
 
5
26
  ### `@gemies/sdk/ask/lean`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gemies/sdk",
3
- "version": "10.1.0",
3
+ "version": "10.2.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",
@@ -1,3 +1,4 @@
1
+ import { useConversationActionApprovals } from '../runtime/action-approvals';
1
2
  /**
2
3
  * The conversation: header, thread and composer, with its voice call. The one screen of the
3
4
  * bottom sheet, `GemieChatScreen` and the Alia app — they are frames around this.
@@ -61,6 +62,7 @@ import {
61
62
  } from '../lib/participants';
62
63
  import { type GemieToolRenderers, GemieToolRenderersProvider } from '../lib/tool-renderers';
63
64
  import { type GemieChartCards, GemieChartCardsProvider } from './charts/chart-cards';
65
+ import { type GemieFileDiffRenderer, GemieFileDiffRendererProvider } from './diff/diff-renderer';
64
66
  import { KeyboardSafeAreaFloor } from '../lib/keyboard';
65
67
  import { type GemieChatLabels, GemieChatLabelsProvider, useLabels } from '../lib/labels';
66
68
  import { type DeviceModel, buildPowerLevelOptions } from '../lib/power-level-options';
@@ -187,6 +189,11 @@ export interface GemieChatContentProps {
187
189
  * `@gemies/sdk/ask/lean` comes without them, so a host on it passes its own here.
188
190
  */
189
191
  chartCards?: GemieChartCards;
192
+ /**
193
+ * How the patch of a file an agent changed is drawn, over the SDK's plain lines. The app brings
194
+ * syntax highlighting and a split layout on the web; the SDK depends on neither.
195
+ */
196
+ fileDiffRenderer?: GemieFileDiffRenderer;
190
197
  /**
191
198
  * The lead's feature gate refused something (`attachments.documents`…): the host shows its own
192
199
  * upsell. Also called for a locked row of the attach menu.
@@ -323,6 +330,7 @@ type ConversationViewProps = Omit<
323
330
  | 'apiUrl'
324
331
  | 'toolRenderers'
325
332
  | 'chartCards'
333
+ | 'fileDiffRenderer'
326
334
  | 'onFeatureLocked'
327
335
  > & { conversationId: string | undefined };
328
336
 
@@ -545,6 +553,11 @@ function GemieConversationView({
545
553
 
546
554
  // ── The ambient wave — one persistent overlay across idle, voice, read-aloud and dictation ──
547
555
  const tts = useTTS({ apiUrl: runtime.apiUrl, ...runtime.speech });
556
+ const actionApprovals = useConversationActionApprovals(
557
+ isAuthenticated ? user?.id : undefined,
558
+ conversationId,
559
+ isLoading,
560
+ );
548
561
  const { state: voiceState } = voice;
549
562
  const wave = useAmbientWave({
550
563
  voice: voiceState
@@ -823,6 +836,7 @@ function GemieConversationView({
823
836
  onStartEdit={edit.start}
824
837
  newConversationOffer={newConversationOffer}
825
838
  approvals={approvalCards}
839
+ actionApprovals={showsPast ? undefined : actionApprovals}
826
840
  agentActivity={agentRun === null ? null : agentActivity}
827
841
  call={voice.isActive ? { agentState: voice.agentState } : undefined}
828
842
  empty={welcome}
@@ -871,6 +885,7 @@ export function GemieChatContent({
871
885
  app,
872
886
  toolRenderers,
873
887
  chartCards,
888
+ fileDiffRenderer,
874
889
  onFeatureLocked,
875
890
  ...props
876
891
  }: GemieChatContentProps) {
@@ -914,13 +929,15 @@ export function GemieChatContent({
914
929
  <GemieChatLabelsProvider labels={labels}>
915
930
  <GemieRuntimeProvider apiUrl={apiUrl ?? parent.apiUrl} host={host} app={chatApp}>
916
931
  <GemieToolRenderersProvider value={toolRenderers ?? NO_RENDERERS}>
917
- {chartCards === undefined ? (
918
- <GemieConversationView {...props} conversationId={controlledId ?? ownId} />
919
- ) : (
920
- <GemieChartCardsProvider value={chartCards}>
932
+ <GemieFileDiffRendererProvider value={fileDiffRenderer ?? null}>
933
+ {chartCards === undefined ? (
921
934
  <GemieConversationView {...props} conversationId={controlledId ?? ownId} />
922
- </GemieChartCardsProvider>
923
- )}
935
+ ) : (
936
+ <GemieChartCardsProvider value={chartCards}>
937
+ <GemieConversationView {...props} conversationId={controlledId ?? ownId} />
938
+ </GemieChartCardsProvider>
939
+ )}
940
+ </GemieFileDiffRendererProvider>
924
941
  </GemieToolRenderersProvider>
925
942
  </GemieRuntimeProvider>
926
943
  </GemieChatLabelsProvider>
@@ -0,0 +1,172 @@
1
+ import { Button } from '@oxy.so/bloom/button';
2
+ import { RiArrowDownSLine } from '@oxy.so/bloom/icons/RiArrowDownSLine';
3
+ import { RiArrowRightSLine } from '@oxy.so/bloom/icons/RiArrowRightSLine';
4
+ import { RiFileCopyLine } from '@oxy.so/bloom/icons/RiFileCopyLine';
5
+ import { Item } from '@oxy.so/bloom/item';
6
+ import { createTokenStyles, useTheme } from '@oxy.so/bloom/theme';
7
+ import { Muted, Text } from '@oxy.so/bloom/typography';
8
+ import { View } from 'react-native';
9
+ import { copyText } from '../../lib/clipboard';
10
+ import { useLabels } from '../../lib/labels';
11
+ import { type CallFileChange, patchLines } from '../../runtime/thread/file-changes';
12
+ import type { DiffLayout, GemieFileDiffRenderer } from './diff-renderer';
13
+ import { PatchLines } from './PatchLines';
14
+
15
+ const MARK = { add: 'A', update: 'M', delete: 'D', rename: 'R' } as const;
16
+
17
+ /** `+12 −3`, the way a diff header says how much a file changed. */
18
+ export function DiffStat({ additions, deletions }: { additions: number; deletions: number }) {
19
+ const styles = useStyles();
20
+ const { t } = useLabels();
21
+ return (
22
+ <View
23
+ style={styles.stat}
24
+ accessible
25
+ accessibilityLabel={t('chat.fileChanges.stats', { additions, deletions })}
26
+ >
27
+ {additions > 0 || deletions === 0 ? (
28
+ <Text style={styles.added}>{`+${additions}`}</Text>
29
+ ) : null}
30
+ {deletions > 0 ? <Text style={styles.removed}>{`−${deletions}`}</Text> : null}
31
+ </View>
32
+ );
33
+ }
34
+
35
+ export interface FileChangeSectionProps {
36
+ change: CallFileChange;
37
+ expanded: boolean;
38
+ onToggle: () => void;
39
+ layout: DiffLayout;
40
+ wrap: boolean;
41
+ /** The host's drawing of a patch; the SDK's plain lines when it brought none. */
42
+ renderer: GemieFileDiffRenderer | null;
43
+ }
44
+
45
+ /**
46
+ * One changed file: a header that says what happened to it and how much (`A`/`M`/`D`/`R`, its
47
+ * path, `+X −Y`), copies its path, and folds its patch open or shut. The patch is drawn only while
48
+ * the section is open, so a long list of files costs what the person has opened.
49
+ */
50
+ export function FileChangeSection({
51
+ change,
52
+ expanded,
53
+ onToggle,
54
+ layout,
55
+ wrap,
56
+ renderer,
57
+ }: FileChangeSectionProps) {
58
+ const { t } = useLabels();
59
+ const { isDark, colors } = useTheme();
60
+ const styles = useStyles();
61
+ const Chevron = expanded ? RiArrowDownSLine : RiArrowRightSLine;
62
+ const operation = t(`chat.fileChanges.operation.${change.operation}`);
63
+ const tint = {
64
+ add: colors.success,
65
+ update: colors.warning,
66
+ delete: colors.error,
67
+ rename: colors.info,
68
+ }[change.operation];
69
+
70
+ return (
71
+ <View style={styles.section} testID={`file-change-${change.key}`}>
72
+ <Item
73
+ density="compact"
74
+ leading={
75
+ <Text style={[styles.mark, { color: tint }]} accessibilityLabel={operation}>
76
+ {MARK[change.operation]}
77
+ </Text>
78
+ }
79
+ title={change.path}
80
+ subtitle={
81
+ change.oldPath === undefined
82
+ ? undefined
83
+ : t('chat.fileChanges.renamedFrom', { path: change.oldPath })
84
+ }
85
+ trailing={
86
+ <View style={styles.trailing}>
87
+ <DiffStat additions={change.additions} deletions={change.deletions} />
88
+ <Button
89
+ iconOnly
90
+ size="sm"
91
+ appearance="plain"
92
+ tone="neutral"
93
+ leadingIcon={RiFileCopyLine}
94
+ accessibilityLabel={t('chat.fileChanges.copyPath')}
95
+ onPress={() => {
96
+ void copyText(change.path, t);
97
+ }}
98
+ />
99
+ <Chevron size="sm" fill={colors.textSecondary} />
100
+ </View>
101
+ }
102
+ expanded={expanded}
103
+ onPress={onToggle}
104
+ accessibilityLabel={`${operation}, ${change.path}`}
105
+ />
106
+ {expanded ? (
107
+ <View style={styles.body}>
108
+ <ChangeBody
109
+ change={change}
110
+ layout={layout}
111
+ wrap={wrap}
112
+ renderer={renderer}
113
+ appearance={isDark ? 'dark' : 'light'}
114
+ />
115
+ </View>
116
+ ) : null}
117
+ </View>
118
+ );
119
+ }
120
+
121
+ /** What an open section shows: the patch, or the reason there is none. */
122
+ function ChangeBody({
123
+ change,
124
+ layout,
125
+ wrap,
126
+ renderer,
127
+ appearance,
128
+ }: {
129
+ change: CallFileChange;
130
+ layout: DiffLayout;
131
+ wrap: boolean;
132
+ renderer: GemieFileDiffRenderer | null;
133
+ appearance: 'light' | 'dark';
134
+ }) {
135
+ const { t } = useLabels();
136
+ const styles = useStyles();
137
+ const say = (key: string) => (
138
+ <View style={styles.note}>
139
+ <Muted>{t(key)}</Muted>
140
+ </View>
141
+ );
142
+ if (change.binary) return say('chat.fileChanges.binary');
143
+ if (change.patch === undefined) {
144
+ return say(change.truncated ? 'chat.fileChanges.tooLarge' : 'chat.fileChanges.unrecorded');
145
+ }
146
+ // A patch with headers only: a rename with no edit, an empty file, a changed mode.
147
+ if (change.additions === 0 && change.deletions === 0 && patchLines(change.patch).length === 0) {
148
+ return say('chat.fileChanges.noContent');
149
+ }
150
+ if (renderer === null) return <PatchLines patch={change.patch} wrap={wrap} />;
151
+ const { PatchView } = renderer;
152
+ return (
153
+ <PatchView
154
+ patch={change.patch}
155
+ path={change.path}
156
+ layout={renderer.layouts.includes(layout) ? layout : 'unified'}
157
+ wrap={wrap}
158
+ appearance={appearance}
159
+ />
160
+ );
161
+ }
162
+
163
+ const useStyles = createTokenStyles((t) => ({
164
+ section: { borderTopWidth: 1, borderColor: t.border },
165
+ trailing: { flexDirection: 'row', alignItems: 'center', gap: 6 },
166
+ stat: { flexDirection: 'row', gap: 6 },
167
+ added: { fontSize: 12, fontWeight: 600, color: t.successText },
168
+ removed: { fontSize: 12, fontWeight: 600, color: t.errorText },
169
+ mark: { fontSize: 12, fontWeight: 700, width: 16, textAlign: 'center' },
170
+ body: { paddingBottom: 8 },
171
+ note: { paddingHorizontal: 16, paddingVertical: 12 },
172
+ }));
@@ -0,0 +1,51 @@
1
+ import { Chip } from '@oxy.so/bloom/chip';
2
+ import { RiFileCodeLine } from '@oxy.so/bloom/icons/RiFileCodeLine';
3
+ import { createTokenStyles } from '@oxy.so/bloom/theme';
4
+ import { Text } from '@oxy.so/bloom/typography';
5
+ import { useMemo, useState } from 'react';
6
+ import { View } from 'react-native';
7
+ import { useLabels } from '../../lib/labels';
8
+ import { type CallFileChange, fileChangeTotals } from '../../runtime/thread/file-changes';
9
+ import { FileChangesViewer } from './FileChangesViewer';
10
+
11
+ /**
12
+ * "3 files changed +42 −7", under a turn in which an agent edited files: a chip that opens the
13
+ * viewer on every file the turn changed. Nothing is drawn for a turn that changed none.
14
+ */
15
+ export function FileChangesCard({ changes }: { changes: readonly CallFileChange[] }) {
16
+ const { t } = useLabels();
17
+ const styles = useStyles();
18
+ const [open, setOpen] = useState(false);
19
+ const totals = useMemo(() => fileChangeTotals(changes), [changes]);
20
+ if (changes.length === 0) return null;
21
+
22
+ return (
23
+ <View style={styles.card}>
24
+ <Chip
25
+ size="md"
26
+ leadingIcon={RiFileCodeLine}
27
+ onPress={() => setOpen(true)}
28
+ accessibilityLabel={t('chat.fileChanges.open', {
29
+ count: totals.files,
30
+ additions: totals.additions,
31
+ deletions: totals.deletions,
32
+ })}
33
+ >
34
+ {t('chat.fileChanges.chip', { count: totals.files })}
35
+ {' '}
36
+ <Text style={styles.added}>{`+${totals.additions}`}</Text>
37
+ {' '}
38
+ <Text style={styles.removed}>{`−${totals.deletions}`}</Text>
39
+ </Chip>
40
+ {open ? (
41
+ <FileChangesViewer changes={changes} open={open} onClose={() => setOpen(false)} />
42
+ ) : null}
43
+ </View>
44
+ );
45
+ }
46
+
47
+ const useStyles = createTokenStyles((t) => ({
48
+ card: { alignItems: 'flex-start', paddingVertical: 4 },
49
+ added: { color: t.successText, fontWeight: 600 },
50
+ removed: { color: t.errorText, fontWeight: 600 },
51
+ }));
@@ -0,0 +1,135 @@
1
+ import { Button } from '@oxy.so/bloom/button';
2
+ import { Chip } from '@oxy.so/bloom/chip';
3
+ import { Dialog } from '@oxy.so/bloom/dialog';
4
+ import { RiCollapseDiagonalLine } from '@oxy.so/bloom/icons/RiCollapseDiagonalLine';
5
+ import { RiExpandDiagonalSLine } from '@oxy.so/bloom/icons/RiExpandDiagonalSLine';
6
+ import {
7
+ SegmentedControl,
8
+ SegmentedControlItem,
9
+ SegmentedControlItemText,
10
+ } from '@oxy.so/bloom/segmented-control';
11
+ import { createTokenStyles } from '@oxy.so/bloom/theme';
12
+ import { useMemo, useState } from 'react';
13
+ import { View } from 'react-native';
14
+ import { useLabels } from '../../lib/labels';
15
+ import { type CallFileChange, fileChangeTotals } from '../../runtime/thread/file-changes';
16
+ import { type DiffLayout, useFileDiffRenderer } from './diff-renderer';
17
+ import { FileChangeSection } from './FileChangeSection';
18
+
19
+ /**
20
+ * How many changed lines open on their own, file by file in order. A turn that changed a handful
21
+ * of lines opens them all; one that rewrote a project opens the first files and leaves the rest
22
+ * folded, so the viewer is never a wall.
23
+ */
24
+ export const OPEN_LINE_BUDGET = 600;
25
+
26
+ /** The sections that start open: in order, until the budget of lines is spent. */
27
+ export function initiallyOpen(changes: readonly CallFileChange[]): Set<string> {
28
+ const open = new Set<string>();
29
+ let spent = 0;
30
+ for (const change of changes) {
31
+ const size = change.additions + change.deletions;
32
+ if (change.patch === undefined || change.binary || spent + size > OPEN_LINE_BUDGET) continue;
33
+ spent += size;
34
+ open.add(change.key);
35
+ }
36
+ return open;
37
+ }
38
+
39
+ export interface FileChangesViewerProps {
40
+ changes: readonly CallFileChange[];
41
+ open: boolean;
42
+ onClose: () => void;
43
+ }
44
+
45
+ /**
46
+ * The files an agent changed, as a sheet (a panel on a wide screen): each file a section that folds,
47
+ * with a unified/split choice where the host's renderer has both, line wrapping, and fold or open
48
+ * every file at once.
49
+ */
50
+ export function FileChangesViewer({ changes, open, onClose }: FileChangesViewerProps) {
51
+ const { t } = useLabels();
52
+ const styles = useStyles();
53
+ const renderer = useFileDiffRenderer();
54
+ const totals = useMemo(() => fileChangeTotals(changes), [changes]);
55
+ const [opened, setOpened] = useState(() => initiallyOpen(changes));
56
+ const [layout, setLayout] = useState<DiffLayout>('unified');
57
+ const [wrap, setWrap] = useState(false);
58
+ const allOpen = changes.every((change) => opened.has(change.key));
59
+ const canSplit = renderer?.layouts.includes('split') === true;
60
+
61
+ const toggle = (key: string) =>
62
+ setOpened((current) => {
63
+ const next = new Set(current);
64
+ if (!next.delete(key)) next.add(key);
65
+ return next;
66
+ });
67
+
68
+ return (
69
+ <Dialog
70
+ open={open}
71
+ onClose={onClose}
72
+ placement={{ base: 'bottom', md: 'center' }}
73
+ maxWidth={1040}
74
+ title={t('chat.fileChanges.title')}
75
+ description={t('chat.fileChanges.summary', {
76
+ count: totals.files,
77
+ additions: totals.additions,
78
+ deletions: totals.deletions,
79
+ })}
80
+ >
81
+ <View style={styles.toolbar}>
82
+ {canSplit ? (
83
+ <SegmentedControl
84
+ label={t('chat.fileChanges.layout')}
85
+ type="radio"
86
+ value={layout}
87
+ onValueChange={(next: string) => setLayout(next === 'split' ? 'split' : 'unified')}
88
+ >
89
+ <SegmentedControlItem value="unified">
90
+ <SegmentedControlItemText>{t('chat.fileChanges.unified')}</SegmentedControlItemText>
91
+ </SegmentedControlItem>
92
+ <SegmentedControlItem value="split">
93
+ <SegmentedControlItemText>{t('chat.fileChanges.split')}</SegmentedControlItemText>
94
+ </SegmentedControlItem>
95
+ </SegmentedControl>
96
+ ) : null}
97
+ <Chip role="checkbox" size="sm" checked={wrap} onCheckedChange={setWrap}>
98
+ {t('chat.fileChanges.wrap')}
99
+ </Chip>
100
+ <Button
101
+ size="sm"
102
+ appearance="plain"
103
+ tone="neutral"
104
+ leadingIcon={allOpen ? RiCollapseDiagonalLine : RiExpandDiagonalSLine}
105
+ onPress={() => setOpened(allOpen ? new Set() : new Set(changes.map((c) => c.key)))}
106
+ >
107
+ {allOpen ? t('chat.fileChanges.collapseAll') : t('chat.fileChanges.expandAll')}
108
+ </Button>
109
+ </View>
110
+ <View>
111
+ {changes.map((change) => (
112
+ <FileChangeSection
113
+ key={change.key}
114
+ change={change}
115
+ expanded={opened.has(change.key)}
116
+ onToggle={() => toggle(change.key)}
117
+ layout={layout}
118
+ wrap={wrap}
119
+ renderer={renderer}
120
+ />
121
+ ))}
122
+ </View>
123
+ </Dialog>
124
+ );
125
+ }
126
+
127
+ const useStyles = createTokenStyles(() => ({
128
+ toolbar: {
129
+ flexDirection: 'row',
130
+ flexWrap: 'wrap',
131
+ alignItems: 'center',
132
+ gap: 8,
133
+ paddingBottom: 12,
134
+ },
135
+ }));
@@ -0,0 +1,119 @@
1
+ import { Button } from '@oxy.so/bloom/button';
2
+ import { createTokenStyles } from '@oxy.so/bloom/theme';
3
+ import { Text } from '@oxy.so/bloom/typography';
4
+ import { useMemo, useState } from 'react';
5
+ import { Platform, ScrollView, View } from 'react-native';
6
+ import { useLabels } from '../../lib/labels';
7
+ import { type PatchLine, patchLines } from '../../runtime/thread/file-changes';
8
+ import type { GemiePatchViewProps } from './diff-renderer';
9
+
10
+ /** How many lines are drawn before "Show more": a patch of thousands of lines is not one frame. */
11
+ export const PATCH_LINES_PAGE = 400;
12
+
13
+ const MONO = Platform.select({
14
+ ios: 'Menlo',
15
+ android: 'monospace',
16
+ default: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
17
+ });
18
+
19
+ /** The width, in digits, of the largest line number: every row's number column is as wide. */
20
+ function digitsOf(lines: readonly PatchLine[]): number {
21
+ let largest = 0;
22
+ for (const line of lines) {
23
+ if (line.kind === 'hunk' || line.kind === 'note') continue;
24
+ largest = Math.max(largest, line.oldLine ?? 0, line.newLine ?? 0);
25
+ }
26
+ return String(largest).length;
27
+ }
28
+
29
+ const SIGN = { add: '+', delete: '−', context: ' ' } as const;
30
+
31
+ /**
32
+ * One file's patch as monospace lines, with its line numbers and the added and removed lines
33
+ * tinted: the SDK's own drawing of a patch, which draws on every platform and needs nothing
34
+ * installed. Drawn a page at a time, so a large patch costs what the person has read.
35
+ */
36
+ export function PatchLines({ patch, wrap }: Pick<GemiePatchViewProps, 'patch' | 'wrap'>) {
37
+ const { t } = useLabels();
38
+ const styles = useStyles();
39
+ const lines = useMemo(() => patchLines(patch), [patch]);
40
+ const [shown, setShown] = useState(PATCH_LINES_PAGE);
41
+ const rows = lines.slice(0, shown);
42
+ const gutter = digitsOf(lines);
43
+
44
+ const body = (
45
+ <View style={wrap ? styles.wrapped : undefined}>
46
+ {rows.map((line, index) => (
47
+ // A patch's lines never reorder: their place in it is their identity.
48
+ // biome-ignore lint/suspicious/noArrayIndexKey: see above
49
+ <Row key={`${index}:${line.kind}`} line={line} gutter={gutter} wrap={wrap} />
50
+ ))}
51
+ </View>
52
+ );
53
+
54
+ return (
55
+ <View>
56
+ {wrap ? body : <ScrollView horizontal>{body}</ScrollView>}
57
+ {lines.length > shown ? (
58
+ <View style={styles.more}>
59
+ <Button
60
+ size="sm"
61
+ appearance="outline"
62
+ tone="neutral"
63
+ onPress={() => setShown((count) => count + PATCH_LINES_PAGE)}
64
+ >
65
+ {t('chat.fileChanges.showMore', { count: lines.length - shown })}
66
+ </Button>
67
+ </View>
68
+ ) : null}
69
+ </View>
70
+ );
71
+ }
72
+
73
+ function Row({ line, gutter, wrap }: { line: PatchLine; gutter: number; wrap: boolean }) {
74
+ const styles = useStyles();
75
+ if (line.kind === 'hunk' || line.kind === 'note') {
76
+ return (
77
+ <View style={styles.rowMeta}>
78
+ <Text style={styles.metaText}>{line.text}</Text>
79
+ </View>
80
+ );
81
+ }
82
+ const number = line.kind === 'delete' ? line.oldLine : line.newLine;
83
+ return (
84
+ <View
85
+ style={[
86
+ styles.row,
87
+ line.kind === 'add' ? styles.added : null,
88
+ line.kind === 'delete' ? styles.removed : null,
89
+ ]}
90
+ >
91
+ <Text style={[styles.number, { minWidth: gutter * 9 + 12 }]}>{number ?? ''}</Text>
92
+ <Text style={styles.sign}>{SIGN[line.kind]}</Text>
93
+ <Text style={[styles.code, wrap ? styles.codeWrapped : null]} selectable>
94
+ {line.text === '' ? ' ' : line.text}
95
+ </Text>
96
+ </View>
97
+ );
98
+ }
99
+
100
+ const useStyles = createTokenStyles((t) => ({
101
+ wrapped: { alignSelf: 'stretch' },
102
+ row: { flexDirection: 'row', alignItems: 'flex-start', paddingRight: 12 },
103
+ rowMeta: { paddingHorizontal: 12, paddingVertical: 4, backgroundColor: t.muted },
104
+ metaText: { fontFamily: MONO, fontSize: 12, color: t.mutedForeground },
105
+ added: { backgroundColor: t.successSubtle },
106
+ removed: { backgroundColor: t.errorSubtle },
107
+ number: {
108
+ fontFamily: MONO,
109
+ fontSize: 12,
110
+ lineHeight: 18,
111
+ textAlign: 'right',
112
+ paddingHorizontal: 6,
113
+ color: t.mutedForeground,
114
+ },
115
+ sign: { fontFamily: MONO, fontSize: 12, lineHeight: 18, width: 14, color: t.mutedForeground },
116
+ code: { fontFamily: MONO, fontSize: 12, lineHeight: 18, color: t.foreground },
117
+ codeWrapped: { flexShrink: 1, flexGrow: 1, flexBasis: '0%' },
118
+ more: { alignItems: 'center', paddingVertical: 8 },
119
+ }));
@@ -0,0 +1,38 @@
1
+ import { type ComponentType, createContext, useContext } from 'react';
2
+
3
+ /** How a file's changes are laid out: one column of lines, or the old and new side by side. */
4
+ export type DiffLayout = 'unified' | 'split';
5
+
6
+ export interface GemiePatchViewProps {
7
+ /** One file's unified patch (`diff --git` headers, then its hunks). */
8
+ patch: string;
9
+ /** The file's path, to pick its language by. */
10
+ path: string;
11
+ layout: DiffLayout;
12
+ /** Long lines wrap instead of scrolling sideways. */
13
+ wrap: boolean;
14
+ /** The theme the person reads in. */
15
+ appearance: 'light' | 'dark';
16
+ }
17
+
18
+ /**
19
+ * The drawing of one file's patch. The SDK draws every patch itself, as plain monospace lines
20
+ * (`PatchLines`: nothing to install, the same on every platform); a host that wants more brings
21
+ * its own, as the app does on the web with syntax highlighting and a split layout
22
+ * (`@pierre/diffs`, which the SDK does not depend on).
23
+ */
24
+ export interface GemieFileDiffRenderer {
25
+ PatchView: ComponentType<GemiePatchViewProps>;
26
+ /** The layouts it can draw; the viewer offers a choice only when there is more than one. */
27
+ layouts: readonly DiffLayout[];
28
+ }
29
+
30
+ const FileDiffRendererContext = createContext<GemieFileDiffRenderer | null>(null);
31
+
32
+ /** The host's own drawing of a patch (`fileDiffRenderer`), over the SDK's plain lines. */
33
+ export const GemieFileDiffRendererProvider = FileDiffRendererContext.Provider;
34
+
35
+ /** The host's renderer, `null` when it brought none. */
36
+ export function useFileDiffRenderer(): GemieFileDiffRenderer | null {
37
+ return useContext(FileDiffRendererContext);
38
+ }
@@ -0,0 +1,95 @@
1
+ import { Badge } from '@oxy.so/bloom/badge';
2
+ import { Button } from '@oxy.so/bloom/button';
3
+ import { Card, CardBody } from '@oxy.so/bloom/card';
4
+ import { Muted, Text } from '@oxy.so/bloom/typography';
5
+ import { useRef, useState } from 'react';
6
+ import { StyleSheet, View } from 'react-native';
7
+ import { useLabels } from '../../lib/labels';
8
+ import type { ActionApproval, ConversationActionApprovals } from '../../runtime/action-approvals';
9
+
10
+ export function ActionApprovalCard({
11
+ entry,
12
+ decide,
13
+ }: {
14
+ entry: ActionApproval;
15
+ decide: ConversationActionApprovals['decide'];
16
+ }) {
17
+ const { t } = useLabels();
18
+ const inFlight = useRef(false);
19
+ const [sending, setSending] = useState(false);
20
+ const [error, setError] = useState(false);
21
+ const [decided, setDecided] = useState(false);
22
+
23
+ async function submit(decision: 'approve' | 'reject') {
24
+ if (inFlight.current || entry.status !== 'pending') return;
25
+ inFlight.current = true;
26
+ setSending(true);
27
+ setError(false);
28
+ try {
29
+ await decide(entry.id, decision);
30
+ setDecided(true);
31
+ } catch {
32
+ setError(true);
33
+ } finally {
34
+ inFlight.current = false;
35
+ setSending(false);
36
+ }
37
+ }
38
+
39
+ return (
40
+ <Card>
41
+ <CardBody>
42
+ <View style={styles.body}>
43
+ <View style={styles.header}>
44
+ <Text variant="title-1-medium">{entry.preview.title}</Text>
45
+ <Badge>
46
+ {t(
47
+ entry.status === 'executed' && entry.preview.action === 'send'
48
+ ? 'chat.actionApproval.sent'
49
+ : `chat.actionApproval.status.${entry.status}`,
50
+ )}
51
+ </Badge>
52
+ </View>
53
+ {entry.preview.fields.map(({ name, label, value }) => (
54
+ <View key={name}>
55
+ <Muted>{label}</Muted>
56
+ <Text selectable>{value}</Text>
57
+ </View>
58
+ ))}
59
+ {entry.status === 'pending' ? (
60
+ <View style={styles.buttons}>
61
+ <Button
62
+ appearance="outline"
63
+ tone="neutral"
64
+ size="sm"
65
+ disabled={sending || decided}
66
+ onPress={() => void submit('reject')}
67
+ >
68
+ {t('chat.actionApproval.reject')}
69
+ </Button>
70
+ <Button
71
+ size="sm"
72
+ disabled={sending || decided}
73
+ onPress={() => void submit('approve')}
74
+ >
75
+ {t(
76
+ entry.preview.action === 'send'
77
+ ? 'chat.actionApproval.send'
78
+ : 'chat.actionApproval.approve',
79
+ )}
80
+ </Button>
81
+ </View>
82
+ ) : null}
83
+ {error ? <Muted>{t('chat.actionApproval.decisionFailed')}</Muted> : null}
84
+ {entry.error ? <Muted>{entry.error}</Muted> : null}
85
+ </View>
86
+ </CardBody>
87
+ </Card>
88
+ );
89
+ }
90
+
91
+ const styles = StyleSheet.create({
92
+ body: { gap: 12 },
93
+ header: { flexDirection: 'row', flexWrap: 'wrap', alignItems: 'center', gap: 8 },
94
+ buttons: { flexDirection: 'row', gap: 8, justifyContent: 'flex-end' },
95
+ });
@@ -1,3 +1,5 @@
1
+ import type { ConversationActionApprovals } from '../../runtime/action-approvals';
2
+ import { ActionApprovalCard } from './ActionApprovalCard';
1
3
  import { AgentThinking } from '@oxy.so/bloom/agent-thinking';
2
4
  import { AiChatThread, type AiChatThreadHandle } from '@oxy.so/bloom/ai-chat';
3
5
  import { ChatDateHeader } from '@oxy.so/bloom/chat-screen';
@@ -89,6 +91,7 @@ export interface GemieThreadProps {
89
91
  * turn waits (ADR 0043 §5). Drawn after the turns, where the person is looking.
90
92
  */
91
93
  approvals?: ApprovalsProps;
94
+ actionApprovals?: ConversationActionApprovals;
92
95
  /** The run an agent is on for this conversation: in progress, or the card it leaves. */
93
96
  agentActivity?: AgentActivityState | null;
94
97
  /**
@@ -145,6 +148,7 @@ export const GemieThread = memo(function GemieThread({
145
148
  onStartEdit,
146
149
  newConversationOffer,
147
150
  approvals,
151
+ actionApprovals,
148
152
  agentActivity,
149
153
  call,
150
154
  empty,
@@ -289,6 +293,15 @@ export const GemieThread = memo(function GemieThread({
289
293
  );
290
294
  }
291
295
 
296
+ const messageIds = new Set(rows.map((message) => message.id));
297
+ const renderApproval = (entry: ConversationActionApprovals['entries'][number]) =>
298
+ actionApprovals === undefined ? null : (
299
+ <ActionApprovalCard key={entry.id} entry={entry} decide={actionApprovals.decide} />
300
+ );
301
+ const detachedApprovals = actionApprovals?.entries.filter(
302
+ (entry) => entry.messageId === null || !messageIds.has(entry.messageId),
303
+ );
304
+
292
305
  const renderRow = (message: Message, index: number) => {
293
306
  const fromHistory = index < history.length;
294
307
  const timing = timingOf(message.id);
@@ -321,6 +334,9 @@ export const GemieThread = memo(function GemieThread({
321
334
  workStartedAt={timing.startedAt}
322
335
  workEndedAt={timing.endedAt}
323
336
  />
337
+ {actionApprovals?.entries
338
+ .filter((entry) => entry.messageId === message.id)
339
+ .map(renderApproval)}
324
340
  </Fragment>
325
341
  );
326
342
  };
@@ -374,6 +390,7 @@ export const GemieThread = memo(function GemieThread({
374
390
  {rows
375
391
  .slice(timeline.start)
376
392
  .map((message, offset) => renderRow(message, timeline.start + offset))}
393
+ {detachedApprovals?.map(renderApproval)}
377
394
  </View>
378
395
 
379
396
  {/* Agent execution — in-progress card or completed result card. A run that failed has no
@@ -34,13 +34,20 @@ import { askedQuestions, isQuestionInvocation } from '../../lib/questions';
34
34
  import { parseCatalogueTool, useToolRenderers } from '../../lib/tool-renderers';
35
35
  import { isWebInvocation, taskListLog, webSearchLog } from '../../lib/work-log';
36
36
  import { useGemieRuntime } from '../../runtime/config';
37
- import { type Message, cardOf, formatElapsed, getToolPillLabel } from '../../runtime/model';
37
+ import {
38
+ type Message,
39
+ cardOf,
40
+ formatElapsed,
41
+ getToolPillLabel,
42
+ turnFileChanges,
43
+ } from '../../runtime/model';
38
44
  import type { OpenThought } from '../../hooks/useOpenThought';
39
45
  import { PlanPreviewCard } from '../PlanPreviewCard';
40
46
  import { AskedQuestions } from '../QuestionCard';
41
47
  import { CanvasComponent } from '../canvas/CanvasComponent';
42
48
  import { ReplyMarkdown } from '../ReplyMarkdown';
43
49
  import { MessageBlockBoundary } from './MessageBlockBoundary';
50
+ import { FileChangesCard } from '../diff/FileChangesCard';
44
51
  import { ToolResultCard } from './ToolResultCard';
45
52
  import { ChatBubble } from './ChatBubble';
46
53
  import { TurnMenu } from './TurnMenu';
@@ -323,6 +330,8 @@ function ReplyTurn({
323
330
  const card = cardOf(call);
324
331
  return card === null ? [] : [{ key: call.toolCallId || `tool-${message.id}-${index}`, card }];
325
332
  });
333
+ // The files an external agent edited this turn, whose patches its edit calls carry.
334
+ const fileChanges = turnFileChanges(toolInvocations);
326
335
  /** The template swaps the steps for the reply once the turn is done. */
327
336
  const turnWorking = isLoading && isLastReply && message.isStreaming === true;
328
337
 
@@ -418,6 +427,7 @@ function ReplyTurn({
418
427
  text.length > 0 ||
419
428
  hasWorkLog ||
420
429
  toolCards.length > 0 ||
430
+ fileChanges.length > 0 ||
421
431
  rendered.length > 0 ||
422
432
  gemieConversations.length > 0 ||
423
433
  inlineCanvases.length > 0 ||
@@ -558,6 +568,11 @@ function ReplyTurn({
558
568
  <ToolResultCard card={card} />
559
569
  </MessageBlockBoundary>
560
570
  ))}
571
+ {fileChanges.length === 0 ? null : (
572
+ <MessageBlockBoundary>
573
+ <FileChangesCard changes={fileChanges} />
574
+ </MessageBlockBoundary>
575
+ )}
561
576
  {gemieConversations.map(({ key, conversation }) => (
562
577
  <MessageBlockBoundary key={key}>
563
578
  <GemieConversationCard
package/src/index.ts CHANGED
@@ -31,6 +31,12 @@ export { ANCHORS, leadToProfile } from './lib/flights';
31
31
  export { parseCatalogueTool, toolRendererKey } from './lib/catalogue-tool';
32
32
  export type { GemieToolRenderers, GemieToolResult } from './lib/tool-renderers';
33
33
  export type { GemieChartCards } from './components/charts/chart-cards';
34
+ export type {
35
+ DiffLayout,
36
+ GemieFileDiffRenderer,
37
+ GemiePatchViewProps,
38
+ } from './components/diff/diff-renderer';
39
+ export { PatchLines } from './components/diff/PatchLines';
34
40
  export { GemieAskProvider, useAskGemie } from './components/GemieAskProvider';
35
41
  export type {
36
42
  GemieAsk,
@@ -84,7 +84,47 @@ 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.fileChanges.binary': 'Binary file, no preview',
88
+ 'chat.fileChanges.chip': { one: '1 file changed', other: '{{count}} files changed' },
89
+ 'chat.fileChanges.collapseAll': 'Collapse all',
90
+ 'chat.fileChanges.copyPath': 'Copy path',
91
+ 'chat.fileChanges.expandAll': 'Expand all',
92
+ 'chat.fileChanges.layout': 'Layout',
93
+ 'chat.fileChanges.noContent': 'No changes to the contents',
94
+ 'chat.fileChanges.open': {
95
+ one: 'Review 1 changed file, +{{additions}} −{{deletions}}',
96
+ other: 'Review {{count}} changed files, +{{additions}} −{{deletions}}',
97
+ },
98
+ 'chat.fileChanges.operation.add': 'Added',
99
+ 'chat.fileChanges.operation.delete': 'Deleted',
100
+ 'chat.fileChanges.operation.rename': 'Renamed',
101
+ 'chat.fileChanges.operation.update': 'Modified',
102
+ 'chat.fileChanges.renamedFrom': 'Renamed from {{path}}',
103
+ 'chat.fileChanges.showMore': { one: 'Show 1 more line', other: 'Show {{count}} more lines' },
104
+ 'chat.fileChanges.split': 'Split',
105
+ 'chat.fileChanges.stats': '{{additions}} lines added, {{deletions}} lines removed',
106
+ 'chat.fileChanges.summary': {
107
+ one: '1 file changed, +{{additions}} −{{deletions}}',
108
+ other: '{{count}} files changed, +{{additions}} −{{deletions}}',
109
+ },
110
+ 'chat.fileChanges.title': 'Changes',
111
+ 'chat.fileChanges.tooLarge': 'Too large to show here',
112
+ 'chat.fileChanges.unified': 'Unified',
113
+ 'chat.fileChanges.unrecorded': 'The agent did not record what changed in this file',
114
+ 'chat.fileChanges.wrap': 'Wrap lines',
87
115
  'chat.like': 'Like',
116
+ 'chat.actionApproval.send': 'Send',
117
+ 'chat.actionApproval.approve': 'Approve',
118
+ 'chat.actionApproval.reject': 'Reject',
119
+ 'chat.actionApproval.status.pending': 'Pending approval',
120
+ 'chat.actionApproval.status.approved': 'Approved',
121
+ 'chat.actionApproval.status.executing': 'Sending…',
122
+ 'chat.actionApproval.status.executed': 'Completed',
123
+ 'chat.actionApproval.status.failed': 'Failed',
124
+ 'chat.actionApproval.status.rejected': 'Rejected',
125
+ 'chat.actionApproval.status.expired': 'Expired',
126
+ 'chat.actionApproval.sent': 'Sent',
127
+ 'chat.actionApproval.decisionFailed': 'Your decision couldn’t be saved. Try again.',
88
128
  'chat.approval.allow': 'Allow',
89
129
  'chat.approval.deny': 'Deny',
90
130
  'chat.approval.resolved.allow': '%{tool}: allowed',
@@ -80,7 +80,50 @@ 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.fileChanges.binary': 'Archivo binario, sin vista previa',
84
+ 'chat.fileChanges.chip': { one: '1 archivo cambiado', other: '{{count}} archivos cambiados' },
85
+ 'chat.fileChanges.collapseAll': 'Contraer todo',
86
+ 'chat.fileChanges.copyPath': 'Copiar ruta',
87
+ 'chat.fileChanges.expandAll': 'Expandir todo',
88
+ 'chat.fileChanges.layout': 'Disposición',
89
+ 'chat.fileChanges.noContent': 'Sin cambios en el contenido',
90
+ 'chat.fileChanges.open': {
91
+ one: 'Revisar 1 archivo cambiado, +{{additions}} −{{deletions}}',
92
+ other: 'Revisar {{count}} archivos cambiados, +{{additions}} −{{deletions}}',
93
+ },
94
+ 'chat.fileChanges.operation.add': 'Añadido',
95
+ 'chat.fileChanges.operation.delete': 'Eliminado',
96
+ 'chat.fileChanges.operation.rename': 'Renombrado',
97
+ 'chat.fileChanges.operation.update': 'Modificado',
98
+ 'chat.fileChanges.renamedFrom': 'Renombrado desde {{path}}',
99
+ 'chat.fileChanges.showMore': {
100
+ one: 'Mostrar 1 línea más',
101
+ other: 'Mostrar {{count}} líneas más',
102
+ },
103
+ 'chat.fileChanges.split': 'Dividida',
104
+ 'chat.fileChanges.stats': '{{additions}} líneas añadidas, {{deletions}} líneas eliminadas',
105
+ 'chat.fileChanges.summary': {
106
+ one: '1 archivo cambiado, +{{additions}} −{{deletions}}',
107
+ other: '{{count}} archivos cambiados, +{{additions}} −{{deletions}}',
108
+ },
109
+ 'chat.fileChanges.title': 'Cambios',
110
+ 'chat.fileChanges.tooLarge': 'Demasiado grande para mostrarlo aquí',
111
+ 'chat.fileChanges.unified': 'Unificada',
112
+ 'chat.fileChanges.unrecorded': 'El agente no registró qué cambió en este archivo',
113
+ 'chat.fileChanges.wrap': 'Ajustar líneas',
83
114
  'chat.like': 'Me gusta',
115
+ 'chat.actionApproval.send': 'Enviar',
116
+ 'chat.actionApproval.approve': 'Aprobar',
117
+ 'chat.actionApproval.reject': 'Rechazar',
118
+ 'chat.actionApproval.status.pending': 'Pendiente de aprobación',
119
+ 'chat.actionApproval.status.approved': 'Aprobado',
120
+ 'chat.actionApproval.status.executing': 'En curso…',
121
+ 'chat.actionApproval.status.executed': 'Completado',
122
+ 'chat.actionApproval.status.failed': 'Fallido',
123
+ 'chat.actionApproval.status.rejected': 'Rechazado',
124
+ 'chat.actionApproval.status.expired': 'Caducado',
125
+ 'chat.actionApproval.sent': 'Enviado',
126
+ 'chat.actionApproval.decisionFailed': 'Tu decisión no se pudo guardar. Inténtalo de nuevo.',
84
127
  'chat.approval.allow': 'Permitir',
85
128
  'chat.approval.deny': 'Denegar',
86
129
  'chat.approval.resolved.allow': '%{tool}: permitido',
@@ -0,0 +1,127 @@
1
+ import { useCallback, useEffect, useState } from 'react';
2
+ import { useRealtimeEvent, useRealtimeReset } from '../realtime/react';
3
+ import { useGemieApi } from './api';
4
+ import { API_ROUTES } from './routes';
5
+
6
+ const STATUS_ORDER = {
7
+ pending: 0,
8
+ approved: 1,
9
+ executing: 2,
10
+ executed: 3,
11
+ failed: 3,
12
+ rejected: 3,
13
+ expired: 3,
14
+ };
15
+
16
+ export interface ActionApproval {
17
+ id: string;
18
+ conversationId: string;
19
+ messageId: string | null;
20
+ preview: {
21
+ title: string;
22
+ action: 'send' | 'approve';
23
+ fields: { name: string; label: string; value: string }[];
24
+ };
25
+ status: keyof typeof STATUS_ORDER;
26
+ expiresAt: string;
27
+ decidedAt: string | null;
28
+ error: string | null;
29
+ }
30
+
31
+ type DecideAction = (id: string, decision: 'approve' | 'reject') => Promise<void>;
32
+ export interface ConversationActionApprovals {
33
+ entries: readonly ActionApproval[];
34
+ decide: DecideAction;
35
+ }
36
+
37
+ const NO_ENTRIES: readonly ActionApproval[] = [];
38
+
39
+ export function useConversationActionApprovals(
40
+ userId: string | undefined,
41
+ conversationId: string | undefined,
42
+ streaming: boolean,
43
+ ): ConversationActionApprovals {
44
+ const api = useGemieApi();
45
+ const scope = userId && conversationId ? JSON.stringify([userId, conversationId]) : undefined;
46
+ const [snapshot, setSnapshot] = useState<{
47
+ scope: string;
48
+ entries: readonly ActionApproval[];
49
+ }>();
50
+ const entries = snapshot?.scope === scope ? (snapshot?.entries ?? NO_ENTRIES) : NO_ENTRIES;
51
+
52
+ const refresh = useCallback(
53
+ (signal?: AbortSignal) => {
54
+ if (!scope || !conversationId) return;
55
+ void api
56
+ .get<{ approvals: ActionApproval[] }>(API_ROUTES.actionApprovals.list, {
57
+ params: { conversationId },
58
+ signal,
59
+ })
60
+ .then(({ data }) => {
61
+ if (signal?.aborted || !Array.isArray(data?.approvals)) return;
62
+ setSnapshot((previous) => {
63
+ const known = previous?.scope === scope ? previous.entries : NO_ENTRIES;
64
+ const byId = new Map(known.map((entry) => [entry.id, entry]));
65
+ return {
66
+ scope,
67
+ entries: [...data.approvals].reverse().map((entry) => {
68
+ const old = byId.get(entry.id);
69
+ return old && STATUS_ORDER[old.status] > STATUS_ORDER[entry.status] ? old : entry;
70
+ }),
71
+ };
72
+ });
73
+ })
74
+ .catch(() => undefined);
75
+ },
76
+ [api, conversationId, scope],
77
+ );
78
+
79
+ useEffect(() => {
80
+ if (streaming) return;
81
+ const controller = new AbortController();
82
+ refresh(controller.signal);
83
+ return () => controller.abort();
84
+ }, [refresh, streaming]);
85
+
86
+ useRealtimeEvent('conversation', ({ data }) => {
87
+ const change = data as { conversation?: { id?: string } };
88
+ if (change.conversation?.id === conversationId) refresh();
89
+ });
90
+ useRealtimeReset(refresh);
91
+
92
+ // The account event is the usual wake. Poll only while a decision or provider receipt is due.
93
+ const awaitingDecision = entries.some((entry) => STATUS_ORDER[entry.status] < 3);
94
+ useEffect(() => {
95
+ if (!awaitingDecision) return;
96
+ const controller = new AbortController();
97
+ const timer = setInterval(() => refresh(controller.signal), 5000);
98
+ return () => {
99
+ controller.abort();
100
+ clearInterval(timer);
101
+ };
102
+ }, [awaitingDecision, refresh]);
103
+
104
+ const decide = useCallback<DecideAction>(
105
+ async (id, decision) => {
106
+ if (!scope) return;
107
+ const { data } = await api.post<ActionApproval>(
108
+ API_ROUTES.actionApprovals.decide(id, decision),
109
+ );
110
+ setSnapshot((previous) =>
111
+ previous?.scope !== scope
112
+ ? previous
113
+ : {
114
+ scope,
115
+ entries: previous.entries.map((entry) =>
116
+ entry.id === id && STATUS_ORDER[entry.status] <= STATUS_ORDER[data.status]
117
+ ? data
118
+ : entry,
119
+ ),
120
+ },
121
+ );
122
+ },
123
+ [api, scope],
124
+ );
125
+
126
+ return { entries, decide };
127
+ }
@@ -22,9 +22,20 @@ export interface GemieArtifact {
22
22
  timestamp: number;
23
23
  }
24
24
 
25
+ /**
26
+ * A turn answered on a lighter model because the person's credits ran out (`alia.credits_fallback`):
27
+ * why, and that the turn's tools are paused. Gemies pays for it; the person is charged nothing.
28
+ */
29
+ export interface GemieCreditsFallback {
30
+ reason: 'credits';
31
+ tools: 'paused';
32
+ }
33
+
25
34
  /** The usage frame a stream ends with: the balance left and, sometimes, a spending warning. */
26
35
  export interface GemieUsageFrame {
27
36
  credits_remaining?: number;
37
+ /** Present when Gemies funded the turn because the person's credits ran out. */
38
+ fallback?: GemieCreditsFallback;
28
39
  credit_warning?: {
29
40
  level?: string;
30
41
  daysRemaining?: unknown;
@@ -86,6 +97,11 @@ export interface GemieRuntimeHost {
86
97
  onOutput?: () => void;
87
98
  /** The stream's usage frame: credits left and the spending warning. */
88
99
  onUsage?: (usage: GemieUsageFrame) => void;
100
+ /**
101
+ * The turn about to stream is on the credits fallback: a lighter model with tools paused. Sent
102
+ * before the first token, so the host can say so while the answer arrives.
103
+ */
104
+ onCreditsFallback?: (fallback: GemieCreditsFallback) => void;
89
105
  /** A tool finished; `name` is the tool, `output` its structural result. */
90
106
  onToolResult?: (result: {
91
107
  toolCallId: string;
@@ -22,6 +22,7 @@ export type {
22
22
  GemieRuntimeHost,
23
23
  GemieRuntimeProviderProps,
24
24
  GemieTurnRequest,
25
+ GemieCreditsFallback,
25
26
  GemieUsageFrame,
26
27
  OfflineConversationStore,
27
28
  SpeechPreferences,
@@ -15,6 +15,7 @@ export type { Translate } from '../lib/copy';
15
15
  export * from './thread/agent-activity';
16
16
  export * from './thread/automation-labels';
17
17
  export * from './thread/conversation-export';
18
+ export * from './thread/file-changes';
18
19
  export * from './thread/message-days';
19
20
  export * from './thread/message-processor';
20
21
  export * from './thread/task-utils';
@@ -11,6 +11,11 @@
11
11
  */
12
12
  export const API_ROUTES = {
13
13
  chat: '/v1/chat/completions',
14
+ actionApprovals: {
15
+ list: '/v1/action-approvals',
16
+ decide: (id: string, decision: 'approve' | 'reject') =>
17
+ `/v1/action-approvals/${encodeURIComponent(id)}/${decision}`,
18
+ },
14
19
  /** The answer to an awaited host action, read by the turn that is waiting for it. */
15
20
  hostResults: (turnId: string) => `/v1/chat/turns/${encodeURIComponent(turnId)}/host-results`,
16
21
  /** The person's folders and projects (`runtime/collections.ts`). */
@@ -0,0 +1,150 @@
1
+ import type { ToolInvocation } from '../types';
2
+
3
+ /**
4
+ * The files an external agent (Claude Code, Codex, OpenCode) changed, as the conversation keeps
5
+ * them (ADR 0043 §5): the tool result of an edit carries `changes`, one standard `diff --git` patch
6
+ * per file, made by the server from whatever each CLI recorded
7
+ * (`packages/api/src/lib/external-agents/file-changes.ts`).
8
+ *
9
+ * Pure. The result is read like every tool result (`cardOf`): the snapshot is untrusted JSON, so
10
+ * every field is checked and an entry that is not a change is left out.
11
+ */
12
+
13
+ export type FileChangeOperation = 'add' | 'update' | 'delete' | 'rename';
14
+
15
+ export interface FileChange {
16
+ /** Relative to the agent's folder when the daemon said so. */
17
+ path: string;
18
+ /** Where a renamed file was. */
19
+ oldPath?: string;
20
+ operation: FileChangeOperation;
21
+ /** Not text (an image, a binary): its patch only says the file changed. */
22
+ binary: boolean;
23
+ /** Absent when nothing was recorded to build one from, or it was too large to keep. */
24
+ patch?: string;
25
+ additions: number;
26
+ deletions: number;
27
+ /** The patch was left out because it was too large (the stats are still the file's). */
28
+ truncated: boolean;
29
+ }
30
+
31
+ /** A change and the call that made it, so two edits of one file stay two sections. */
32
+ export interface CallFileChange extends FileChange {
33
+ /** Unique within the turn: the call's id and the file's place in it. */
34
+ key: string;
35
+ }
36
+
37
+ export interface FileChangeTotals {
38
+ /** Distinct paths: a file edited twice is one file. */
39
+ files: number;
40
+ additions: number;
41
+ deletions: number;
42
+ }
43
+
44
+ const OPERATIONS: readonly FileChangeOperation[] = ['add', 'update', 'delete', 'rename'];
45
+
46
+ const isCount = (value: unknown): value is number =>
47
+ typeof value === 'number' && Number.isFinite(value) && value >= 0;
48
+
49
+ function fileChange(value: unknown): FileChange | null {
50
+ if (value === null || typeof value !== 'object') return null;
51
+ const v = value as Record<string, unknown>;
52
+ if (typeof v.path !== 'string' || v.path === '') return null;
53
+ if (!OPERATIONS.includes(v.operation as FileChangeOperation)) return null;
54
+ return {
55
+ path: v.path,
56
+ ...(typeof v.oldPath === 'string' && v.oldPath !== '' ? { oldPath: v.oldPath } : {}),
57
+ operation: v.operation as FileChangeOperation,
58
+ binary: v.binary === true,
59
+ ...(typeof v.patch === 'string' ? { patch: v.patch } : {}),
60
+ additions: isCount(v.additions) ? v.additions : 0,
61
+ deletions: isCount(v.deletions) ? v.deletions : 0,
62
+ truncated: v.truncated === true,
63
+ };
64
+ }
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;
70
+ if (!Array.isArray(changes)) return [];
71
+ return changes.flatMap((entry, index) => {
72
+ const change = fileChange(entry);
73
+ return change === null ? [] : [{ ...change, key: `${call.toolCallId}:${index}` }];
74
+ });
75
+ }
76
+
77
+ /** Every file the calls of a turn changed, call by call. */
78
+ export function turnFileChanges(calls: readonly ToolInvocation[]): CallFileChange[] {
79
+ return calls.flatMap(fileChangesOf);
80
+ }
81
+
82
+ /** What "N files changed +X −Y" says of a list of changes. */
83
+ export function fileChangeTotals(changes: readonly FileChange[]): FileChangeTotals {
84
+ const files = new Set<string>();
85
+ let additions = 0;
86
+ let deletions = 0;
87
+ for (const change of changes) {
88
+ files.add(change.path);
89
+ additions += change.additions;
90
+ deletions += change.deletions;
91
+ }
92
+ return { files: files.size, additions, deletions };
93
+ }
94
+
95
+ /** The file's name, without its folder. */
96
+ export function fileChangeName(path: string): string {
97
+ const parts = path.replaceAll('\\', '/').split('/');
98
+ return parts.at(-1) || path;
99
+ }
100
+
101
+ /** One line of a patch's hunks, as a plain list can draw it. */
102
+ export type PatchLine =
103
+ | { kind: 'hunk'; text: string }
104
+ | { kind: 'context' | 'add' | 'delete'; text: string; oldLine?: number; newLine?: number }
105
+ | { kind: 'note'; text: string };
106
+
107
+ const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@(.*)$/;
108
+
109
+ /**
110
+ * The lines of a patch's hunks with their line numbers, for a view that draws no more than text.
111
+ * The headers before the first hunk (`diff --git`, `---`, `+++`, `new file mode`) are not lines of
112
+ * the file and are left out; `` is kept as a note.
113
+ */
114
+ export function patchLines(patch: string): PatchLine[] {
115
+ const out: PatchLine[] = [];
116
+ let oldLine = 0;
117
+ let newLine = 0;
118
+ let inHunk = false;
119
+ const lines = patch.split('\n');
120
+ if (lines.at(-1) === '') lines.pop();
121
+ for (const line of lines) {
122
+ const header = HUNK_HEADER.exec(line);
123
+ if (header) {
124
+ inHunk = true;
125
+ oldLine = Number(header[1]);
126
+ newLine = Number(header[2]);
127
+ out.push({ kind: 'hunk', text: line });
128
+ continue;
129
+ }
130
+ if (!inHunk) continue;
131
+ if (line.startsWith('\\')) {
132
+ out.push({ kind: 'note', text: line.slice(1).trim() });
133
+ } else if (line.startsWith('+')) {
134
+ out.push({ kind: 'add', text: line.slice(1), newLine: newLine++ });
135
+ } else if (line.startsWith('-')) {
136
+ out.push({ kind: 'delete', text: line.slice(1), oldLine: oldLine++ });
137
+ } else if (line.startsWith('diff --git ')) {
138
+ // A second file's section in a patch of several: the viewer is handed one file's patch.
139
+ break;
140
+ } else {
141
+ out.push({
142
+ kind: 'context',
143
+ text: line.startsWith(' ') ? line.slice(1) : line,
144
+ oldLine: oldLine++,
145
+ newLine: newLine++,
146
+ });
147
+ }
148
+ }
149
+ return out;
150
+ }
@@ -726,7 +726,7 @@ export function useConversationStream({
726
726
  return;
727
727
  }
728
728
  if (isGroupTurn && event.errorCode === 'agent_declined') {
729
- // A superseded room reply was never stored. Drop its provisional text
729
+ // A declined room reply was never stored. Drop its provisional text
730
730
  // across both transports instead of presenting it as a failed saved reply.
731
731
  roomRef.current.ended.add(event.consultId);
732
732
  roomRef.current.discarded.add(event.consultId);
@@ -1213,6 +1213,10 @@ export function useConversationStream({
1213
1213
  }
1214
1214
  continue;
1215
1215
  }
1216
+ case 'alia.credits_fallback': {
1217
+ host.onCreditsFallback?.({ reason: 'credits', tools: 'paused' });
1218
+ continue;
1219
+ }
1216
1220
  case 'alia.agent_turn': {
1217
1221
  if (parsed.turnId) {
1218
1222
  const run = {