@steerable/agent-shell-web 0.12.8 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,249 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { LuMinimize2 } from 'react-icons/lu';
3
+ import { t } from '@/i18n';
4
+ import { hasHostBridge } from '@/lib/host-bridge';
5
+ import {
6
+ compactChat,
7
+ getChatContextStatus,
8
+ type ChatContextStatus,
9
+ type CompactChatOptions,
10
+ type CompactChatResult,
11
+ } from '@/lib/local-api';
12
+
13
+ export interface ContextUsagePillProps {
14
+ chatId: string;
15
+ messageCount: number;
16
+ isStreaming: boolean;
17
+ /** Optional latest in-memory turn usage when streaming just finished. */
18
+ livePromptTokens?: number;
19
+ liveCachedPromptTokens?: number;
20
+ onCompacted?: (result: CompactChatResult) => void;
21
+ }
22
+
23
+ function formatCompactCount(n: number): string {
24
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`;
25
+ if (n >= 1_000) return `${Math.round(n / 1_000)}k`;
26
+ return String(n);
27
+ }
28
+
29
+ function formatMegabytes(bytes: number): string {
30
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
31
+ }
32
+
33
+ export function ContextUsagePill({
34
+ chatId,
35
+ messageCount,
36
+ isStreaming,
37
+ livePromptTokens,
38
+ liveCachedPromptTokens,
39
+ onCompacted,
40
+ }: ContextUsagePillProps) {
41
+ const [status, setStatus] = useState<ChatContextStatus | null>(null);
42
+ const [open, setOpen] = useState(false);
43
+ const [focus, setFocus] = useState('');
44
+ const [compacting, setCompacting] = useState(false);
45
+ const [feedback, setFeedback] = useState<string | null>(null);
46
+ const containerRef = useRef<HTMLDivElement>(null);
47
+
48
+ const refreshStatus = useCallback(async () => {
49
+ if (!chatId || !hasHostBridge()) return;
50
+ try {
51
+ const next = await getChatContextStatus(chatId);
52
+ setStatus(next);
53
+ } catch {
54
+ // Ignore transient status fetch errors so composer toolbar never flickers.
55
+ }
56
+ }, [chatId]);
57
+
58
+ useEffect(() => {
59
+ if (messageCount === 0) {
60
+ setStatus(null);
61
+ return;
62
+ }
63
+ if (!isStreaming) {
64
+ void refreshStatus();
65
+ }
66
+ }, [chatId, messageCount, isStreaming, refreshStatus]);
67
+
68
+ useEffect(() => {
69
+ if (!open) return;
70
+ void refreshStatus();
71
+ const handlePointerDown = (event: PointerEvent) => {
72
+ if (
73
+ event.target instanceof Node &&
74
+ containerRef.current?.contains(event.target)
75
+ ) {
76
+ return;
77
+ }
78
+ setOpen(false);
79
+ };
80
+ window.addEventListener('pointerdown', handlePointerDown);
81
+ return () => window.removeEventListener('pointerdown', handlePointerDown);
82
+ }, [open, refreshStatus]);
83
+
84
+ if (!hasHostBridge() || messageCount === 0) {
85
+ return null;
86
+ }
87
+
88
+ const maxTokens = status?.maxContextTokens ?? 131_072;
89
+ const estTokens = Math.max(status?.estimatedTokens ?? 0, livePromptTokens ?? 0);
90
+ const maxBytes = status?.maxRequestBytes ?? 4_194_304;
91
+ const estBytes = status?.estimatedBytes ?? 0;
92
+ const promptTokens = livePromptTokens ?? status?.promptTokens ?? 0;
93
+ const cachedTokens = liveCachedPromptTokens ?? status?.cachedPromptTokens ?? 0;
94
+ const cacheHitPct =
95
+ promptTokens > 0 ? Math.min(100, Math.round((cachedTokens / promptTokens) * 100)) : null;
96
+
97
+ const tokenRatio = maxTokens > 0 ? Math.min(1, estTokens / maxTokens) : 0;
98
+ const byteRatio = maxBytes > 0 ? Math.min(1, estBytes / maxBytes) : 0;
99
+ const dominantRatio = Math.max(tokenRatio, byteRatio);
100
+ const dominantPct = Math.round(dominantRatio * 100);
101
+
102
+ const toneClass =
103
+ dominantRatio >= 0.85
104
+ ? 'border-red-500/40 bg-red-500/10 text-red-600 dark:text-red-400'
105
+ : dominantRatio >= 0.7
106
+ ? 'border-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-400'
107
+ : 'border-agent-border/60 bg-agent-muted/40 text-agent-muted-foreground hover:text-agent-foreground';
108
+
109
+ const barColor =
110
+ dominantRatio >= 0.85
111
+ ? 'bg-red-500'
112
+ : dominantRatio >= 0.7
113
+ ? 'bg-amber-500'
114
+ : 'bg-agent-primary';
115
+
116
+ const handleCompactNow = async () => {
117
+ if (compacting) return;
118
+ setCompacting(true);
119
+ setFeedback(null);
120
+ try {
121
+ const opts: CompactChatOptions = {};
122
+ if (focus.trim()) opts.focus = focus.trim();
123
+ const res = await compactChat(chatId, opts);
124
+ setFocus('');
125
+ await refreshStatus();
126
+ if (res.queuedOnActiveTurn) {
127
+ setFeedback(t('Compaction queued for the next step.'));
128
+ } else if (res.compacted > 0) {
129
+ setFeedback(t('Compacted {count} earlier messages.', { count: res.compacted }));
130
+ onCompacted?.(res);
131
+ } else {
132
+ setFeedback(t('Context is already compact.'));
133
+ }
134
+ } catch (err) {
135
+ setFeedback(err instanceof Error ? err.message : String(err));
136
+ } finally {
137
+ setCompacting(false);
138
+ }
139
+ };
140
+
141
+ return (
142
+ <div ref={containerRef} className="relative inline-flex items-center">
143
+ <button
144
+ type="button"
145
+ data-testid="context-usage-pill"
146
+ onClick={() => setOpen((prev) => !prev)}
147
+ title={t('Context window and payload usage')}
148
+ className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] leading-tight transition-colors ${toneClass}`}
149
+ >
150
+ <LuMinimize2 className="h-3 w-3 shrink-0 opacity-80" />
151
+ <span>
152
+ {formatCompactCount(estTokens)} · {dominantPct}%
153
+ </span>
154
+ </button>
155
+
156
+ {open && (
157
+ <div
158
+ data-testid="context-usage-popover"
159
+ className="absolute bottom-full left-0 z-50 mb-2 w-72 rounded-agent-lg border border-agent-border bg-agent-canvas p-3 text-xs shadow-lg"
160
+ >
161
+ <div className="font-medium text-agent-foreground">
162
+ {t('Context budget')}
163
+ </div>
164
+
165
+ <div className="mt-2 space-y-2">
166
+ <div>
167
+ <div className="flex items-center justify-between text-[11px] text-agent-muted-foreground">
168
+ <span>{t('Token window')}</span>
169
+ <span>
170
+ {formatCompactCount(estTokens)} / {formatCompactCount(maxTokens)} (
171
+ {Math.round(tokenRatio * 100)}%)
172
+ </span>
173
+ </div>
174
+ <div className="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-agent-muted">
175
+ <div
176
+ className={`h-full transition-all ${barColor}`}
177
+ style={{ width: `${Math.max(2, Math.round(tokenRatio * 100))}%` }}
178
+ />
179
+ </div>
180
+ </div>
181
+
182
+ <div>
183
+ <div className="flex items-center justify-between text-[11px] text-agent-muted-foreground">
184
+ <span>{t('Request body')}</span>
185
+ <span>
186
+ {formatMegabytes(estBytes)} / {formatMegabytes(maxBytes)} (
187
+ {Math.round(byteRatio * 100)}%)
188
+ </span>
189
+ </div>
190
+ <div className="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-agent-muted">
191
+ <div
192
+ className={`h-full transition-all ${barColor}`}
193
+ style={{ width: `${Math.max(2, Math.round(byteRatio * 100))}%` }}
194
+ />
195
+ </div>
196
+ </div>
197
+
198
+ {cacheHitPct !== null && (
199
+ <div className="flex items-center justify-between text-[11px] text-agent-muted-foreground">
200
+ <span>{t('Prompt cache hit')}</span>
201
+ <span>{cacheHitPct}%</span>
202
+ </div>
203
+ )}
204
+
205
+ {(status?.compactionCount ?? 0) > 0 && (
206
+ <div className="text-[11px] text-agent-muted-foreground">
207
+ {t('Auto-compacted {count} times in this chat', {
208
+ count: status?.compactionCount ?? 0,
209
+ })}
210
+ </div>
211
+ )}
212
+ </div>
213
+
214
+ <div className="mt-3 border-t border-agent-border/60 pt-2.5">
215
+ <label className="block text-[11px] text-agent-muted-foreground">
216
+ {t('Keep specific details (optional)')}
217
+ </label>
218
+ <input
219
+ type="text"
220
+ data-testid="compact-focus-input"
221
+ value={focus}
222
+ onChange={(e) => setFocus(e.target.value)}
223
+ placeholder={t('e.g. SQL schema and error codes')}
224
+ className="mt-1 w-full rounded-agent-md border border-agent-border bg-agent-card px-2 py-1 text-xs text-agent-foreground placeholder:text-agent-muted-foreground/60 focus:outline-none focus:ring-1 focus:ring-agent-primary"
225
+ />
226
+ <button
227
+ type="button"
228
+ data-testid="compact-now-btn"
229
+ disabled={compacting}
230
+ onClick={() => void handleCompactNow()}
231
+ className="mt-2 flex w-full items-center justify-center gap-1.5 rounded-agent-md bg-agent-primary px-2.5 py-1.5 text-xs font-medium text-agent-primary-foreground transition hover:bg-agent-primary/90 disabled:opacity-50"
232
+ >
233
+ {compacting ? t('Compacting context…') : t('Compact context now')}
234
+ </button>
235
+ {feedback && (
236
+ <div
237
+ role="status"
238
+ data-testid="compact-feedback"
239
+ className="mt-1.5 text-[11px] text-agent-muted-foreground"
240
+ >
241
+ {feedback}
242
+ </div>
243
+ )}
244
+ </div>
245
+ </div>
246
+ )}
247
+ </div>
248
+ );
249
+ }
@@ -0,0 +1,88 @@
1
+ import { useState } from 'react';
2
+ import { t } from '@/i18n';
3
+ import { getHostBridge, hasHostBridge } from '@/lib/host-bridge';
4
+
5
+ export interface MemorySaveNoticeBarProps {
6
+ refinementId: string;
7
+ scope?: 'user' | 'workspace' | 'tenant';
8
+ chatId?: string;
9
+ workspaceId?: string;
10
+ onEdit?: () => void;
11
+ onWithdrawn?: (refinementId: string) => void;
12
+ }
13
+
14
+ export function MemorySaveNoticeBar({
15
+ refinementId,
16
+ scope = 'workspace',
17
+ chatId,
18
+ workspaceId,
19
+ onEdit,
20
+ onWithdrawn,
21
+ }: MemorySaveNoticeBarProps) {
22
+ const [withdrawn, setWithdrawn] = useState(false);
23
+
24
+ const handleWithdraw = async () => {
25
+ const path = `/api/v2/memory/refinements/${encodeURIComponent(refinementId)}/withdraw`;
26
+ const body = {
27
+ ...(chatId ? { chatId } : {}),
28
+ ...(workspaceId ? { workspaceId } : {}),
29
+ };
30
+ if (hasHostBridge()) {
31
+ await getHostBridge()?.localBackend.request({ method: 'POST', path, body });
32
+ } else {
33
+ await fetch(path, {
34
+ method: 'POST',
35
+ headers: { 'Content-Type': 'application/json' },
36
+ body: JSON.stringify(body),
37
+ });
38
+ }
39
+ setWithdrawn(true);
40
+ onWithdrawn?.(refinementId);
41
+ };
42
+
43
+ if (withdrawn) {
44
+ return (
45
+ <div
46
+ data-testid="memory-notice-withdrawn"
47
+ className="mt-1.5 flex items-center gap-2 text-[11px] text-agent-muted-foreground"
48
+ >
49
+ <span>{t('Withdrawn from memory and blocked from re-learning.')}</span>
50
+ </div>
51
+ );
52
+ }
53
+
54
+ const label =
55
+ scope === 'user'
56
+ ? t('Remembered personal preference')
57
+ : t('Remembered project preference');
58
+
59
+ return (
60
+ <div
61
+ data-testid="memory-save-notice-bar"
62
+ className="mt-1.5 flex flex-wrap items-center gap-2 text-[11px] text-agent-muted-foreground"
63
+ >
64
+ <span>{label}</span>
65
+ <span>·</span>
66
+ {onEdit ? (
67
+ <button
68
+ type="button"
69
+ data-testid="memory-notice-edit"
70
+ onClick={onEdit}
71
+ className="underline hover:text-agent-foreground"
72
+ >
73
+ {t('Edit')}
74
+ </button>
75
+ ) : null}
76
+ <button
77
+ type="button"
78
+ data-testid="memory-notice-withdraw"
79
+ onClick={() => void handleWithdraw()}
80
+ className="underline hover:text-rose-600"
81
+ >
82
+ {t('Withdraw')}
83
+ </button>
84
+ </div>
85
+ );
86
+ }
87
+
88
+ export default MemorySaveNoticeBar;
@@ -211,6 +211,36 @@ interface MessageListProps {
211
211
  onSelectSuggestion?: (text: string) => void;
212
212
  }
