@gemies/sdk 10.13.0 → 10.15.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.15.0
4
+
5
+ ### A gemie can call
6
+
7
+ A gemie's call rings as a `call` frame on the realtime connection, and is answered by opening the
8
+ voice session with its id: `useVoiceRoom({ callId, conversationId, agentId })`. The new
9
+ `@gemies/sdk/calls` entry carries the shared types (`CallWire`, `CallEventData`, statuses, end
10
+ reasons and error codes). The voice protocol gains `assistant.speaking`, `endedBy: 'gemie'` on
11
+ `session.closed` when the gemie hung up, and the `call-unavailable` error. The contract is Gemies
12
+ `docs/calls-api.md`.
13
+
14
+ ## 10.14.0
15
+
16
+ ### What a coding agent's turn changed, and the way back
17
+
18
+ A turn that carries a checkpoint (Gemies ADR 0052) shows its changes once, in the "N files changed"
19
+ chip, and not as a step of the work log. The diff viewer now draws a tree of the changed files above
20
+ the diffs, and pressing a file opens its diff. From a checkpointed turn the viewer also offers the
21
+ whole conversation's changes and, where Gemies allows it, reverting to before the turn, after asking.
22
+
23
+ Two optional host callbacks carry what the SDK cannot ask `/v1` for: `listTurnCheckpoints` and
24
+ `revertTurnCheckpoint`. Without them a turn's diffs still show, from the thread alone. New copy under
25
+ `chat.checkpoints.*` and `chat.fileTree.*`.
26
+
3
27
  ## 10.13.0
4
28
 
5
29
  ### A usage limit says when it resets
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gemies/sdk",
3
- "version": "10.13.0",
3
+ "version": "10.15.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",
@@ -14,6 +14,7 @@
14
14
  "./ask/lean": "./src/ask-lean.ts",
15
15
  "./ask/text": "./src/ask-text.ts",
16
16
  "./avatar": "./src/avatar.ts",
17
+ "./calls": "./src/calls.ts",
17
18
  "./character": "./src/character.ts",
18
19
  "./connectors": "./src/connectors.ts",
19
20
  "./content": "./src/lib/content-utils.ts",
package/src/calls.ts ADDED
@@ -0,0 +1,107 @@
1
+ /**
2
+ * A gemie's calls, as a client sees them (Gemies `docs/calls-api.md`).
3
+ *
4
+ * The server's copy is `packages/api/src/domain/call.ts`; the SDK does not depend on the API
5
+ * package, so the shapes are restated here and `call-contract.test.ts` holds the two equal.
6
+ *
7
+ * Pure data: no React, no socket. A ringing call arrives as a `call` frame on the realtime
8
+ * connection (`@gemies/sdk/realtime`) and is listed by `GET /calls?live=true`; it is answered by
9
+ * opening the voice session with its id (`useVoiceRoom({ callId, conversationId, agentId })`).
10
+ */
11
+
12
+ export const CALL_CHANNELS = ['app', 'phone', 'own_number'] as const;
13
+ export type CallChannel = (typeof CALL_CHANNELS)[number];
14
+
15
+ export const CALL_DIRECTIONS = ['outbound', 'inbound'] as const;
16
+ export type CallDirection = (typeof CALL_DIRECTIONS)[number];
17
+
18
+ export const CALL_STATUSES = [
19
+ 'ringing',
20
+ 'active',
21
+ 'ended',
22
+ 'failed',
23
+ 'declined',
24
+ 'missed',
25
+ ] as const;
26
+ export type CallStatus = (typeof CALL_STATUSES)[number];
27
+
28
+ export const CALL_END_REASONS = [
29
+ 'gemie_hangup',
30
+ 'conversation_ended',
31
+ 'user_hangup',
32
+ 'declined',
33
+ 'missed',
34
+ 'cancelled',
35
+ 'max_duration',
36
+ 'idle_timeout',
37
+ 'credits_exhausted',
38
+ 'moved_elsewhere',
39
+ 'server_shutdown',
40
+ 'error',
41
+ ] as const;
42
+ export type CallEndReason = (typeof CALL_END_REASONS)[number];
43
+
44
+ export const CALL_SPEAKERS = ['gemie', 'user', 'third_party'] as const;
45
+ export type CallSpeaker = (typeof CALL_SPEAKERS)[number];
46
+
47
+ export const CALL_ERROR_CODES = [
48
+ 'invalid_request',
49
+ 'not_found',
50
+ 'not_ringing',
51
+ 'not_live',
52
+ 'call_in_progress',
53
+ 'rate_limited',
54
+ 'voice_plan_required',
55
+ 'not_configured',
56
+ 'not_enabled',
57
+ ] as const;
58
+ export type CallErrorCode = (typeof CALL_ERROR_CODES)[number];
59
+
60
+ export const CALL_EVENTS = [
61
+ 'call.ringing',
62
+ 'call.accepted',
63
+ 'call.declined',
64
+ 'call.missed',
65
+ 'call.ended',
66
+ 'call.failed',
67
+ ] as const;
68
+ export type CallEventName = (typeof CALL_EVENTS)[number];
69
+
70
+ /** A call, as `GET /calls` and the `call` realtime frame carry it. */
71
+ export interface CallWire {
72
+ readonly id: string;
73
+ readonly channel: CallChannel;
74
+ readonly direction: CallDirection;
75
+ readonly status: CallStatus;
76
+ readonly endReason: CallEndReason | null;
77
+ /** The gemie; `null` is Alia. */
78
+ readonly agentId: string | null;
79
+ readonly agentName: string | null;
80
+ readonly conversationId: string | null;
81
+ readonly purpose: string | null;
82
+ readonly to: string | null;
83
+ readonly from: string | null;
84
+ readonly createdAt: string;
85
+ readonly ringExpiresAt: string | null;
86
+ readonly answeredAt: string | null;
87
+ readonly endedAt: string | null;
88
+ readonly durationSeconds: number | null;
89
+ }
90
+
91
+ export interface CallTranscriptEntry {
92
+ readonly id: string;
93
+ readonly speaker: CallSpeaker;
94
+ readonly text: string;
95
+ readonly ts: string;
96
+ }
97
+
98
+ /** The `data` of a `call` realtime frame. */
99
+ export interface CallEventData {
100
+ readonly event: CallEventName;
101
+ readonly call: CallWire;
102
+ }
103
+
104
+ /** The body of a refused `/calls` request. */
105
+ export interface CallErrorBody {
106
+ readonly error: { readonly code: CallErrorCode; readonly message: string };
107
+ }
@@ -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 }) => (
@@ -37,6 +37,11 @@ export interface UseVoiceRoomOptions {
37
37
  conversationId?: string;
38
38
  /** The agent this call talks to; omitted, Alia. */
39
39
  agentId?: string;
40
+ /**
41
+ * Answer this ringing call from the gemie (`@gemies/sdk/calls`). `conversationId` and `agentId`
42
+ * must be the call's own.
43
+ */
44
+ callId?: string;
40
45
  /** Which of the product's two voices answers. */
41
46
  voicePreference?: ProductVoice;
42
47
  /** Bearer for the call; defaults to the surrounding Oxy session's. */
@@ -126,6 +131,7 @@ export function useVoiceRoom(options: UseVoiceRoomOptions = {}) {
126
131
  getAppAssertion,
127
132
  conversationId: current.conversationId ?? newConversationId(),
128
133
  ...(current.agentId === undefined ? {} : { agentId: current.agentId }),
134
+ ...(current.callId === undefined ? {} : { callId: current.callId }),
129
135
  voice: current.voicePreference ?? 'female',
130
136
  locale: current.lang ?? defaultSpeechLanguage(),
131
137
  createEngine: current.createAudioEngine ?? createVoiceAudioEngine,
@@ -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',
@@ -9,6 +9,7 @@ const VOICE_ERRORS: Record<VoiceErrorCode, string> = {
9
9
  'plan-required': 'El modo voz necesita un plan de pago',
10
10
  'credits-exhausted': 'Te has quedado sin créditos para esta llamada',
11
11
  'agent-unavailable': 'Este Gemie no está disponible para una llamada',
12
+ 'call-unavailable': 'Esa llamada ya no está sonando',
12
13
  'invalid-request': 'No se pudo iniciar la llamada',
13
14
  'resume-unavailable': 'No se pudo retomar la llamada: empieza una nueva',
14
15
  'realtime-unavailable': 'La voz no está disponible ahora mismo: inténtalo más tarde',
@@ -36,6 +36,7 @@ export const VOICE_ERROR_MESSAGES: Readonly<Record<VoiceErrorCode, string>> = {
36
36
  'plan-required': 'Voice mode needs a paid plan',
37
37
  'credits-exhausted': "You've run out of credits for this call",
38
38
  'agent-unavailable': 'This agent is not available for a call',
39
+ 'call-unavailable': 'That call is not ringing any more',
39
40
  'invalid-request': 'The call could not be started',
40
41
  'resume-unavailable': 'The call could not be picked up again — start a new one',
41
42
  'realtime-unavailable': 'Voice is not available right now — try again later',
@@ -87,6 +87,8 @@ export interface VoiceCallOptions {
87
87
  readonly getAppAssertion?: () => Promise<string | null>;
88
88
  readonly conversationId: string;
89
89
  readonly agentId?: string;
90
+ /** The ringing call from the gemie that this call answers (`@gemies/sdk/calls`). */
91
+ readonly callId?: string;
90
92
  readonly voice: ProductVoice;
91
93
  /** BCP-47. */
92
94
  readonly locale: string;
@@ -376,6 +378,7 @@ export class VoiceCall {
376
378
  protocol: VOICE_PROTOCOL_VERSION,
377
379
  conversationId: this.options.conversationId,
378
380
  ...(this.options.agentId === undefined ? {} : { agentId: this.options.agentId }),
381
+ ...(this.options.callId === undefined ? {} : { callId: this.options.callId }),
379
382
  voice: this.options.voice,
380
383
  locale: this.options.locale,
381
384
  });
@@ -417,6 +420,8 @@ export class VoiceCall {
417
420
  case 'transcript.done':
418
421
  this.upsertMessage(event, () => event.text, false);
419
422
  return;
423
+ // Playback, not this event, is what moves the state to `speaking`.
424
+ case 'assistant.speaking':
420
425
  case 'assistant.audio_done':
421
426
  return;
422
427
  case 'assistant.done':
@@ -41,6 +41,7 @@ export type VoiceServerErrorCode =
41
41
  | 'plan-required'
42
42
  | 'credits-exhausted'
43
43
  | 'agent-unavailable'
44
+ | 'call-unavailable'
44
45
  | 'invalid-request'
45
46
  | 'resume-unavailable'
46
47
  | 'realtime-unavailable'
@@ -54,6 +55,7 @@ const SERVER_ERROR_CODES: ReadonlySet<string> = new Set<VoiceServerErrorCode>([
54
55
  'plan-required',
55
56
  'credits-exhausted',
56
57
  'agent-unavailable',
58
+ 'call-unavailable',
57
59
  'invalid-request',
58
60
  'resume-unavailable',
59
61
  'realtime-unavailable',
@@ -94,6 +96,8 @@ export type VoiceClientEvent =
94
96
  agentId?: string;
95
97
  voice: ProductVoice;
96
98
  locale: string;
99
+ /** Answer this ringing call from a gemie (`@gemies/sdk/calls`). */
100
+ callId?: string;
97
101
  }
98
102
  | { type: 'session.resume'; protocol: number; voiceSessionId: string; afterSeq: number }
99
103
  | { type: 'playback.interrupted'; itemId: string; playedMs: number }
@@ -118,6 +122,7 @@ export type VoiceServerEvent =
118
122
  */
119
123
  | { type: 'transcript.delta'; role: VoiceRole; messageId: string; itemId: string; text: string }
120
124
  | { type: 'transcript.done'; role: VoiceRole; messageId: string; itemId: string; text: string }
125
+ | { type: 'assistant.speaking'; itemId: string }
121
126
  | { type: 'assistant.audio_done'; itemId: string }
122
127
  | {
123
128
  type: 'assistant.done';
@@ -137,7 +142,8 @@ export type VoiceServerEvent =
137
142
  retryable: boolean;
138
143
  reference: string;
139
144
  }
140
- | { type: 'session.closed'; reason: VoiceCloseReason };
145
+ /** `endedBy: 'gemie'`: the gemie hung up. */
146
+ | { type: 'session.closed'; reason: VoiceCloseReason; endedBy?: 'gemie' };
141
147
 
142
148
  /** A server event as received: numbered once a session exists. */
143
149
  export type ReceivedVoiceEvent = VoiceServerEvent & { seq?: number };
@@ -199,6 +205,7 @@ export function parseVoiceServerEvent(raw: string): ReceivedVoiceEvent | null {
199
205
  }
200
206
  case 'user.speech_started':
201
207
  case 'user.speech_stopped':
208
+ case 'assistant.speaking':
202
209
  case 'assistant.audio_done':
203
210
  return isString(event.itemId) ? { type: event.type, itemId: event.itemId, ...seq } : null;
204
211
  case 'transcript.delta':
@@ -288,6 +295,7 @@ export function parseVoiceServerEvent(raw: string): ReceivedVoiceEvent | null {
288
295
  isString(event.reason) && CLOSE_REASONS.has(event.reason)
289
296
  ? (event.reason as VoiceCloseReason)
290
297
  : 'error',
298
+ ...(event.endedBy === 'gemie' ? { endedBy: 'gemie' as const } : {}),
291
299
  ...seq,
292
300
  };
293
301
  default:
@@ -6,6 +6,7 @@
6
6
  * Pure data: no React, no socket, so a test on either side can import it.
7
7
  */
8
8
 
9
+ import type { CallEventData } from '../calls';
9
10
  import type { Message } from '../runtime/types';
10
11
 
11
12
  /** The one server → client event. */
@@ -32,6 +33,7 @@ export const REALTIME_DURABLE_TYPES = [
32
33
  'notification',
33
34
  'connections',
34
35
  'collections',
36
+ 'call',
35
37
  ] as const;
36
38
 
37
39
  /** Signals: only true while they happen, never replayed. */
@@ -143,6 +145,8 @@ export interface RealtimeData {
143
145
  notification: { readonly notification: Record<string, unknown> & { readonly id: string } };
144
146
  connections: Record<string, never>;
145
147
  collections: CollectionsSnapshotWire;
148
+ /** A gemie's call rang, was answered or declined, or ended (`@gemies/sdk/calls`). */
149
+ call: CallEventData;
146
150
  activity: RealtimeActivity;
147
151
  room: {
148
152
  readonly conversationId: string;
@@ -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';
@@ -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
+ }