@gemies/sdk 10.3.0 → 10.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # @gemies/sdk
2
2
 
3
+ ## 10.4.0
4
+
5
+ ### Richer answers to a coding CLI's permission questions
6
+
7
+ A coding CLI (ADR 0043 §5) asks to run something on the person's computer and the turn waits. The
8
+ question now offers more than allow and deny, and shows in two places that answer together.
9
+
10
+ - **Decisions.** `ApprovalDecision` is `allow`, `allow_session` (this tool on this exact path or
11
+ URL, for the rest of the conversation's session; offered only where the server can scope it, so
12
+ not for shell commands today), `deny` and `cancel` (deny, and stop the turn).
13
+ A denial can carry `feedback`, words the agent is told. When the agent supplies its own options
14
+ (`ApprovalOption`), their ids and labels are shown and sent back unchanged (`optionId`); the
15
+ built-in ones are named in English and Spanish (`chat.approval.option.*`). Every question can be
16
+ declined.
17
+ - **In the thread and above the composer.** The timeline's card lists the answers; the composer docks
18
+ a compact `ApprovalBar` (who is waiting, what they would run, the answers), and on web `Y` approves,
19
+ `A` allows for the session and `N` declines, once per press, only on the chat on screen and except
20
+ while typing. Both answer through
21
+ one `useApprovalActions`, so an answer is sent once however many places show the question.
22
+ - **A reply declines.** While a question waits, text typed in the composer and sent declines it and
23
+ goes to the agent as the feedback. The field's placeholder and the bar say so; Stop gives way to
24
+ send while there are words to send, and comes back when there are none.
25
+ - **Nothing stays open.** When a turn ends — answered, stopped, failed, the connection lost — every
26
+ question still waiting is settled (`ended`, or `cancel` when the person stopped it), so no card
27
+ stays pressable for a request nobody waits on. A question answered by the person's earlier
28
+ "allow for this session" reads as such (`auto`).
29
+ - **Host.** `onApprovalDecision(requestId, agentId, decision, details?)` takes the wider decision
30
+ and `{ optionId, feedback }`; it rejects with `ApprovalExpiredError` for a question no longer open
31
+ (a 404, or a 409 for one answered differently elsewhere). New optional `listApprovalGrants` and
32
+ `revokeApprovalGrant` let the thread list what was allowed for the session and take each back;
33
+ without them nothing is listed. A host written against 10.3 keeps compiling and carries the wider
34
+ decisions to Gemies as they are; it forwards no `details` until it takes them.
35
+ - `chat.approval.allow` and `chat.approval.deny` are gone (use `chat.approval.option.allow` and
36
+ `chat.approval.option.deny`); `stillPending` is gone, since a new turn starts with none.
37
+
3
38
  ## 10.3.0
4
39
 
5
40
  ### Chat streams resume after a dropped connection
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gemies/sdk",
3
- "version": "10.3.0",
3
+ "version": "10.4.0",
4
4
  "description": "The Gemies SDK: the conversation runtime, chat UI, voice calls and dictation for Oxy apps that talk to a gemie",
5
5
  "main": "src/index.ts",
6
6
  "react-native": "src/index.ts",
@@ -0,0 +1,131 @@
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 React, { useMemo } from 'react';
5
+ import { Platform, View } from 'react-native';
6
+ import {
7
+ APPROVAL_SHORTCUT_KEYS,
8
+ type ApprovalShortcutActions,
9
+ useApprovalShortcuts,
10
+ } from '../hooks/useApprovalShortcuts';
11
+ import { useLabels } from '../lib/labels';
12
+ import {
13
+ approvalOptionLabel,
14
+ optionOfKind,
15
+ orderedApprovalOptions,
16
+ type ApprovalDecision,
17
+ } from '../runtime/approvals';
18
+ import type { ApprovalActions } from '../runtime/use-approval-actions';
19
+
20
+ const SHORTCUT_OF: Partial<Record<ApprovalDecision, string>> = {
21
+ allow: APPROVAL_SHORTCUT_KEYS.approve,
22
+ allow_session: APPROVAL_SHORTCUT_KEYS.approveForSession,
23
+ deny: APPROVAL_SHORTCUT_KEYS.decline,
24
+ };
25
+
26
+ /**
27
+ * The CLI's question, compact, above the composer where the person is about to type (ADR 0043 §5):
28
+ * who asks and what it would run, the answers, and — said plainly — that writing a reply below
29
+ * declines it and tells the agent why. On web the keys answer too (`useApprovalShortcuts`).
30
+ *
31
+ * The thread shows the same question as a card in the timeline; both answer through the same
32
+ * actions, so one answered here is answered there.
33
+ */
34
+ export const ApprovalBar = React.memo(function ApprovalBar({
35
+ approvals,
36
+ isFocused = true,
37
+ }: {
38
+ approvals: ApprovalActions;
39
+ /** False for a chat kept mounted under another screen: it must not hear the keyboard. */
40
+ isFocused?: boolean;
41
+ }) {
42
+ const { t } = useLabels();
43
+ const styles = useStyles();
44
+ const { pending: entry, decide, sending, failed, canAnswer } = approvals;
45
+ const busy = entry !== undefined && sending.has(entry.requestId);
46
+
47
+ const shortcuts = useMemo<ApprovalShortcutActions | undefined>(() => {
48
+ if (!entry || !canAnswer || busy || !isFocused) return undefined;
49
+ const answer = (kind: ApprovalDecision) => {
50
+ const option = optionOfKind(entry, kind);
51
+ return option ? () => void decide(entry, kind, { optionId: option.id }) : undefined;
52
+ };
53
+ return {
54
+ approve: answer('allow'),
55
+ approveForSession: answer('allow_session'),
56
+ // The way out is a no: declining, or stopping when that is all the question offers.
57
+ decline: answer('deny') ?? answer('cancel'),
58
+ };
59
+ }, [entry, canAnswer, busy, decide, isFocused]);
60
+ useApprovalShortcuts(shortcuts);
61
+
62
+ if (!entry) return null;
63
+ const waiting = approvals.entries.filter((e) => e.outcome === 'pending').length;
64
+ const hasKeys = Platform.OS === 'web' && isFocused;
65
+
66
+ return (
67
+ <View
68
+ style={styles.bar}
69
+ accessibilityRole="alert"
70
+ accessibilityLiveRegion="polite"
71
+ aria-live="polite"
72
+ >
73
+ <View style={styles.text}>
74
+ <Text style={styles.title} numberOfLines={1}>
75
+ {t('chat.approval.bar.title', { agent: approvals.agentName, tool: entry.tool })}
76
+ {waiting > 1 ? ` · ${t('chat.approval.bar.more', { count: waiting - 1 })}` : ''}
77
+ </Text>
78
+ {entry.summary ? (
79
+ <Text style={styles.summary} numberOfLines={2}>
80
+ {entry.summary}
81
+ </Text>
82
+ ) : null}
83
+ <Text style={styles.hint}>
84
+ {failed.has(entry.requestId)
85
+ ? t('chat.approval.sendFailed')
86
+ : t('chat.approval.bar.replyHint', { agent: approvals.agentName })}
87
+ </Text>
88
+ </View>
89
+ {canAnswer && !busy ? (
90
+ <View style={styles.actions}>
91
+ {orderedApprovalOptions(entry.options).map((option) => (
92
+ <Button
93
+ key={option.id}
94
+ size="xs"
95
+ appearance={option.kind === 'allow' ? 'solid' : 'subtle'}
96
+ tone={option.kind === 'cancel' ? 'danger' : undefined}
97
+ onPress={() => void decide(entry, option.kind, { optionId: option.id })}
98
+ trailing={
99
+ hasKeys && SHORTCUT_OF[option.kind] && option.label === undefined ? (
100
+ <Text style={styles.key}>{SHORTCUT_OF[option.kind]}</Text>
101
+ ) : undefined
102
+ }
103
+ >
104
+ {approvalOptionLabel(option, t)}
105
+ </Button>
106
+ ))}
107
+ </View>
108
+ ) : null}
109
+ </View>
110
+ );
111
+ });
112
+
113
+ const useStyles = createTokenStyles((t) => ({
114
+ bar: {
115
+ flexDirection: 'row',
116
+ flexWrap: 'wrap',
117
+ alignItems: 'center',
118
+ gap: 8,
119
+ marginBottom: 8,
120
+ paddingHorizontal: 12,
121
+ paddingVertical: 8,
122
+ borderRadius: 16,
123
+ backgroundColor: t.popover,
124
+ },
125
+ text: { flexGrow: 1, flexShrink: 1, flexBasis: 200, gap: 2 },
126
+ title: { fontSize: 14, fontWeight: 600, color: t.foreground, lineHeight: 20 },
127
+ summary: { fontSize: 13, color: t.foreground, lineHeight: 18, fontFamily: 'monospace' },
128
+ hint: { fontSize: 12, color: t.mutedForeground, lineHeight: 16 },
129
+ actions: { flexDirection: 'row', flexWrap: 'wrap', gap: 6 },
130
+ key: { fontSize: 11, color: t.mutedForeground, lineHeight: 14 },
131
+ }));
@@ -1,4 +1,7 @@
1
1
  import { useConversationActionApprovals } from '../runtime/action-approvals';
2
+ import { optionOfKind } from '../runtime/approvals';
3
+ import { useApprovalActions } from '../runtime/use-approval-actions';
4
+ import { ApprovalBar } from './ApprovalBar';
2
5
  /**
3
6
  * The conversation: header, thread and composer, with its voice call. The one screen of the
4
7
  * bottom sheet, `GemieChatScreen` and the Alia app — they are frames around this.
@@ -422,7 +425,7 @@ function GemieConversationView({
422
425
  suggestedNewConversation,
423
426
  dismissSuggestedNewConversation,
424
427
  agentRun,
425
- approvals,
428
+ approvals: approvalEntries,
426
429
  settleApproval,
427
430
  failedTurn,
428
431
  retryFailedTurn,
@@ -664,20 +667,43 @@ function GemieConversationView({
664
667
  );
665
668
 
666
669
  // A coding CLI's question to its own user (ADR 0043 §5): the host carries the answer to Gemies.
670
+ // The thread's card and the composer's bar answer through the same actions.
667
671
  const decideApproval = runtime.host.onApprovalDecision;
668
- const approvalCards = useMemo(
669
- () => ({
670
- entries: approvals,
671
- agentName: lead.name,
672
- onDecide:
673
- decideApproval === undefined
674
- ? undefined
675
- : (entry: (typeof approvals)[number], decision: 'allow' | 'deny') =>
676
- decideApproval(entry.requestId, entry.agentId, decision),
677
- onSettled: settleApproval,
678
- }),
679
- [approvals, lead.name, decideApproval, settleApproval],
680
- );
672
+ const stopTurn = useCallback(() => void stop(), [stop]);
673
+ const approvals = useApprovalActions({
674
+ entries: approvalEntries,
675
+ agentName: lead.name,
676
+ onDecide:
677
+ decideApproval === undefined
678
+ ? undefined
679
+ : (entry, decision, details) =>
680
+ decideApproval(entry.requestId, entry.agentId, decision, details),
681
+ onSettled: settleApproval,
682
+ onStopTurn: stopTurn,
683
+ grants: {
684
+ agentId,
685
+ conversationId,
686
+ list: runtime.host.listApprovalGrants,
687
+ revoke: runtime.host.revokeApprovalGrant,
688
+ },
689
+ });
690
+ // While a question waits, a reply typed in the composer is the answer: it declines the request
691
+ // and the words go to the agent. The composer says so, and sends instead of stopping.
692
+ const decliningOption =
693
+ approvals.canAnswer && approvals.pending !== undefined
694
+ ? optionOfKind(approvals.pending, 'deny')
695
+ : undefined;
696
+ const replyDeclines = decliningOption !== undefined && composer.text.trim() !== '';
697
+ const submitReply = useCallback(async () => {
698
+ const entry = approvals.pending;
699
+ const words = composer.text.trim();
700
+ if (!entry || !decliningOption || words === '') return;
701
+ const sent = await approvals.decide(entry, 'deny', {
702
+ optionId: decliningOption.id,
703
+ feedback: words,
704
+ });
705
+ if (sent) composer.setText('');
706
+ }, [approvals, composer, decliningOption]);
681
707
 
682
708
  // ── The chrome ──
683
709
  const latestMessages = useRef(messages);
@@ -760,8 +786,14 @@ function GemieConversationView({
760
786
  }}
761
787
  value={composer.text}
762
788
  onValueChange={composer.setText}
763
- onSubmit={() => void composer.submit(composer.text)}
764
- busy={isLoading}
789
+ onSubmit={() => void (replyDeclines ? submitReply() : composer.submit(composer.text))}
790
+ // Stop gives way to send while a reply would decline the question the agent waits on.
791
+ busy={isLoading && !replyDeclines}
792
+ approval={
793
+ approvals.pending === undefined ? undefined : (
794
+ <ApprovalBar approvals={approvals} isFocused={isFocused} />
795
+ )
796
+ }
765
797
  loaderPhase={composerPhase}
766
798
  disabled={closed || loading}
767
799
  onStop={stop}
@@ -778,9 +810,11 @@ function GemieConversationView({
778
810
  ? t('usageLimit.inputDisabledPlaceholder')
779
811
  : editing !== undefined
780
812
  ? t('composer.editPlaceholder')
781
- : group === undefined
782
- ? labels.placeholder(lead.name)
783
- : t('chat.groupPlaceholder')
813
+ : approvals.pending !== undefined && decliningOption !== undefined
814
+ ? t('chat.approval.replyPlaceholder', { agent: lead.name })
815
+ : group === undefined
816
+ ? labels.placeholder(lead.name)
817
+ : t('chat.groupPlaceholder')
784
818
  }
785
819
  status={status}
786
820
  // The mode selector is the power level: how much power this turn gets.
@@ -835,7 +869,7 @@ function GemieConversationView({
835
869
  onRegenerate={composer.regenerate}
836
870
  onStartEdit={edit.start}
837
871
  newConversationOffer={newConversationOffer}
838
- approvals={approvalCards}
872
+ approvals={approvals}
839
873
  actionApprovals={showsPast ? undefined : actionApprovals}
840
874
  agentActivity={agentRun === null ? null : agentActivity}
841
875
  call={voice.isActive ? { agentState: voice.agentState } : undefined}
@@ -106,6 +106,11 @@ export interface GemieComposerProps<T extends GemieSuggestion = GemieSuggestion>
106
106
  suggestions?: GemieComposerSuggestions<T>;
107
107
  /** What Alia is waiting on, docked above the composer. */
108
108
  questions?: GemieComposerQuestions;
109
+ /**
110
+ * A coding CLI's permission question (`ApprovalBar`), docked above the composer beside the
111
+ * questions: where the person is about to type the reply that declines it.
112
+ */
113
+ approval?: ReactNode;
109
114
  /** The tab on the card's top edge (`ComposerPanelStatusTab`). */
110
115
  status?: ReactNode;
111
116
  /** Drawn where send would be while there is nothing to send (voice mode). */
@@ -151,6 +156,7 @@ function GemieComposerBody<T extends GemieSuggestion>({
151
156
  attachmentKinds,
152
157
  suggestions,
153
158
  questions,
159
+ approval,
154
160
  status,
155
161
  emptyAction,
156
162
  accessory,
@@ -301,6 +307,7 @@ function GemieComposerBody<T extends GemieSuggestion>({
301
307
  {labels.dictationRemaining(remainingSeconds)}
302
308
  </Text>
303
309
  ) : null}
310
+ {approval}
304
311
  {questions && questions.items.length > 0 ? (
305
312
  // Beside the loader, not through the pill's `question` slot: the light traces the box it
306
313
  // wraps, so a question inside it would be ringed too.
@@ -1,111 +1,79 @@
1
+ import { Button } from '@oxy.so/bloom/button';
1
2
  import { Notification } from '@oxy.so/bloom/notification';
2
3
  import { Muted } from '@oxy.so/bloom/typography';
3
- import React, { useCallback, useState } from 'react';
4
+ import React from 'react';
4
5
  import { StyleSheet, View } from 'react-native';
5
6
  import { useLabels } from '../../lib/labels';
6
7
  import {
7
- ApprovalExpiredError,
8
- type ApprovalDecision,
8
+ approvalOptionLabel,
9
+ orderedApprovalOptions,
9
10
  type ApprovalEntry,
10
- type ApprovalOutcome,
11
+ type ApprovalGrant,
11
12
  } from '../../runtime/approvals';
12
-
13
- export interface ApprovalsProps {
14
- readonly entries: readonly ApprovalEntry[];
15
- /** Who is asking: the agent's name, as the thread names it. */
16
- readonly agentName: string;
17
- /**
18
- * Carries the person's answer to Gemies. Rejects with `ApprovalExpiredError` when the question is
19
- * no longer open. Omitted, a question is shown with no way to answer it.
20
- */
21
- readonly onDecide?: (entry: ApprovalEntry, decision: ApprovalDecision) => Promise<void>;
22
- /** The answer is known here (the person's own, or the question closed): show it now. */
23
- readonly onSettled: (requestId: string, outcome: ApprovalOutcome) => void;
24
- }
13
+ import type { ApprovalActions } from '../../runtime/use-approval-actions';
25
14
 
26
15
  /**
27
16
  * A coding CLI asking its own user for permission to run something on their computer, in the
28
- * conversation (Gemies ADR 0043 §5): who is asking, what for, and the two answers. The CLI waits
29
- * for the person; once answered the card shrinks to one line saying how it ended.
17
+ * conversation (Gemies ADR 0043 §5): who is asking, what for, and the answers it offers. The CLI
18
+ * waits for the person; once answered the card shrinks to one line saying how it ended.
30
19
  *
31
- * This is the CLI's prompt to the person who runs it, not a permission Gemies or Oxy asks for.
20
+ * This is the CLI's prompt to the person who runs it, not a permission Gemies or Oxy asks for. The
21
+ * composer shows the same question in a compact bar; both answer through the same actions, so a
22
+ * question answered in one is answered in both.
32
23
  */
33
24
  export const ApprovalCards = React.memo(function ApprovalCards({
34
- entries,
35
- agentName,
36
- onDecide,
37
- onSettled,
38
- }: ApprovalsProps) {
25
+ approvals,
26
+ }: {
27
+ approvals: ApprovalActions;
28
+ }) {
39
29
  return (
40
30
  <>
41
- {entries.map((entry) => (
42
- <ApprovalCard
43
- key={entry.requestId}
44
- entry={entry}
45
- agentName={agentName}
46
- onDecide={onDecide}
47
- onSettled={onSettled}
48
- />
31
+ {approvals.entries.map((entry) => (
32
+ <ApprovalCard key={entry.requestId} entry={entry} approvals={approvals} />
33
+ ))}
34
+ {approvals.grants.map((grant) => (
35
+ <ApprovalGrantRow key={grant.id} grant={grant} approvals={approvals} />
49
36
  ))}
50
37
  </>
51
38
  );
52
39
  });
53
40
 
54
- function ApprovalCard({
55
- entry,
56
- agentName,
57
- onDecide,
58
- onSettled,
59
- }: {
60
- entry: ApprovalEntry;
61
- agentName: string;
62
- onDecide: ApprovalsProps['onDecide'];
63
- onSettled: ApprovalsProps['onSettled'];
64
- }) {
41
+ function ApprovalCard({ entry, approvals }: { entry: ApprovalEntry; approvals: ApprovalActions }) {
65
42
  const { t } = useLabels();
66
- const [sending, setSending] = useState(false);
67
- const [failed, setFailed] = useState(false);
68
-
69
- const decide = useCallback(
70
- (decision: ApprovalDecision) => {
71
- if (sending || !onDecide) return;
72
- setSending(true);
73
- setFailed(false);
74
- onDecide(entry, decision).then(
75
- () => onSettled(entry.requestId, decision),
76
- (error: unknown) => {
77
- setSending(false);
78
- if (error instanceof ApprovalExpiredError) onSettled(entry.requestId, 'expired');
79
- else setFailed(true);
80
- },
81
- );
82
- },
83
- [sending, onDecide, entry, onSettled],
84
- );
85
43
 
86
44
  if (entry.outcome !== 'pending') {
45
+ const line = t(
46
+ entry.auto ? 'chat.approval.resolved.auto' : `chat.approval.resolved.${entry.outcome}`,
47
+ { tool: entry.tool },
48
+ );
87
49
  return (
88
50
  <View style={styles.resolved} accessibilityRole="text">
89
- <Muted>{t(`chat.approval.resolved.${entry.outcome}`, { tool: entry.tool })}</Muted>
51
+ <Muted>{entry.feedback ? `${line} · “${entry.feedback}”` : line}</Muted>
90
52
  </View>
91
53
  );
92
54
  }
93
55
 
94
- const description = [entry.summary, failed ? t('chat.approval.sendFailed') : undefined]
56
+ const description = [
57
+ entry.summary,
58
+ approvals.failed.has(entry.requestId) ? t('chat.approval.sendFailed') : undefined,
59
+ ]
95
60
  .filter(Boolean)
96
61
  .join('\n');
62
+ const sending = approvals.sending.has(entry.requestId);
97
63
  return (
98
64
  <Notification
99
65
  status="warning"
100
- title={t('chat.approval.title', { agent: agentName, tool: entry.tool })}
66
+ title={t('chat.approval.title', { agent: approvals.agentName, tool: entry.tool })}
101
67
  description={description === '' ? undefined : description}
102
68
  // While an answer is on its way there is nothing to press: a second tap must not send another.
103
69
  actions={
104
- onDecide && !sending
105
- ? [
106
- { label: t('chat.approval.deny'), onPress: () => decide('deny') },
107
- { label: t('chat.approval.allow'), onPress: () => decide('allow') },
108
- ]
70
+ approvals.canAnswer && !sending
71
+ ? orderedApprovalOptions(entry.options).map((option) => ({
72
+ label: approvalOptionLabel(option, t),
73
+ onPress: () => void approvals.decide(entry, option.kind, { optionId: option.id }),
74
+ ...(option.kind === 'allow' ? {} : { appearance: 'subtle' as const }),
75
+ ...(option.kind === 'cancel' ? { tone: 'danger' as const } : {}),
76
+ }))
109
77
  : undefined
110
78
  }
111
79
  dismissible={false}
@@ -113,6 +81,40 @@ function ApprovalCard({
113
81
  );
114
82
  }
115
83
 
84
+ /** What the person allowed for the session, with the way to take it back. */
85
+ function ApprovalGrantRow({
86
+ grant,
87
+ approvals,
88
+ }: {
89
+ grant: ApprovalGrant;
90
+ approvals: ApprovalActions;
91
+ }) {
92
+ const { t } = useLabels();
93
+ return (
94
+ <View style={styles.grant}>
95
+ <Muted style={styles.grantText} numberOfLines={1}>
96
+ {`${t('chat.approval.grant', { tool: grant.tool })}: ${grant.target}`}
97
+ </Muted>
98
+ <Button
99
+ size="xs"
100
+ appearance="plain"
101
+ tone="neutral"
102
+ onPress={() => void approvals.revokeGrant(grant.id)}
103
+ >
104
+ {t('chat.approval.revoke')}
105
+ </Button>
106
+ </View>
107
+ );
108
+ }
109
+
116
110
  const styles = StyleSheet.create({
117
111
  resolved: { paddingHorizontal: 16, paddingVertical: 4 },
112
+ grant: {
113
+ flexDirection: 'row',
114
+ alignItems: 'center',
115
+ gap: 8,
116
+ paddingHorizontal: 16,
117
+ paddingVertical: 2,
118
+ },
119
+ grantText: { flexShrink: 1 },
118
120
  });
@@ -36,7 +36,8 @@ import type { ThreadHistory } from '../../runtime/thread/thread-history';
36
36
  import type { AgentState } from '../../types';
37
37
  import { AgentResultCard } from './AgentResultCard';
38
38
  import { AgentTaskCard } from './AgentTaskCard';
39
- import { type ApprovalsProps, ApprovalCards } from './ApprovalCard';
39
+ import type { ApprovalActions } from '../../runtime/use-approval-actions';
40
+ import { ApprovalCards } from './ApprovalCard';
40
41
  import { NewConversationOffer } from './NewConversationOffer';
41
42
  import { type ThreadActions, ThreadRow } from './ThreadRow';
42
43
 
@@ -90,7 +91,7 @@ export interface GemieThreadProps {
90
91
  * A coding CLI asking its own user for permission to run something on their computer, while the
91
92
  * turn waits (ADR 0043 §5). Drawn after the turns, where the person is looking.
92
93
  */
93
- approvals?: ApprovalsProps;
94
+ approvals?: ApprovalActions;
94
95
  actionApprovals?: ConversationActionApprovals;
95
96
  /** The run an agent is on for this conversation: in progress, or the card it leaves. */
96
97
  agentActivity?: AgentActivityState | null;
@@ -404,7 +405,7 @@ export const GemieThread = memo(function GemieThread({
404
405
  ) : null}
405
406
 
406
407
  {approvals === undefined || approvals.entries.length === 0 ? null : (
407
- <ApprovalCards {...approvals} />
408
+ <ApprovalCards approvals={approvals} />
408
409
  )}
409
410
 
410
411
  {/* The agent's offer to start the next stretch fresh. Last in the list on purpose: it
@@ -0,0 +1,93 @@
1
+ import { useEffect } from 'react';
2
+ import { Platform } from 'react-native';
3
+
4
+ /** What a shortcut does; each is absent when the question does not offer it. */
5
+ export interface ApprovalShortcutActions {
6
+ readonly approve?: () => void;
7
+ readonly approveForSession?: () => void;
8
+ readonly decline?: () => void;
9
+ }
10
+
11
+ /** The key that does each thing, so the buttons can name it. */
12
+ export const APPROVAL_SHORTCUT_KEYS = {
13
+ approve: 'Y',
14
+ approveForSession: 'A',
15
+ decline: 'N',
16
+ } as const;
17
+
18
+ /** The part of a key event the shortcuts read. */
19
+ export interface ShortcutKeyEvent {
20
+ readonly key: string;
21
+ readonly ctrlKey?: boolean;
22
+ readonly metaKey?: boolean;
23
+ readonly altKey?: boolean;
24
+ readonly shiftKey?: boolean;
25
+ readonly isComposing?: boolean;
26
+ /** The key is being held down. */
27
+ readonly repeat?: boolean;
28
+ readonly defaultPrevented?: boolean;
29
+ readonly target?: unknown;
30
+ preventDefault?: () => void;
31
+ }
32
+
33
+ /** Whether keys typed here are text: a field, or anything the person can edit. */
34
+ function isEditing(target: unknown): boolean {
35
+ const el = target as { tagName?: string; isContentEditable?: boolean } | null;
36
+ if (el === null || typeof el !== 'object') return false;
37
+ const tag = el.tagName?.toLowerCase();
38
+ return tag === 'input' || tag === 'textarea' || tag === 'select' || el.isContentEditable === true;
39
+ }
40
+
41
+ /**
42
+ * What a key does to the question: `Y` approves it once, `A` allows it for the session, `N`
43
+ * declines it. Only a bare key pressed once counts — a held key must not answer the next question
44
+ * too — and not while the person is typing: the composer is where they write the reply that
45
+ * declines with feedback, and its letters are theirs. `Escape` is left alone: it closes whatever
46
+ * is open over the chat, and closing something must not decline a request.
47
+ */
48
+ export function approvalShortcut(
49
+ event: ShortcutKeyEvent,
50
+ actions: ApprovalShortcutActions,
51
+ ): (() => void) | undefined {
52
+ if (event.defaultPrevented || event.isComposing || event.repeat) return undefined;
53
+ if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return undefined;
54
+ if (isEditing(event.target)) return undefined;
55
+ switch (event.key) {
56
+ case 'y':
57
+ case 'Y':
58
+ return actions.approve;
59
+ case 'a':
60
+ case 'A':
61
+ return actions.approveForSession;
62
+ case 'n':
63
+ case 'N':
64
+ return actions.decline;
65
+ default:
66
+ return undefined;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * The keyboard shortcuts of the question the composer's bar shows, on web (there is no keyboard to
72
+ * speak of elsewhere). `target` is where keys are heard: the document, unless a test brings its own.
73
+ */
74
+ export function useApprovalShortcuts(
75
+ actions: ApprovalShortcutActions | undefined,
76
+ target:
77
+ | Pick<EventTarget, 'addEventListener' | 'removeEventListener'>
78
+ | undefined = Platform.OS === 'web'
79
+ ? (globalThis as { document?: Document }).document
80
+ : undefined,
81
+ ): void {
82
+ useEffect(() => {
83
+ if (actions === undefined || target === undefined) return;
84
+ const onKeyDown = (event: Event) => {
85
+ const run = approvalShortcut(event as unknown as ShortcutKeyEvent, actions);
86
+ if (run === undefined) return;
87
+ (event as unknown as ShortcutKeyEvent).preventDefault?.();
88
+ run();
89
+ };
90
+ target.addEventListener('keydown', onKeyDown);
91
+ return () => target.removeEventListener('keydown', onKeyDown);
92
+ }, [actions, target]);
93
+ }
@@ -125,11 +125,23 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
125
125
  'chat.actionApproval.status.expired': 'Expired',
126
126
  'chat.actionApproval.sent': 'Sent',
127
127
  'chat.actionApproval.decisionFailed': 'Your decision couldn’t be saved. Try again.',
128
- 'chat.approval.allow': 'Allow',
129
- 'chat.approval.deny': 'Deny',
130
- 'chat.approval.resolved.allow': '%{tool}: allowed',
131
- 'chat.approval.resolved.deny': '%{tool}: denied',
128
+ 'chat.approval.bar.more': '%{count} more waiting',
129
+ 'chat.approval.bar.replyHint': 'Reply below to decline and tell %{agent} why.',
130
+ 'chat.approval.bar.title': '%{agent} is waiting to run %{tool}',
131
+ 'chat.approval.grant': 'Allowed for this session — %{tool}',
132
+ 'chat.approval.option.allow': 'Approve',
133
+ 'chat.approval.option.allow_session': 'Always allow this session',
134
+ 'chat.approval.option.cancel': 'Stop',
135
+ 'chat.approval.option.deny': 'Decline',
136
+ 'chat.approval.replyPlaceholder': 'Decline and tell %{agent} why…',
137
+ 'chat.approval.resolved.allow': '%{tool}: approved',
138
+ 'chat.approval.resolved.allow_session': '%{tool}: allowed for this session',
139
+ 'chat.approval.resolved.auto': '%{tool}: allowed, as you did for this session',
140
+ 'chat.approval.resolved.cancel': '%{tool}: stopped',
141
+ 'chat.approval.resolved.deny': '%{tool}: declined',
142
+ 'chat.approval.resolved.ended': '%{tool}: closed with the turn',
132
143
  'chat.approval.resolved.expired': '%{tool}: timed out',
144
+ 'chat.approval.revoke': 'Revoke',
133
145
  'chat.approval.sendFailed': "Your answer couldn't be sent. Try again.",
134
146
  'chat.approval.title': '%{agent} wants to run %{tool}',
135
147
  'chat.newConversationAccept': 'Start a new one',
@@ -124,11 +124,23 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
124
124
  'chat.actionApproval.status.expired': 'Caducado',
125
125
  'chat.actionApproval.sent': 'Enviado',
126
126
  'chat.actionApproval.decisionFailed': 'Tu decisión no se pudo guardar. Inténtalo de nuevo.',
127
- 'chat.approval.allow': 'Permitir',
128
- 'chat.approval.deny': 'Denegar',
129
- 'chat.approval.resolved.allow': '%{tool}: permitido',
130
- 'chat.approval.resolved.deny': '%{tool}: denegado',
127
+ 'chat.approval.bar.more': '%{count} más esperando',
128
+ 'chat.approval.bar.replyHint': 'Responde abajo para rechazar y decirle a %{agent} por qué.',
129
+ 'chat.approval.bar.title': '%{agent} espera para ejecutar %{tool}',
130
+ 'chat.approval.grant': 'Permitido en esta sesión — %{tool}',
131
+ 'chat.approval.option.allow': 'Aprobar',
132
+ 'chat.approval.option.allow_session': 'Permitir siempre en esta sesión',
133
+ 'chat.approval.option.cancel': 'Detener',
134
+ 'chat.approval.option.deny': 'Rechazar',
135
+ 'chat.approval.replyPlaceholder': 'Rechaza y dile a %{agent} por qué…',
136
+ 'chat.approval.resolved.allow': '%{tool}: aprobado',
137
+ 'chat.approval.resolved.allow_session': '%{tool}: permitido en esta sesión',
138
+ 'chat.approval.resolved.auto': '%{tool}: permitido, como indicaste para esta sesión',
139
+ 'chat.approval.resolved.cancel': '%{tool}: detenido',
140
+ 'chat.approval.resolved.deny': '%{tool}: rechazado',
141
+ 'chat.approval.resolved.ended': '%{tool}: cerrado con el turno',
131
142
  'chat.approval.resolved.expired': '%{tool}: sin respuesta a tiempo',
143
+ 'chat.approval.revoke': 'Revocar',
132
144
  'chat.approval.sendFailed': 'No se pudo enviar tu respuesta. Inténtalo de nuevo.',
133
145
  'chat.approval.title': '%{agent} quiere ejecutar %{tool}',
134
146
  'chat.newConversationAccept': 'Empezar una nueva',
@@ -4,16 +4,45 @@
4
4
  * During a turn with an external agent (Claude Code on the person's computer), the CLI may stop and
5
5
  * ask whether it can run something there. The turn waits; the stream carries two named events:
6
6
  *
7
- * `alia.cli_permission_request` the CLI asks: which tool, on what.
8
- * `alia.cli_permission_resolved` the answer was given, or the time ran out.
7
+ * `alia.cli_permission_request` the CLI asks: which tool, on what, and the answers it offers.
8
+ * `alia.cli_permission_resolved` the answer was given, or the time ran out, or the turn ended.
9
9
  *
10
10
  * This is the third-party CLI's prompt to the person who runs it, on their own machine. It is not
11
11
  * an Oxy grant: nothing here reaches Oxy, and the SDK does not know the endpoint that carries the
12
12
  * answer — the host does (`GemieRuntimeHost.onApprovalDecision`).
13
13
  */
14
14
 
15
- export type ApprovalDecision = 'allow' | 'deny';
16
- export type ApprovalOutcome = ApprovalDecision | 'expired';
15
+ /**
16
+ * What the person answers with:
17
+ *
18
+ * `allow` this once.
19
+ * `allow_session` this tool on this target for the rest of the conversation's session.
20
+ * `deny` no; with the words the agent is told, when there are any.
21
+ * `cancel` no, and stop the turn.
22
+ */
23
+ export type ApprovalDecision = 'allow' | 'allow_session' | 'deny' | 'cancel';
24
+
25
+ /** How a question ended: an answer, a timeout, or the turn going on (or ending) without one. */
26
+ export type ApprovalOutcome = ApprovalDecision | 'expired' | 'ended';
27
+
28
+ /**
29
+ * One way to answer. `id` and `label` are the agent's own when it offered the option: the label is
30
+ * shown as given and the id goes back as given. A built-in option has no `label`; the thread names
31
+ * it in the person's language.
32
+ */
33
+ export interface ApprovalOption {
34
+ readonly id: string;
35
+ readonly kind: ApprovalDecision;
36
+ readonly label?: string;
37
+ }
38
+
39
+ /** What a host's `onApprovalDecision` carries beside the decision. */
40
+ export interface ApprovalDetails {
41
+ /** The agent's option the person picked; absent for a built-in answer. */
42
+ readonly optionId?: string;
43
+ /** Words for the agent, with a denial. */
44
+ readonly feedback?: string;
45
+ }
17
46
 
18
47
  export interface ApprovalRequest {
19
48
  readonly requestId: string;
@@ -24,16 +53,58 @@ export interface ApprovalRequest {
24
53
  readonly summary?: string;
25
54
  /** ISO time after which the CLI is told no. */
26
55
  readonly expiresAt: string;
56
+ /** What can be answered. Always at least one way to say no. */
57
+ readonly options: readonly ApprovalOption[];
27
58
  }
28
59
 
29
60
  /** A request and where it stands: waiting for the person, or how it ended. */
30
61
  export interface ApprovalEntry extends ApprovalRequest {
31
62
  readonly outcome: 'pending' | ApprovalOutcome;
63
+ /** The person did not answer: their earlier "allow for this session" did. */
64
+ readonly auto?: boolean;
65
+ /** What the person told the agent with a denial, kept to show beside the answer. */
66
+ readonly feedback?: string;
32
67
  }
33
68
 
34
69
  const text = (value: unknown, max: number): string | undefined =>
35
70
  typeof value === 'string' && value !== '' ? value.slice(0, max) : undefined;
36
71
 
72
+ const DECISIONS: readonly ApprovalDecision[] = ['allow', 'allow_session', 'deny', 'cancel'];
73
+ const isDecision = (value: unknown): value is ApprovalDecision =>
74
+ typeof value === 'string' && (DECISIONS as readonly string[]).includes(value);
75
+
76
+ /** What a server that predates the options offers: a yes and a no. */
77
+ export const DEFAULT_APPROVAL_OPTIONS: readonly ApprovalOption[] = [
78
+ { id: 'allow', kind: 'allow' },
79
+ { id: 'deny', kind: 'deny' },
80
+ ];
81
+
82
+ /**
83
+ * The options in a request frame, as given. Ids and labels are the agent's: they are not rewritten,
84
+ * only bounded. An option without a usable id or kind is dropped; a request that is left with no
85
+ * way to say no gets one, so a card never traps the person.
86
+ */
87
+ function parseOptions(raw: unknown): readonly ApprovalOption[] {
88
+ if (!Array.isArray(raw)) return DEFAULT_APPROVAL_OPTIONS;
89
+ const options: ApprovalOption[] = [];
90
+ for (const item of raw.slice(0, 8)) {
91
+ if (item === null || typeof item !== 'object') continue;
92
+ const { id, kind, label } = item as Record<string, unknown>;
93
+ if (typeof id !== 'string' || id === '' || id.length > 80 || !isDecision(kind)) continue;
94
+ if (options.some((o) => o.id === id)) continue;
95
+ const shown = text(label, 80)?.trim();
96
+ options.push({ id, kind, ...(shown ? { label: shown } : {}) });
97
+ }
98
+ if (options.length === 0) return DEFAULT_APPROVAL_OPTIONS;
99
+ if (!options.some((o) => o.kind === 'deny' || o.kind === 'cancel')) {
100
+ options.push({
101
+ id: options.some((o) => o.id === 'deny') ? 'gemies:deny' : 'deny',
102
+ kind: 'deny',
103
+ });
104
+ }
105
+ return options;
106
+ }
107
+
37
108
  /** The request in an `alia.cli_permission_request` frame, or `null` when the frame is not one. */
38
109
  export function parseApprovalRequest(data: unknown): ApprovalRequest | null {
39
110
  if (data === null || typeof data !== 'object') return null;
@@ -46,20 +117,27 @@ export function parseApprovalRequest(data: unknown): ApprovalRequest | null {
46
117
  return null;
47
118
  }
48
119
  const summary = text(d.summary, 200);
49
- return { requestId, agentId, tool, ...(summary ? { summary } : {}), expiresAt };
120
+ return {
121
+ requestId,
122
+ agentId,
123
+ tool,
124
+ ...(summary ? { summary } : {}),
125
+ expiresAt,
126
+ options: parseOptions(d.options),
127
+ };
50
128
  }
51
129
 
52
130
  /** The answer in an `alia.cli_permission_resolved` frame, or `null` when the frame is not one. */
53
131
  export function parseApprovalResolved(
54
132
  data: unknown,
55
- ): { requestId: string; outcome: ApprovalOutcome } | null {
133
+ ): { requestId: string; outcome: ApprovalOutcome; auto: boolean } | null {
56
134
  if (data === null || typeof data !== 'object') return null;
57
135
  const d = data as Record<string, unknown>;
58
136
  const requestId = text(d.requestId, 100);
59
137
  if (!requestId) return null;
60
138
  const decision = d.decision;
61
- if (decision !== 'allow' && decision !== 'deny' && decision !== 'expired') return null;
62
- return { requestId, outcome: decision };
139
+ if (!isDecision(decision) && decision !== 'expired' && decision !== 'ended') return null;
140
+ return { requestId, outcome: decision, auto: d.auto === true };
63
141
  }
64
142
 
65
143
  /** A request arrived: waiting, once. A repeat of one already here changes nothing. */
@@ -76,12 +154,50 @@ export function withApprovalOutcome(
76
154
  list: readonly ApprovalEntry[],
77
155
  requestId: string,
78
156
  outcome: ApprovalOutcome,
157
+ extras: { readonly auto?: boolean; readonly feedback?: string } = {},
79
158
  ): ApprovalEntry[] {
80
159
  return list.map((entry) =>
81
- entry.requestId === requestId && entry.outcome === 'pending' ? { ...entry, outcome } : entry,
160
+ entry.requestId === requestId && entry.outcome === 'pending'
161
+ ? {
162
+ ...entry,
163
+ outcome,
164
+ ...(extras.auto ? { auto: true } : {}),
165
+ ...(extras.feedback ? { feedback: extras.feedback } : {}),
166
+ }
167
+ : entry,
82
168
  );
83
169
  }
84
170
 
171
+ /**
172
+ * Every question still waiting ends as `outcome`. For the moments the stream cannot say it itself
173
+ * — it broke, the person stopped the turn, the conversation changed — so no card stays pressable
174
+ * for a request nobody is waiting on.
175
+ */
176
+ export function settlePending(
177
+ list: readonly ApprovalEntry[],
178
+ outcome: ApprovalOutcome,
179
+ ): ApprovalEntry[] {
180
+ return list.some((entry) => entry.outcome === 'pending')
181
+ ? list.map((entry) => (entry.outcome === 'pending' ? { ...entry, outcome } : entry))
182
+ : [...list];
183
+ }
184
+
185
+ /** What the person is being asked now: the oldest question still waiting, or `undefined`. */
186
+ export const firstPending = (list: readonly ApprovalEntry[]): ApprovalEntry | undefined =>
187
+ list.find((entry) => entry.outcome === 'pending');
188
+
189
+ /**
190
+ * What the person allowed for the rest of a conversation's session: one tool on one path or URL,
191
+ * until `expiresAt` or until they take it back.
192
+ */
193
+ export interface ApprovalGrant {
194
+ readonly id: string;
195
+ readonly tool: string;
196
+ /** The path or URL allowed. */
197
+ readonly target: string;
198
+ readonly expiresAt: string;
199
+ }
200
+
85
201
  /**
86
202
  * What a host's `onApprovalDecision` rejects with when the question is no longer open (answered
87
203
  * elsewhere, or its time ran out): the card then reads "Timed out" instead of offering a retry.
@@ -93,7 +209,28 @@ export class ApprovalExpiredError extends Error {
93
209
  }
94
210
  }
95
211
 
96
- /** What a new turn keeps of the last one's approvals: the ones still waiting. */
97
- export function stillPending(list: readonly ApprovalEntry[]): ApprovalEntry[] {
98
- return list.filter((entry) => entry.outcome === 'pending');
99
- }
212
+ /**
213
+ * The options in the order they are laid out: no on the left, yes on the right, as a pair of
214
+ * buttons reads. Options of one kind keep the agent's own order.
215
+ */
216
+ const LAYOUT_RANK: Record<ApprovalDecision, number> = {
217
+ cancel: 0,
218
+ deny: 1,
219
+ allow_session: 2,
220
+ allow: 3,
221
+ };
222
+ export const orderedApprovalOptions = (options: readonly ApprovalOption[]): ApprovalOption[] =>
223
+ [...options].sort((a, b) => LAYOUT_RANK[a.kind] - LAYOUT_RANK[b.kind]);
224
+
225
+ /**
226
+ * What an option says. The agent's own label is shown exactly as it gave it; a built-in option is
227
+ * named by the person's language (`chat.approval.option.<kind>`).
228
+ */
229
+ export const approvalOptionLabel = (option: ApprovalOption, t: (key: string) => string): string =>
230
+ option.label ?? t(`chat.approval.option.${option.kind}`);
231
+
232
+ /** The option to send for a decision: the first the question offers of that kind. */
233
+ export const optionOfKind = (
234
+ entry: Pick<ApprovalEntry, 'options'>,
235
+ kind: ApprovalDecision,
236
+ ): ApprovalOption | undefined => entry.options.find((o) => o.kind === kind);
@@ -1,5 +1,6 @@
1
1
  import { createContext, type ReactNode, useContext, useMemo } from 'react';
2
2
  import { GEMIES_API_URL } from '../lib/origins';
3
+ import type { ApprovalDecision, ApprovalDetails, ApprovalGrant } from './approvals';
3
4
  import type { AgentRun } from './types';
4
5
  import { GemieRealtimeProvider } from '../realtime/react';
5
6
 
@@ -123,13 +124,24 @@ export interface GemieRuntimeHost {
123
124
  /**
124
125
  * The person answered a coding CLI that asked for permission to run something on their own
125
126
  * computer (`alia.cli_permission_request`, ADR 0043). The host carries the answer to Gemies; the
126
- * promise rejects when it could not be sent. Omitted, the request is shown with no way to answer.
127
+ * promise rejects when it could not be sent, and with `ApprovalExpiredError` when the question is
128
+ * no longer open. `details` carries the agent's own option when the person picked one, and the
129
+ * words that go to the agent with a denial. Omitted, the request is shown with no way to answer.
127
130
  */
128
- onApprovalDecision?: (
131
+ onApprovalDecision?(
129
132
  requestId: string,
130
133
  agentId: string,
131
- decision: 'allow' | 'deny',
132
- ) => Promise<void>;
134
+ decision: ApprovalDecision,
135
+ details?: ApprovalDetails,
136
+ ): Promise<void>;
137
+ /**
138
+ * What the person allowed for the rest of this conversation's session with a coding CLI
139
+ * ("always allow this session"). Read after such an answer, and shown in the thread with a way
140
+ * to take each one back. Omitted, nothing is listed.
141
+ */
142
+ listApprovalGrants?(agentId: string, conversationId: string): Promise<readonly ApprovalGrant[]>;
143
+ /** Takes one allowance back: the next such question is asked again. */
144
+ revokeApprovalGrant?(agentId: string, grantId: string): Promise<void>;
133
145
  /** The agent's row in the host's list, ahead of the server: your line, then her answer. */
134
146
  onTurnPreview?: (agentId: string | null | undefined, text: string) => void;
135
147
  /**
@@ -15,7 +15,15 @@
15
15
 
16
16
  export { GemieRuntimeProvider, useGemieRuntime } from './config';
17
17
  export { ApprovalExpiredError } from './approvals';
18
- export type { ApprovalDecision, ApprovalEntry, ApprovalRequest } from './approvals';
18
+ export type {
19
+ ApprovalDecision,
20
+ ApprovalDetails,
21
+ ApprovalEntry,
22
+ ApprovalGrant,
23
+ ApprovalOption,
24
+ ApprovalOutcome,
25
+ ApprovalRequest,
26
+ } from './approvals';
19
27
  export type {
20
28
  GemieArtifact,
21
29
  GemieRuntimeConfig,
@@ -0,0 +1,162 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import {
3
+ ApprovalExpiredError,
4
+ type ApprovalDecision,
5
+ type ApprovalDetails,
6
+ type ApprovalEntry,
7
+ type ApprovalGrant,
8
+ type ApprovalOutcome,
9
+ firstPending,
10
+ } from './approvals';
11
+
12
+ /** `set` with `id` in it, or without. */
13
+ function mark(set: ReadonlySet<string>, id: string, on: boolean): ReadonlySet<string> {
14
+ const next = new Set(set);
15
+ if (on) next.add(id);
16
+ else next.delete(id);
17
+ return next;
18
+ }
19
+
20
+ /** What the thread and the composer's bar are given to show and answer the questions. */
21
+ export interface ApprovalActions {
22
+ readonly entries: readonly ApprovalEntry[];
23
+ /** Who is asking: the agent's name, as the thread names it. */
24
+ readonly agentName: string;
25
+ /** False when the host cannot carry an answer: a question is shown with nothing to press. */
26
+ readonly canAnswer: boolean;
27
+ /** Questions whose answer is on its way: nothing is offered for them until it arrives. */
28
+ readonly sending: ReadonlySet<string>;
29
+ /** Questions whose answer could not be sent: offered again, with a line saying so. */
30
+ readonly failed: ReadonlySet<string>;
31
+ /** The oldest question still waiting: the one the bar and the shortcuts are about. */
32
+ readonly pending: ApprovalEntry | undefined;
33
+ /** What the person allowed for this session, each to be taken back. Empty until there is one. */
34
+ readonly grants: readonly ApprovalGrant[];
35
+ readonly revokeGrant: (grantId: string) => Promise<void>;
36
+ /** Answers one question, once however often it is pressed. Resolves true when it was sent. */
37
+ readonly decide: (
38
+ entry: ApprovalEntry,
39
+ decision: ApprovalDecision,
40
+ details?: ApprovalDetails,
41
+ ) => Promise<boolean>;
42
+ }
43
+
44
+ export interface UseApprovalActionsInput {
45
+ readonly entries: readonly ApprovalEntry[];
46
+ readonly agentName: string;
47
+ /** Carries the answer to Gemies; rejects with `ApprovalExpiredError` when it is no longer open. */
48
+ readonly onDecide:
49
+ | ((
50
+ entry: ApprovalEntry,
51
+ decision: ApprovalDecision,
52
+ details?: ApprovalDetails,
53
+ ) => Promise<void>)
54
+ | undefined;
55
+ /** The answer is known here: show it now. */
56
+ readonly onSettled: (requestId: string, outcome: ApprovalOutcome, feedback?: string) => void;
57
+ /** Stops the running turn, for the answer that says so (`cancel`). */
58
+ readonly onStopTurn?: () => void;
59
+ /** Where the session's allowances are read and taken back; omitted, none are listed. */
60
+ readonly grants?: {
61
+ readonly agentId: string | undefined;
62
+ readonly conversationId: string | undefined;
63
+ readonly list:
64
+ | ((agentId: string, conversationId: string) => Promise<readonly ApprovalGrant[]>)
65
+ | undefined;
66
+ readonly revoke: ((agentId: string, grantId: string) => Promise<void>) | undefined;
67
+ };
68
+ }
69
+
70
+ /**
71
+ * The answering of the CLI's questions, shared by every place that shows them — the thread's row
72
+ * and the composer's bar — so a question answered in one is answered in both, and pressing it twice,
73
+ * or once in each, sends one answer.
74
+ */
75
+ export function useApprovalActions({
76
+ entries,
77
+ agentName,
78
+ onDecide,
79
+ onSettled,
80
+ onStopTurn,
81
+ grants: source,
82
+ }: UseApprovalActionsInput): ApprovalActions {
83
+ const [sending, setSending] = useState<ReadonlySet<string>>(() => new Set());
84
+ const [failed, setFailed] = useState<ReadonlySet<string>>(() => new Set());
85
+ // The guard is a ref: two presses in one frame both see the same render's state.
86
+ const inFlight = useRef(new Set<string>());
87
+
88
+ const decide = useCallback(
89
+ async (entry: ApprovalEntry, decision: ApprovalDecision, details?: ApprovalDetails) => {
90
+ const id = entry.requestId;
91
+ if (!onDecide || entry.outcome !== 'pending' || inFlight.current.has(id)) return false;
92
+ inFlight.current.add(id);
93
+ setSending((s) => mark(s, id, true));
94
+ setFailed((f) => mark(f, id, false));
95
+ try {
96
+ await onDecide(entry, decision, details);
97
+ onSettled(id, decision, details?.feedback);
98
+ if (decision === 'cancel') onStopTurn?.();
99
+ return true;
100
+ } catch (error: unknown) {
101
+ if (error instanceof ApprovalExpiredError) onSettled(id, 'expired');
102
+ else setFailed((f) => mark(f, id, true));
103
+ return false;
104
+ } finally {
105
+ inFlight.current.delete(id);
106
+ setSending((s) => mark(s, id, false));
107
+ }
108
+ },
109
+ [onDecide, onSettled, onStopTurn],
110
+ );
111
+
112
+ const pending = useMemo(() => firstPending(entries), [entries]);
113
+
114
+ // The allowances are read when this conversation has one to show: after the person allowed
115
+ // something for the session, or a question was answered by what they allowed earlier.
116
+ const [grants, setGrants] = useState<readonly ApprovalGrant[]>([]);
117
+ const allowed = entries.filter((e) => e.outcome === 'allow_session').length;
118
+ const { agentId, conversationId, list, revoke } = source ?? {};
119
+ useEffect(() => {
120
+ if (allowed === 0 || !list || !agentId || !conversationId) {
121
+ // Nothing to list: keep the same empty list, so nothing is drawn again for it.
122
+ setGrants((current) => (current.length === 0 ? current : []));
123
+ return;
124
+ }
125
+ let current = true;
126
+ list(agentId, conversationId).then(
127
+ (found) => current && setGrants(found),
128
+ // Not being able to list them is not a reason to hide the conversation.
129
+ () => current && setGrants((now) => (now.length === 0 ? now : [])),
130
+ );
131
+ return () => {
132
+ current = false;
133
+ };
134
+ }, [allowed, list, agentId, conversationId]);
135
+ const revokeGrant = useCallback(
136
+ async (grantId: string) => {
137
+ if (!revoke || !agentId) return;
138
+ try {
139
+ await revoke(agentId, grantId);
140
+ setGrants((current) => current.filter((g) => g.id !== grantId));
141
+ } catch {
142
+ // Still allowed, and still listed: the person can press it again.
143
+ }
144
+ },
145
+ [revoke, agentId],
146
+ );
147
+
148
+ return useMemo(
149
+ () => ({
150
+ entries,
151
+ agentName,
152
+ canAnswer: onDecide !== undefined,
153
+ sending,
154
+ failed,
155
+ pending,
156
+ grants,
157
+ revokeGrant,
158
+ decide,
159
+ }),
160
+ [entries, agentName, onDecide, sending, failed, pending, grants, revokeGrant, decide],
161
+ );
162
+ }
@@ -33,7 +33,7 @@ import {
33
33
  type ApprovalOutcome,
34
34
  parseApprovalRequest,
35
35
  parseApprovalResolved,
36
- stillPending,
36
+ settlePending,
37
37
  withApprovalOutcome,
38
38
  withApprovalRequest,
39
39
  } from './approvals';
@@ -447,8 +447,8 @@ export function useConversationStream({
447
447
  // A new send answers the old failure, whether it is the retry or a fresh
448
448
  // message: either way the card comes down.
449
449
  setFailedTurn(null);
450
- // The last turn's answered questions are history; one still waiting stays.
451
- setApprovals(stillPending);
450
+ // The last turn's questions are history: it is over, and none of them is waiting on anyone.
451
+ setApprovals([]);
452
452
  retryRef.current = null;
453
453
 
454
454
  // Everything the send is about to change, so a turn that produces no real
@@ -1237,7 +1237,9 @@ export function useConversationStream({
1237
1237
  const resolved = parseApprovalResolved(parsed);
1238
1238
  if (resolved) {
1239
1239
  setApprovals((prev) =>
1240
- withApprovalOutcome(prev, resolved.requestId, resolved.outcome),
1240
+ withApprovalOutcome(prev, resolved.requestId, resolved.outcome, {
1241
+ auto: resolved.auto,
1242
+ }),
1241
1243
  );
1242
1244
  }
1243
1245
  continue;
@@ -1608,6 +1610,13 @@ export function useConversationStream({
1608
1610
  // Settle only this turn's message ids, including when a new send has already
1609
1611
  // started in the same conversation. Error paths may have settled them first.
1610
1612
  settleAssistant(controller?.signal.aborted === true ? 'cancelled' : 'completed');
1613
+ // However the turn ended — answered, stopped, failed, the connection lost — the agent is no
1614
+ // longer waiting on any question it asked: none stays pressable. A newer turn's own
1615
+ // questions are not this one's to close.
1616
+ if (turnGenerationRef.current === turnGeneration) {
1617
+ const outcome = controller?.signal.aborted === true ? 'cancel' : 'ended';
1618
+ setApprovals((prev) => settlePending(prev, outcome));
1619
+ }
1611
1620
  // Retain this control while its ACK drains so repeated Stop remains deduplicated.
1612
1621
  // Local transport cleanup is required even after the thread has been replaced.
1613
1622
  if (turnControl) await turnControl.finish();
@@ -1718,9 +1727,14 @@ export function useConversationStream({
1718
1727
  }, [isLoading, setComposerPhase]);
1719
1728
 
1720
1729
  /** The person's own answer, shown at once; the stream's `alia.cli_permission_resolved` repeats it. */
1721
- const settleApproval = useCallback((requestId: string, outcome: ApprovalOutcome) => {
1722
- setApprovals((prev) => withApprovalOutcome(prev, requestId, outcome));
1723
- }, []);
1730
+ const settleApproval = useCallback(
1731
+ (requestId: string, outcome: ApprovalOutcome, feedback?: string) => {
1732
+ setApprovals((prev) =>
1733
+ withApprovalOutcome(prev, requestId, outcome, feedback ? { feedback } : {}),
1734
+ );
1735
+ },
1736
+ [],
1737
+ );
1724
1738
 
1725
1739
  /** Put the offer away. It wrote nothing, so there is nothing else to undo. */
1726
1740
  const dismissSuggestedNewConversation = useCallback(() => {