213
213
 
214
+ const COMPACTED_SUMMARY_PREFIX = '[context compacted: earlier conversation summarized]';
215
+
216
+ function CompactionSummaryDivider({ content }: { content: string }) {
217
+ const [expanded, setExpanded] = useState(false);
218
+ const body = content.startsWith(COMPACTED_SUMMARY_PREFIX)
219
+ ? content.slice(COMPACTED_SUMMARY_PREFIX.length).trim()
220
+ : content;
221
+ return (
222
+ <div data-testid="compaction-divider" className="my-2">
223
+ <div className="flex items-center gap-2 text-[11px] text-agent-muted-foreground">
224
+ <div className="h-px flex-1 bg-agent-border/60" />
225
+ <button
226
+ type="button"
227
+ onClick={() => setExpanded((v) => !v)}
228
+ aria-expanded={expanded}
229
+ className="rounded-full border border-agent-border/60 bg-agent-muted/40 px-2.5 py-0.5 transition-colors hover:text-agent-foreground"
230
+ >
231
+ {t('Earlier conversation compacted')}
232
+ </button>
233
+ <div className="h-px flex-1 bg-agent-border/60" />
234
+ </div>
235
+ {expanded && body ? (
236
+ <div className="mt-1.5 rounded-agent-md border border-agent-border/60 bg-agent-muted/30 px-3 py-2 text-xs whitespace-pre-wrap text-agent-muted-foreground">
237
+ {body}
238
+ </div>
239
+ ) : null}
240
+ </div>
241
+ );
242
+ }
243
+
214
244
  export function MessageList({
215
245
  messages,
216
246
  isStreaming,
@@ -453,6 +483,11 @@ export function MessageList({
453
483
  {turn.userGroup.messages.length === 1 ? (
454
484
  internalTrigger(turn.userGroup.messages[0]) ? (
455
485
  null
486
+ ) : turn.userGroup.messages[0].content.startsWith(COMPACTED_SUMMARY_PREFIX) ? (
487
+ <CompactionSummaryDivider
488
+ key={turn.userGroup.messages[0].id}
489
+ content={turn.userGroup.messages[0].content}
490
+ />
456
491
  ) : (
457
492
  <UserMessage
458
493
  key={turn.userGroup.messages[0].id}
@@ -477,6 +512,10 @@ export function MessageList({
477
512
  {turn.userGroup.messages.map((msg, idx) => (
478
513
  internalTrigger(msg) ? (
479
514
  null
515
+ ) : msg.content.startsWith(COMPACTED_SUMMARY_PREFIX) ? (
516
+ <div key={msg.id} className="px-3 py-1">
517
+ <CompactionSummaryDivider content={msg.content} />
518
+ </div>
480
519
  ) : (
481
520
  <UserMessage
482
521
  key={msg.id}
@@ -152,10 +152,14 @@ function actionLabel(action: FailureAction): string {
152
152
  switch (action.kind) {
153
153
  case 'retry':
154
154
  return t('Continue');
155
+ case 'compact-and-retry':
156
+ return t('Compact context and continue');
155
157
  case 'network-diagnostics':
156
158
  return t('Network diagnostics');
157
159
  case 'open-model-settings':
158
160
  return t('Open model settings');
161
+ case 'open-license-settings':
162
+ return t('Manage license');
159
163
  case 'new-chat':
160
164
  return t('New chat');
161
165
  }
@@ -174,6 +178,8 @@ function causeSummary(detail: TurnFailureDetail | undefined, reason: string): st
174
178
  return t('The service reported its own failure.');
175
179
  case 'context_overflow':
176
180
  return t('The request exceeds the model window.');
181
+ case 'license':
182
+ return t('The system deployment license is expired or invalid.');
177
183
  case 'invalid_request':
178
184
  return t('The service rejected the request.');
179
185
  default:
@@ -193,6 +199,8 @@ function categoryLabel(kind: string | undefined): string {
193
199
  return t('Service error');
194
200
  case 'context_overflow':
195
201
  return t('Conversation too long');
202
+ case 'license':
203
+ return t('System license');
196
204
  case 'invalid_request':
197
205
  return t('Rejected request');
198
206
  default:
@@ -23,8 +23,10 @@ export { readTurnFailureDetail, readTurnFailureKind };
23
23
  /** One action a failed turn can offer. */
24
24
  export type FailureAction =
25
25
  | { kind: 'retry' }
26
+ | { kind: 'compact-and-retry' }
26
27
  | { kind: 'network-diagnostics' }
27
28
  | { kind: 'open-model-settings' }
29
+ | { kind: 'open-license-settings' }
28
30
  | { kind: 'new-chat' };
29
31
 
30
32
  /** Everything the card renders, derived from one failure. */
@@ -111,9 +113,19 @@ export function failurePresentation(
111
113
  case 'context_overflow':
112
114
  return {
113
115
  title: t('This conversation is too long for the model'),
114
- body: t('Start a new chat, or select Regenerate to try a different approach.'),
115
- primary: { kind: 'new-chat' },
116
- secondary: [{ kind: 'retry' }],
116
+ body: t('Compact earlier messages to free up space and continue, or start a new chat.'),
117
+ primary: { kind: 'compact-and-retry' },
118
+ secondary: [{ kind: 'new-chat' }, { kind: 'retry' }],
119
+ classified: true,
120
+ };
121
+ case 'license':
122
+ return {
123
+ title: t('Enterprise license expired or invalid'),
124
+ body: t(
125
+ 'New AI turns are paused until an administrator updates the license. Your chat history, files, and exports remain fully accessible.',
126
+ ),
127
+ primary: { kind: 'open-license-settings' },
128
+ secondary: [],
117
129
  classified: true,
118
130
  };
119
131
  case 'invalid_request':
@@ -110,6 +110,8 @@ function kindLabel(kind: string): string {
110
110
  return t('Service error');
111
111
  case 'context_overflow':
112
112
  return t('Conversation too long');
113
+ case 'license':
114
+ return t('System license');
113
115
  case 'invalid_request':
114
116
  return t('Rejected request');
115
117
  default: