@gemies/sdk 10.1.0 → 10.3.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,44 @@
1
1
  # @gemies/sdk
2
2
 
3
+ ## 10.3.0
4
+
5
+ ### Chat streams resume after a dropped connection
6
+
7
+ When the connection that carries a turn drops (a network switch, a sleeping tab, a proxy closing an
8
+ idle socket), `useConversationStream` no longer fails the turn. The server numbers every frame of a
9
+ turn (the SSE `id:`) and keeps the newest ones; the client remembers the last number it applied and,
10
+ on a stream that ends without `[DONE]` or fails mid-read, reconnects to
11
+ `GET /v1/chat/turns/:turnId/stream` with exponential backoff and jitter and carries on. A frame it
12
+ already has is dropped by its number, so a delta is applied once. When the server cannot replay what
13
+ was missed (the cursor is older than its buffer, or the turn finished meanwhile) it sends one
14
+ `alia.snapshot` of the turn instead, which the client applies idempotently over the reply it is
15
+ drawing. The turn is failed only once the resume is refused or its attempts are spent, and then as a
16
+ cut stream always was: `hasUsableStreamOutput` decides whether the person keeps an answer.
17
+
18
+ A server that does not number its frames is read exactly as before. Nothing is added to the public
19
+ API: the reconnect lives inside the hook.
20
+
21
+ ## 10.2.0
22
+
23
+ ### The files an agent changed, as a diff
24
+
25
+ A turn in which an external agent (Claude Code, Codex, OpenCode) edited files now ends with a
26
+ "N files changed +X −Y" chip under it, and the chip opens a viewer: one section per file with its
27
+ `+`/`−` counts, folding on its own and all at once, copying its path, with a choice of unified or
28
+ split layout where the host's renderer has both, and line wrapping. The patches come from the edit
29
+ call's tool result (`changes`, one standard `diff --git` patch per file, made by the server from
30
+ whatever each CLI recorded). A file with no patch says why: binary, too large to keep, or never
31
+ recorded by the agent.
32
+
33
+ The SDK draws a patch itself, as numbered monospace lines with the added and removed ones tinted,
34
+ on every platform, a page of 400 lines at a time. A host that wants more passes `fileDiffRenderer`
35
+ to `GemieChatContent` (`{ PatchView, layouts }`, typed `GemieFileDiffRenderer`): the Gemies web app
36
+ brings `@pierre/diffs`, with syntax highlighting in a worker pool and a split layout, which the SDK
37
+ does not depend on. `PatchLines` is exported as the fallback for a host's own renderer while it loads.
38
+
39
+ `@gemies/sdk/model` carries the data side: `fileChangesOf`, `turnFileChanges`, `fileChangeTotals`
40
+ and `patchLines`.
41
+
3
42
  ## 10.1.0
4
43
 
5
44
  ### `@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.3.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
+ }